How does the Go internal package rule work?
The rule is defined on import paths. If a path contains an element named internal, only code inside the tree rooted at that element's parent directory may import it. The go command checks this when it resolves imports, so go build, go test and go vet all reject a violating import before any code is compiled.
Take a module example.com/shop with a package at example.com/shop/orders/internal/pricing. The parent of internal is orders, so these can import pricing:
example.com/shop/ordersexample.com/shop/orders/http- any other package under
orders/
A package at example.com/shop/billing sits outside that tree. If it imports pricing, the build fails with an error containing use of internal package example.com/shop/orders/internal/pricing not allowed, along with the file and line of the offending import. The rule also works across modules. Nothing outside example.com/shop can import example.com/shop/internal/..., whatever go.mod says.
This makes it a better boundary than a naming convention such as a _private suffix, a README, or a folder template. Those depend on every reviewer noticing every import, indefinitely. The internal check is part of the toolchain, so:
- It needs no configuration and no extra tooling.
- It runs on every developer's machine.
- It cannot be skipped without moving the package.
A shortcut import across a domain boundary becomes a build failure the author sees immediately, not a review comment that may or may not get written. It also forces the reverse decision into the open. If another domain needs the code, someone has to move it out of internal, and that move shows up as a deliberate, visible change in the diff.
# Minimal module: orders owns pricing; billing tries to reach into it.
mkdir -p shop/orders/internal/pricing shop/orders/http shop/billing && cd shop
go mod init example.com/shop
cat > orders/internal/pricing/pricing.go <<'EOF'
package pricing
func Total(cents int) int { return cents }
EOF
# Allowed: orders/http is inside the tree rooted at orders/, the parent of internal/.
cat > orders/http/handler.go <<'EOF'
package http
import "example.com/shop/orders/internal/pricing"
func Quote() int { return pricing.Total(1200) }
EOF
# Rejected: billing/ is outside orders/, so it cannot import orders/internal/...
cat > billing/billing.go <<'EOF'
package billing
import "example.com/shop/orders/internal/pricing"
func Charge() int { return pricing.Total(1200) }
EOF
go build ./orders/... # succeeds
go build ./billing/... # fails while resolving imports, before compiling
# Output resembles:
# billing/billing.go:3:8: use of internal package example.com/shop/orders/internal/pricing not allowed
A small module in which orders/http may import orders/internal/pricing, while billing is rejected by the go toolchain with a 'use of internal package ... not allowed' error.
What does a modular monolith layout with nested internal packages look like?
A layout for a shop with billing and shipping domains might look like this:
cmd/shop/main.go: process entry point and wiringinternal/billing/: the domain's public API (types, interfaces, constructors)internal/service/: business rulesinternal/store/: persistenceinternal/sql/: queries and migrations
shipping/: same shape, with its own nestedinternal/platform/: shared plumbing such as config, logging and database setup
The rule applies at two levels. The top-level internal/ is rooted at the module root, so every package in the module can import internal/billing, internal/shipping and internal/platform. External modules cannot. The nested internal/billing/internal/ is rooted at internal/billing, so only billing and its subpackages can import billing/internal/store. If shipping or cmd/shop tries to import it, the build fails.
This includes main.go. Because it cannot reach billing/internal/store, it cannot build billing's components itself. It has to call a constructor in billing, for example one that accepts a database handle and returns the domain's service. That keeps assembly logic inside each domain and limits main.go to connecting domains together.
The layout suits teams that run several business capabilities in one deployable and want each capability's internals to be private to the team that owns it. It has costs. Import paths become long, some file names repeat across trees (several store packages, for example), and moving around the code takes more steps. Each extra level of nesting adds to these costs, so add a level only when it hides something real.
+-----------------------------------------------------+
| cmd/shop/main.go -- wiring only, calls constructors |
+-----------------------------------------------------+
| | |
v v v
+------------------+ +------------------+ +-------------------+
| internal/billing | | internal/shipping| | internal/platform |
| public API: | | public API: | | config, logging, |
| types, ctors | | types, ctors | | database setup |
+------------------+ +------------------+ +-------------------+
| |
v v
+------------------+ +------------------+
| billing/internal | | shipping/internal|
| service/ | | service/ |
| store/ | | store/ |
| sql/ | | sql/ |
+------------------+ +------------------+
shipping ---X---> billing/internal/store build fails
main.go ---X---> billing/internal/store build fails
other module ---X---> shop/internal/... build fails
---> allowed import ---X---> blocked by the internal rule
main.go can reach each domain's public API and shared platform code, while each domain's nested internal/ tree can only be imported by that domain.
How do you design a domain's public API package?
The public API package is the only part of a domain other code should import, so keep it small enough to read in one sitting. You can use internal/billing itself as that package. A separate internal/billing/billingapi is useful when the implementation is large and you want contracts kept apart from wiring. In either case the package holds three things: an interface such as Service with methods like Charge and Refund, plain request and response structs such as ChargeRequest and ChargeResult, and a constructor. Repositories, SQL, retry helpers and pricing rules go under billing/internal/..., where only billing code can import them.
The constructor, for example New(deps Deps) Service, should return the interface rather than the concrete struct. Callers then depend on the method set, other domains can substitute a fake in tests, and you can restructure the implementation without breaking them. Keep Deps limited to what billing needs from outside, such as a clock, a logger and the narrow interfaces it consumes from other domains.
internal restricts import paths. It does not control which types appear in signatures. If ChargeResult has a field of type store.Invoice, or a method returns one, callers can still read its exported fields and call its methods. They just can't write the type's name. Your storage model has then become part of the contract.
To prevent this, define small API-specific types and map them at the boundary. The cost is boilerplate: near-duplicate structs and conversion functions that need updating when fields change. That cost is usually worth paying for types that cross domains. For values that are truly stable, such as an ID type or a currency code, define them once in the API package and use them internally too.
// internal/billing/billing.go: the only package other domains import.
package billing
import (
"context"
"database/sql"
"log/slog"
"time"
"example.com/shop/internal/billing/internal/store" // importable only under billing/
)
type InvoiceID string // small, stable value type owned by the API
type ChargeRequest struct {
CustomerID string
AmountCents int64
Currency string // e.g. "EUR"
}
// ChargeResult holds API fields only. Embedding store.Invoice here would
// leak the storage model to callers even though store sits under internal/.
type ChargeResult struct {
InvoiceID InvoiceID
ChargedAt time.Time
}
type Service interface {
Charge(ctx context.Context, req ChargeRequest) (ChargeResult, error)
Refund(ctx context.Context, id InvoiceID) error
}
// Deps uses only standard or API types, never store types.
type Deps struct {
DB *sql.DB
Log *slog.Logger
Now func() time.Time
}
// New returns the interface. The concrete type in service.go stays unexported.
func New(d Deps) Service { return &service{repo: store.NewRepo(d.DB), deps: d} }
// toResult is the boundary mapping: boilerplate that keeps store.Invoice private.
func toResult(inv store.Invoice) ChargeResult {
return ChargeResult{InvoiceID: InvoiceID(inv.ID), ChargedAt: inv.CreatedAt}
}
A billing API package that exposes a Service interface, plain request and result types, and a constructor returning the interface, and that maps the internal store.Invoice to an API type so the storage model never appears in a public signature.
How should domains communicate and be wired without import cycles?
Go refuses to compile a program whose packages import each other in a cycle. If billing imports orders and orders imports billing, the build fails. Between domains this is useful: the dependency graph must stay acyclic, so a circular dependency between two domains surfaces as a compile error the day someone introduces it.
The pattern that keeps the graph clean is the consumer-side interface. Instead of billing depending on the concrete orders.Service, billing declares the narrow interface it needs, such as an OrderReader with a single OrderTotal(ctx, orderID) method. billing owns that contract and does not need to know how orders are stored. Any type with a matching method set satisfies it implicitly, so orders does not import billing and does not need to know it exists.
Cross-domain calls should pass IDs and value types, not entity structs or ORM models. If a database model crosses a boundary, the consumer takes on the provider's schema, lazy-loading behavior, and mutation rules. A value type like Money or OrderID carries data without that coupling.
Wire everything in main or a dedicated composition-root package such as internal/app. That package constructs each domain's service and passes one into another, so domains never call each other's constructors.
Don't add an interface to every call by reflex. Each interface means "go to definition" lands on a method signature instead of the code. Introduce one when it breaks a cycle, narrows a dependency, or enables a test you actually need.
// Go. internal/billing/billing.go: billing declares only what it needs.
package billing
// OrderReader is owned by billing. orders satisfies it implicitly
// and never imports billing, so no cycle can form.
type OrderReader interface {
OrderTotal(ctx context.Context, id shared.OrderID) (shared.Money, error)
}
type Service struct{ orders OrderReader }
func NewService(o OrderReader) *Service { return &Service{orders: o} }
func (s *Service) Invoice(ctx context.Context, id shared.OrderID) error {
total, err := s.orders.OrderTotal(ctx, id) // an ID in, a value type out
if err != nil {
return err
}
_ = total // build the invoice from values, never from an orders DB model
return nil
}
// internal/orders/orders.go: a concrete service with no knowledge of billing.
func (s *Service) OrderTotal(ctx context.Context, id shared.OrderID) (shared.Money, error) {
var cents int64
err := s.db.QueryRowContext(ctx,
"SELECT total_cents FROM orders WHERE id = $1", string(id)).Scan(¢s)
return shared.Money{Cents: cents, Currency: "EUR"}, err
}
// cmd/shop/main.go: the composition root, the only place that calls constructors.
func main() {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
orderSvc := orders.NewService(db)
billingSvc := billing.NewService(orderSvc) // *orders.Service satisfies billing.OrderReader
_ = billingSvc // pass on to HTTP handlers, workers, etc.
}
The billing package defines a narrow consumer-side OrderReader interface that takes and returns IDs and value types, and main wires the concrete orders service into billing so neither domain imports or constructs the other.
What does internal not enforce, and how do you check it in CI?
The internal rule answers one question: may this package import that one? Everything else is outside it.
| Gap | Why the compiler allows it | How to catch it |
|---|---|---|
| Siblings inside a domain tree import each other | billing/internal/invoice and billing/internal/ledger share a parent, so both are visible |
Per-domain allowlist in CI |
internal/platform imports a domain |
It sits under the module root, which can see every domain | Import-graph script in CI |
| One domain queries another's tables | SQL strings are not imports | Ownership rules and review |
Keep internal/platform to logging, config loading, database setup, and shared error types. A common or util package erodes boundaries because it has no admission rule. Any helper without an obvious home ends up there. Once it imports a domain type, every domain that uses it depends on that domain too.
For the graph check, run go list -f over ./internal/..., printing .ImportPath with .Imports. Fail the build if a platform package imports a domain path, or if a domain imports anything from another domain except its API package. .Imports lists direct imports only. Use go list -deps when you also need to catch transitive leaks.
Assign each table to exactly one domain. Direct queries and cross-domain joins tie one domain to another's schema, so a column rename breaks code the owning team cannot see. Transactions that span domains are awkward. Either the owner exposes a function that accepts a caller's transaction handle, or you accept eventual consistency. Enforce both rules in review: changes to a domain's migrations need approval from its owners, and new cross-domain SQL needs a stated reason.
How do you migrate a flat Go project layout and test each domain?
Start with a domain that few other packages import, such as notifications or billing. Leaf domains surface fewer violations, so the first move stays small enough to review in one pull request.
- Define the public API first. Create the domain's top-level package and export only the types and functions callers actually use today. At this stage those functions can delegate to the existing flat code.
- Move the implementation under the nested internal directory. Relocate handlers, storage and helpers into
billing/internal/...and update imports within the domain. - Run
go build ./...and fix every error. Each "use of internal package not allowed" error marks a call site that bypasses the API. Either add a deliberate export to the public package or reroute the caller through an existing one. - Merge, then repeat with the next domain.
For testing, keep white-box unit tests next to the code in each internal package. There they can exercise unexported logic directly. In the domain's public package, add black-box tests in an external billing_test package. These tests import only the public path, so they fail to compile if the API lacks something a real caller needs. Running go test ./billing/... exercises one domain in isolation.
The compiler replaces a recurring manual audit. As an illustrative estimate, assume 50 cross-domain call sites and about ten minutes each to trace by hand. That is roughly eight hours per audit, and the result is out of date as soon as the next commit lands. A build produces the same list of violations in seconds, and the rule stops new ones from being merged.
When should you avoid this approach, and what are the alternatives?
Nested internal packages are not free. In a small codebase with a handful of handlers and one team, splitting the code into many domains adds ceremony: every cross-domain call needs an exported API, a wiring change, and a test double. Early in a product's life, when you do not yet know where the seams are, it is cheaper to stay flat. Moving code across an internal boundary later means rewriting imports, APIs, and tests at the same time.
Draw boundaries around stable business capabilities, such as billing or inventory. Do not draw them around the current org chart or around database tables. Teams reorganise and schemas get normalised, but the capabilities a business sells change slowly.
A top-level internal/ also blocks reuse by other modules. If another repository needs your money-handling code, you must expose it in a deliberate public package. That package becomes something you commit to versioning, not something you expose by accident.
| Approach | Enforcement | Development cost | Extraction readiness |
|---|---|---|---|
| Convention-only flat packages | None; relies on review | Lowest | Poor; coupling accumulates |
Nested internal/ per domain |
Compiler, plus CI for sibling imports | Moderate | Good for code structure |
| Separate Go modules per domain | Module and version boundaries | High; cross-module changes need coordinated releases | Better |
| Linters or import-graph tools alone | CI only, and only if the rules are maintained | Low to moderate | Depends on rule quality |
| Microservices | Network boundary | Highest; adds deployment, observability, and on-call load | Already extracted |
Even a clean modular monolith only rehearses extraction. In-process calls do not show you network latency or partial failure. They also let a single database transaction span two domains, which is an assumption that breaks once one of those domains sits behind a network call.
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 internal packages, 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.