How does Go's internal package rule work?
The go command enforces one rule on import paths. If a path contains an element named internal, only code inside the tree rooted at the parent of that internal directory can import it. The check runs when packages are loaded for a build, so an illegal import stops go build, go test and go vet before anything compiles. Nobody has to remember a convention, and code review doesn't have to catch it.
Take a module example.com/shop with a package at internal/billing. Its parent is the module root, so example.com/shop/cmd/api can import example.com/shop/internal/billing. Code in a separate module cannot. Nesting narrows access further. A package at internal/billing/internal/ledger can be imported by internal/billing and anything beneath it. If internal/orders tries to import it, the go tool reports that use of an internal package is not allowed and names both packages. That nested case is what makes the rule useful inside a monolith, because each domain can keep its own private subpackages.
The rule has limits you need to know:
- It is path-based. Moving a directory changes who has access. Any new package placed under the parent gets access automatically.
- It does nothing inside a package. All files in one package see each other's unexported identifiers.
- It does nothing at runtime. It is only a check on build-time imports.
- It restricts imports, not data. An exported function can return values of an internal type. Callers can store those values, call their exported methods, and pass them along without ever naming the internal package.
example.com/shop/ # module root (go.mod: module example.com/shop)
├── go.mod
├── cmd/api/main.go
└── internal/
├── billing/
│ ├── billing.go
│ └── internal/
│ └── ledger/ledger.go # parent of this internal/ is internal/billing
└── orders/orders.go
// cmd/api/main.go: ALLOWED
// cmd/api is under the module root, the parent of the top-level internal/.
import "example.com/shop/internal/billing"
// internal/billing/billing.go: ALLOWED
// billing is the parent of its own internal/, so it may use ledger.
import "example.com/shop/internal/billing/internal/ledger"
// internal/orders/orders.go: REJECTED
// orders is not inside the internal/billing tree.
import "example.com/shop/internal/billing/internal/ledger"
// $ go build ./...
// The build stops before compiling with an error that points at the
// import in internal/orders/orders.go and reports that use of internal
// package example.com/shop/internal/billing/internal/ledger is not allowed.
// A separate module, such as example.com/reports, gets the same error
// for any import of example.com/shop/internal/..., because it is
// outside the example.com/shop tree.
A module layout showing which imports the go tool accepts and which it rejects, including a nested internal directory that keeps a ledger package private to the billing domain.
What is a Go modular monolith layout and who should use it?
A Go modular monolith layout is a single module, with one go.mod at the root, arranged so the directory tree itself encodes the domain boundaries. Entrypoints live under cmd/<binary>. Each bounded context gets its own package under internal/, such as internal/billing and internal/orders. A domain's implementation details go one level deeper, in a nested internal/ that only that domain can import.
go.modcmd/api/: can importinternal/billingandinternal/ordersinternal/billing/: the public API, importable by anything in the moduleinternal/ledger/: importable only from withininternal/billing/...internal/postgres/: importable only from withininternal/billing/...
orders/: can importinternal/billing, but notbilling/internal/...internal/pricing/: importable only from withininternal/orders/...
The top-level internal/ keeps the whole tree private to the module. The nested internal/ keeps each domain's internals private from the other domains. The second rule is what makes this a modular monolith rather than a module with folders. Encapsulation is enforced by the compiler, not by convention. You get it without splitting into multiple modules with version and replace-directive overhead, and without the network calls and partial-failure handling that services bring.
The layout fits teams whose domains are emerging but already identifiable, all shipped as one deployable. It is most useful when several people work in different areas and accidental coupling is starting to hurt.
Avoid it in small teams or young codebases. When you don't yet know where the boundaries are, nested internal/ directories add ceremony around guesses. A flatter layout is cheaper to change until real seams appear.
┌─ module root (one go.mod) ───────────────────────────────────────────┐
│ │
│ ┌──────────────┐ │
│ │ cmd/api │ │
│ └──┬────────┬──┘ │
│ imports │ │ imports │
│ ┌───────────────┘ └─────────────┐ │
│ ▼ ▼ │
│ ┌─ internal/billing ───────┐ imports ┌─ internal/orders ────────┐ │
│ │ public API │◄──────────┤ public API │ │
│ │ ┌──────────────────────┐ │ │ ┌──────────────────────┐ │ │
│ │ │ internal/ledger │ │ │ │ internal/pricing │ │ │
│ │ │ internal/postgres │ │◄────X─────┤ │ │ │ │
│ │ └──────────────────────┘ │ blocked │ └──────────────────────┘ │ │
│ │ visible only to │by compiler│ visible only to │ │
│ │ internal/billing/... │ │ internal/orders/... │ │
│ └──────────────────────────┘ └──────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────┘
nothing outside the module can import any package under internal/
One module, one go.mod: cmd/api imports each domain's public package, orders may import internal/billing but not billing's nested internal packages, and the compiler rejects that import.
How do you design each domain package's public API?
Once you know where a boundary sits, treat internal/<domain> as a contract. Its exported identifiers are the only things other domains can depend on, so keep that set small: a Service type with its constructor, request and response DTOs such as PlaceOrderInput and Order, and perhaps one or two interfaces the domain needs from outside. Everything else goes one level down. In an orders package, the SQL queries, row structs and transaction helpers belong in internal/orders/internal/store. Under the internal rule, only code rooted at internal/orders can import that path. billing and shipping cannot reach the store even if they want to. The Service translates store rows into DTOs before returning them, so a schema change stays inside orders.
This only works if you organize by business capability. Compare the two approaches:
| Layout | Who must import whom | What internal can hide |
|---|---|---|
models/, handlers/, repositories/ |
Every layer imports the others across all domains | Almost nothing; each layer must stay visible to the whole module |
orders/, billing/, shipping/ |
Domains import each other's public API only | Each domain's storage, adapters and helpers |
With layer-based packages, repositories holds data access for every domain, so no domain owns it. You can't place it under a single domain's internal/ without breaking the others.
Nested internal hides only what you put there. If orders exports its store row type as a return value, or a Service method that accepts a raw *sql.Tx, callers will couple to those details anyway. Review every exported signature and ask whether you would accept a caller depending on it.
// internal/orders/orders.go (module example.com/shop)
package orders
import (
"context"
"database/sql"
// Only code under internal/orders may import this path. An import from
// internal/billing fails to build with "use of internal package ... not allowed".
"example.com/shop/internal/orders/internal/store"
)
// PlaceOrderInput is the request DTO other domains construct.
type PlaceOrderInput struct {
CustomerID string
SKU string
Quantity int
}
// Order is the response DTO. It is deliberately not store's row struct.
type Order struct {
ID string
CustomerID string
TotalCents int64
}
// Service is the domain's entry point. Its field is unexported, and no
// exported signature mentions a store type.
type Service struct{ q *store.Queries }
// NewService takes a plain *sql.DB so callers never need the store package.
func NewService(db *sql.DB) *Service { return &Service{q: store.New(db)} }
func (s *Service) PlaceOrder(ctx context.Context, in PlaceOrderInput) (Order, error) {
row, err := s.q.InsertOrder(ctx, in.CustomerID, in.SKU, in.Quantity)
if err != nil {
return Order{}, err
}
// Map row -> DTO here so a schema change stays inside orders.
return Order{ID: row.ID, CustomerID: row.CustomerID, TotalCents: row.TotalCents}, nil
}
The orders package (Go source) exports only a Service, its constructor, and two DTOs, while the SQL row types and queries in internal/orders/internal/store stay invisible to other domains.
How should domains call each other without import cycles?
The default is simple: a domain may import another domain's exported API, and the dependency arrow points one way. Cycles appear when two domains each need something from the other. If orders imports billing to charge a customer, and billing imports orders to look up order totals, the build fails with an import cycle.
The fix is a consumer-side interface. billing declares a small interface describing only what it needs, such as OrderLookup with a single OrderTotal(ctx, id) method. It does not import orders. The orders service satisfies that interface implicitly, because Go interfaces need no implements declaration. In cmd/server/main.go, the composition root constructs the concrete orders.Service and passes it into billing.NewService. Only main knows both concrete types, so the dependency graph stays acyclic.
This has a cost. A direct call becomes an interface, a constructor parameter and a wiring line. "Go to definition" now lands on an interface rather than the code that runs. Keep the pattern for edges that would otherwise form cycles, or where you actually need a test double. Do not use it everywhere. Declaring an interface beside every struct "for decoupling" doubles the surface area and makes navigation worse without removing any coupling.
Frequent cycle-breaking is also a warning sign. If orders and billing keep needing each other's internals, the boundary was probably drawn in the wrong place early on. You can keep extracting interfaces, which makes the wiring more and more awkward. The alternative is to admit the two areas form one domain and merge the packages. Merging is often the more honest fix.
// internal/billing/billing.go (consumer declares only what it needs; no import of orders)
package billing
import "context"
type OrderLookup interface {
OrderTotal(ctx context.Context, id string) (cents int64, err error)
}
type Service struct{ orders OrderLookup }
func NewService(orders OrderLookup) *Service { return &Service{orders: orders} }
// internal/orders/orders.go (satisfies billing.OrderLookup implicitly; never imports billing)
package orders
import "context"
type Service struct{ /* db handle, etc. */ }
func NewService() *Service { return &Service{} }
func (s *Service) OrderTotal(ctx context.Context, id string) (int64, error) {
return 4200, nil // placeholder: read the order and sum its lines
}
// cmd/server/main.go (composition root: the only place that knows both concrete types)
package main
import (
"example.com/shop/internal/billing"
"example.com/shop/internal/orders"
)
// Compile-time check that orders.Service still satisfies billing's interface.
var _ billing.OrderLookup = (*orders.Service)(nil)
func main() {
bill := billing.NewService(orders.NewService())
_ = bill // pass into HTTP handlers, workers, etc.
}
Three Go files showing billing declaring a one-method OrderLookup interface that orders.Service satisfies without either package importing the other, with the concrete wiring done only in cmd/server/main.go.
Where should shared code and database access live?
Keep internal/platform deliberately small: logger construction, config loading, the database connection pool, and maybe tracing setup. These are infrastructure concerns that every domain needs and none should own. The test for adding something is narrow: does it know nothing about any business concept? If a helper mentions an invoice or a user, it belongs in a domain.
Avoid common/ or util/. These packages start as a place for a string helper and grow into a shared library of half-domain types. Because every domain imports them, they become the coupling point that the domain split was meant to remove. A change to one helper now forces a rebuild and review of everything.
Each domain owns its tables and the queries against them. Put that code in a nested store package, such as internal/billing/internal/store. The internal rule then guarantees that only code under internal/billing can import it. Other domains reach billing data only through billing's public API.
The most common leak happens in the database, not in imports. A reporting query joins orders to invoices, or two domains write to the same table. Import boundaries stay clean and the compiler stays silent, but a schema change in billing now breaks orders at runtime. Treat a cross-domain join as a cross-domain call. Route it through the owning package or through a read model that a domain explicitly publishes.
A single go.mod also means one shared third-party dependency graph. Each module path resolves to one version for the whole build. If one domain upgrades a library to get a fix, every other domain that uses that library moves too, and must absorb any breaking changes in the same change set.
How do you enforce boundaries the compiler does not check?
The internal rule controls who can import from outside a subtree. It says nothing about imports inside it. internal/billing and internal/orders share the same parent, so each can import the other. The compiler only steps in when the two form a cycle. The rule has no way to express "billing may depend on orders, but orders must never depend on billing." Directional rules like that are exactly what keep a modular monolith from turning back into a tangle.
Since the toolchain won't enforce direction, enforce it in CI. go list reports the import graph for every package. A template such as go list -f '{{.ImportPath}} {{join .Imports " "}}' ./... prints each package followed by its direct imports, one line per package.
Next, keep a small rule file in the repository that lists which domains each domain may import. Treat that file as an architectural decision record. Changes to it go through review with the people who own the affected domains. A short script reads the go list output, keeps only the edges between your own internal/ packages, and fails the build on any edge the rule file does not allow. The approach is the same whether you write the check yourself or adopt an existing linter.
The check covers structure. Review covers intent. A reviewer should still ask whether a newly allowed edge belongs in the domain's public API or points to a misplaced responsibility.
The return is engineering time. A forbidden import caught in CI costs one line to remove. The same import found months later has picked up callers, tests, and assumptions, and removing it becomes a refactoring project.
How do you migrate a tangled project, and what are the alternatives?
Pick the domain with the fewest inbound callers and move it first, for example from pkg/billing to internal/billing/, with its implementation in a nested internal/ below that. Then run the build. Each compile error marks a dependency nobody documented: a handler reaching into a repository, or a report reading another domain's structs. Fix each one by adding a deliberate exported function or type to the domain's API. Do not add a wrapper that re-exports the internal type. That restores the old coupling under a new name and defeats the move.
This is disruptive. Every moved path breaks imports across the module, so make each move a single focused change and merge it quickly. Rebasing long-lived branches across a path change is painful.
| Layout | Isolation | Development cost | Iteration speed |
|---|---|---|---|
| Flat single package | None | Lowest at first, rises as the code grows | Fast until it tangles |
Layer-first (handlers/, models/) |
Separates layers, not domains | Low | Changes touch every layer |
| Nested-internal modular monolith | Compiler-enforced per domain | Moderate | Fast, with one build and atomic refactors |
| Multiple modules in one repo | Strong, with separate dependency graphs | Versioning, replace directives or a workspace setup |
Slower cross-module changes |
| Separate services | Strongest, including at runtime | Deployment, network contracts, observability | Slowest across boundaries |
The modular monolith does not lock you in, and it does not require a later split. If a domain's exported API is narrow and it owns its tables, extracting it as its own module only means changing import paths for its callers. Turning it into a service means replacing those calls with a client that has the same signatures. In both cases the change stays at the API edge, because callers never depended on anything else.
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 modular monolith layout, 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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.