How I structure Go microservices for change
When someone needs to change a service I’ve worked on, I want them to be able to find the relevant behavior and test their change locally. That includes me after a few months away. The service should give us enough context to understand its dependencies and the boundaries a change needs to preserve.
Hexagonal architecture gives me useful places to put those boundaries. Small interfaces keep the dependencies understandable. A common handler shape makes recurring work composable. Tests and architecture checks help keep those decisions in place as the service changes.
That structure matters when I delegate a change, too. A coding agent can work from the booking contract and the checks around it. I want its result to come with evidence I can inspect, and its unanswered business questions to remain visible.
- Extract a booking operation both callers can use
- Let the application define its dependencies
- Use a common contract for application handlers
- Pass time into the booking rule
- Add logging and metrics with decorators
- Connect both adapters in the composition root
- Choose tests that exercise the failure you care about
- Decide when a booking can be retried
- Check architectural boundaries in the build
- Prepare the context for an agent's change
- Review the change and the evidence
- The full presentation
- References
The handler and decorator approach owes a good deal to Three Dots Labs' Wild Workouts example. I've adapted the ideas to the services I work on. The delivery-booking example below uses neutral vocabulary to explain the structure; its booking rules are illustrative.
I'll assume you can read Go functions and interfaces. We'll follow a booking operation from an HTTP endpoint into a shared application handler, then consider how to delegate that extraction to a coding agent. Along the way, the booking's expiry rule gives us a few decisions that the package structure cannot settle.
Extract a booking operation both callers can use
Suppose an HTTP endpoint accepts a delivery booking. It decodes the request, checks whether a reservation hold is still valid, and writes a database document. All of that can fit in one handler. Then a broker consumer needs to accept bookings too.
I want both entry points to use the same booking behavior. Copying the validation into the consumer would give me two places to update the next time the rule changes. Calling the HTTP endpoint from the consumer would make an internal operation depend on transport details it does not need.
That gives the first extraction a specific purpose: move booking orchestration behind a callable application boundary. The HTTP endpoint keeps decoding requests and mapping results to responses. The broker consumer gets its own translation and delivery policy. Both call the booking operation.
Before moving the code, I write down what the existing endpoint actually does. What counts as an expired hold? Which failure does the caller see when storage is unavailable? What happens if the same booking arrives again? If the answers are unclear, moving code is premature. A cleaner package layout would leave the uncertainty intact.
I also establish a dependency check early: application code may not import a database adapter. Otherwise the extracted handler can grow a direct MongoDB dependency during the next change. The check gives the person making that change feedback about the boundary before it becomes a review comment.
An existing service may not follow boundaries that I am only now introducing. I use a baseline to record the accepted findings, refuse new ones, and remove entries as their violations are fixed. That lets us preserve the new boundary without making every change depend on a service-wide rewrite. The identity of each finding matters. Keeping the total number unchanged would still allow a new violation to replace an old one.
For example, these are two different findings under the same dependency rule:
Fixing the import in legacy.go while adding it in book_delivery.go leaves the count at one. The new finding must still fail the check. Once the old finding is fixed, I remove it from the baseline so that restoring the forbidden import fails too.

Let the application define its dependencies
For the booking operation, the application needs to record a delivery booking. It does not need to construct a BSON filter or know which MongoDB collection stores it.
I declare this interface beside the booking handler. The database adapter implements it using domain values at the boundary and its own persistence representation internally. Go's implicit interface implementation lets the concrete adapter satisfy the interface without importing the application package merely to declare that relationship. The Go code review guidance recommends placing interfaces with their consumers.fn:1
This is a driven port: something the application calls. The operation the HTTP adapter invokes is a driving port: a way to ask the application to do work. Both contracts belong to the application core. Cockburn's original Ports and Adapters description makes this ability to drive the application independently of its eventual UI and database central to the design.fn:2
The distinction between dependencies and calls takes a moment to get used to. At runtime, the booking handler calls the database adapter through an interface. In source code, the application refers to its own interface, while the adapter refers to domain types and provides the required method. The application has no import of the adapter.

A small arrangement might look like this:
There is no need to create all of these packages before they contain useful work. The import direction is what I preserve when I introduce a boundary.
I also avoid creating a general repository interface simply because the MongoDB implementation has several methods. That would make each caller depend on the provider's entire API. The booking handler asks for the behavior it needs. Another use case can have a different interface, even if one concrete adapter satisfies both.
Small does not have to mean one method. If a consumer needs a coherent set of operations with shared transaction semantics, splitting it into several unrelated interfaces can obscure that requirement. The consumer's contract determines the boundary.
HTTP structs can carry JSON tags, MongoDB documents can carry BSON tags, and the domain keeps its own values. This costs mapping code. I accept that cost when it prevents storage or transport changes from spreading into business rules, and I test the mappings because they can be wrong too.
For a small service whose work consists almost entirely of storing and returning records, I may keep a concrete implementation and a few functions for longer. Here, the second caller gives the booking boundary a job: keep the hold rule shared while each adapter handles its own protocol. I introduce the extra structure when I can explain what change or test it makes easier.
Use a common contract for application handlers
Once the booking operation has a home, I want its entry point to look familiar. I use this shape for application handlers:
The input describes one operation. The result has a concrete type, and failures use an error. A command with no result payload uses Void. A query uses its result type. That keeps logging and instrumentation wrappers independent of any particular booking request.
A function with the same signature could do this work. HandlerFunc lets such a function participate in the same composition. I use the interface for handlers that hold dependencies, with a consistent Handle method for their wrappers. Across several operations, that saves me from writing a separate wrapper API for each one. For a single short function, I would often keep the function.
I keep command and query intent visible in the application packages. A query returning bookings and a command recording one make different promises, even though both fit the handler interface. This separation is useful without separate read databases or event sourcing.
The common signature does not decide whether an operation is safe to repeat. A command may provide idempotency. A query may observe different data on the next attempt or consume enough resources that retrying it makes an outage worse. Those are properties of the operation and its dependencies.
Handler gives the wrappers a common invocation mechanism. The concrete bookDeliveryHandler coordinates the booking use case, delegating the expiry decision to the domain and recording the booking through its repository port:
type BookDelivery struct {
ID string
HoldUntil time.Time
}
type bookDeliveryHandler struct {
repository DeliveryBookingRepository
now func() time.Time
}
func NewBookDeliveryHandler(
repository DeliveryBookingRepository,
now func() time.Time,
) decorator.Handler[BookDelivery, decorator.Void] {
return bookDeliveryHandler{repository: repository, now: now}
}
func (h bookDeliveryHandler) Handle(
ctx context.Context, cmd BookDelivery,
) (decorator.Void, error) {
b, err := booking.NewDeliveryBooking(
cmd.ID, cmd.HoldUntil, h.now(),
)
if err != nil {
return decorator.Void{}, err
}
if err := h.repository.RecordDeliveryBooking(ctx, b); err != nil {
return decorator.Void{}, fmt.Errorf("record booking: %w", err)
}
return decorator.Void{}, nil
}
The HTTP adapter can decode its generated request type into BookDelivery and map the returned error to an HTTP response. A broker adapter can construct the same command from an event. Neither needs to reimplement the hold rule.
The constructor returns decorator.Handler to keep construction and decoration on the same public contract. Returning the concrete handler would also work; it satisfies the interface when passed to ChainDecorators. Go's usual guidance favors returning concrete types.fn:1 Here, I accept hiding any additional methods from callers. If they need more behavior, I reconsider that choice instead of adding type assertions around it.
Pass time into the booking rule
For the example, a booking is valid only while its hold has not expired. I want the boundary case to be explicit: at the deadline itself, the hold is expired.
var ErrInvalidID = errors.New("booking ID is required")
var ErrHoldExpired = errors.New("booking hold expired")
type DeliveryBooking struct {
id string
holdUntil time.Time
}
func NewDeliveryBooking(
id string, holdUntil, now time.Time,
) (DeliveryBooking, error) {
if id == "" {
return DeliveryBooking{}, ErrInvalidID
}
if !now.Before(holdUntil) {
return DeliveryBooking{}, ErrHoldExpired
}
return DeliveryBooking{id: id, holdUntil: holdUntil}, nil
}
func (b DeliveryBooking) ID() string { return b.id }
func (b DeliveryBooking) HoldUntil() time.Time { return b.holdUntil }
The application obtains time through its injected function. The composition root can supply time.Now; a test can supply a fixed instant. The domain imports time for its value type and comparisons, but never asks the environment what time it is.
That lets a test choose an instant just before the deadline, the exact deadline, and an instant afterward. There is no sleep and no dependence on how quickly a test machine happens to run.
There is still a business decision to make about time. The handler above checks the hold when it handles the request. If the intended rule is based on when an event was accepted elsewhere, the input and trust assumptions need to express that instead. Injecting a clock makes the choice testable; it does not choose the correct policy.
Add logging and metrics with decorators
A handler that records a booking still needs logging and metrics. Putting that work in every handler body makes ordinary changes noisy. Because the entry point has a consistent type, I can wrap it:
At construction, I choose the wrappers and their order:
A request enters logging, then metrics, then the booking handler. Results return through those wrappers in the opposite order. The operation can be tested with no wrappers, and the composition can be tested separately when order matters.

Suppose I later add a retry wrapper. Placing it inside the metrics wrapper makes that metric describe one overall invocation, including retries. Placing metrics inside retry makes it describe individual attempts. Either can be useful, but they answer different questions. If I need both, I instrument both explicitly.
The booking constructor leaves retry out until I've decided how to handle a repeated request, including one that arrives after the hold has expired.
Connect both adapters in the composition root
With the operation constructed, the composition root supplies it to both adapters:
Each adapter constructor accepts decorator.Handler[command.BookDelivery, decorator.Void]. The HTTP adapter translates its decoded request into command.BookDelivery; the broker adapter translates a booking event into that same command. The repository and clock are already supplied to the shared handler, so the adapters do not need them.
That reuse depends on both callers needing the same booking behavior. Concurrent calls also require the repository, clock and decorators to support overlapping invocations. Request-specific values stay inside each Handle call; a metrics wrapper that shares a mutable counter across calls must synchronize its updates.fn:3
Consider an in-process test with a fixed clock and a recording repository. Through each adapter, submit a booking whose hold has expired. Both should reject it without a repository call. With a fresh repository for each path, submit a valid booking and check the recorded ID and deadline. That scenario exercises both translations and the shared rule. The adapters can still map the rejection differently: an HTTP response and a broker processing outcome serve different callers.
Adding the broker path now requires its event mapping and consumer wiring. The domain rule and MongoDB mapping stay where they were. For the existing HTTP endpoint, I also keep tests that check its response contract. Calling the new handler successfully would leave that part unchecked.
The composition root also creates the database clients and other long-lived resources, passes them to adapters, and coordinates shutdown. A handler does not create a fresh client for every call. Workers need cancellation and a way to finish or abandon in-flight work before their dependencies close. A common Handle method can serve a worker's application operation; scheduling and recovery remain part of the worker's design.
Choose tests that exercise the failure you care about
The repository interface gives the booking test a small substitution point. A function type is enough to implement it:
The test can choose a storage error without starting MongoDB:
func TestBookDeliveryPreservesStorageFailure(t *testing.T) {
unavailable := errors.New("storage unavailable")
now := time.Date(2026, 10, 31, 10, 0, 0, 0, time.UTC)
repository := repositoryFunc(func(
context.Context, booking.DeliveryBooking,
) error {
return unavailable
})
handler := command.NewBookDeliveryHandler(
repository, func() time.Time { return now },
)
_, err := handler.Handle(context.Background(), command.BookDelivery{
ID: "booking-42", HoldUntil: now.Add(time.Minute),
})
if !errors.Is(err, unavailable) {
t.Fatalf("got %v, want storage failure", err)
}
}
I would also check that an expired hold never reaches the repository, and that a valid command records the expected domain value. These tests run real domain and application code. Only the persistence dependency is replaced.
They say nothing about whether the MongoDB adapter maps the ID to the correct field. For that, I need the real adapter and a real database. I use different test scopes to exercise different failure modes:
| Scope | What runs for real | Booking failure it can expose |
|---|---|---|
| Domain unit | Booking values and rules | A hold is accepted at its expiry instant |
| Use case | Domain and handler; function fake at the repository port | A storage failure is swallowed or invalid input reaches persistence |
| Adapter integration | One adapter and its backing dependency | The stored representation cannot be read back correctly |
| Component, in process | Service composition with selected dependencies substituted | Wiring supplies the wrong implementation or wrappers run in the wrong order |
| Component, out of process | Built service with provisioned dependencies | Configuration, startup, or the external request contract is wrong |
| End to end | Collaborating services | A neighboring consumer interprets the booking differently |
These are not six suites I generate for every handler. I choose the cheapest scope that actually exercises the risk. Index initialization can be checked by a focused integration test if that test runs the initializer; it does not inherently require launching the entire service.

Testcontainers lets the test process provision dependencies such as MongoDB or a broker.fn:4 The harness still needs isolated state and reliable cleanup. Running a real database does not make tests parallel-safe if they all write to the same collection with the same identities.
As the scope widens, the booking behavior can stay recognizable. I can exercise a repository contract against a fake and a real implementation, then run a relevant booking scenario through the built service. That gives the fake something concrete to stay compatible with. The fast test remains useful without pretending it covers the driver or deployment packaging.
In CI/CD Across Team Boundaries, I discuss the next boundary: a change that only becomes meaningful when several teams' services interact. The local service tests establish their own claims; a cross-service scenario checks the collaboration those tests cannot see.
Decide when a booking can be retried
A broker consumer adds another reason to distinguish a handler result from its delivery contract. Consider this sequence:
The application can return an error or a successful result. The surrounding consumer loop decides how that result affects retries and offset commits. A callback returning nil is not itself a broker acknowledgement. Recovery depends on how processing and offset persistence are coordinated.fn:5
Dropping malformed input, quarantining it, and retrying it indefinitely are different operational policies. A permanent booking rejection is also different from losing the connection to storage. I want the adapter's error mapping to state which outcome it chooses, with tests that exercise the consumer loop where necessary.
A database write can succeed while its acknowledgement is lost. The caller cannot tell whether another attempt will create a duplicate. The expiry rule makes the ambiguity more apparent: a first attempt might succeed before the deadline, then a retry after the deadline fails in the domain constructor before reaching storage.
Suppose we decide that an identical retry of an accepted booking should return the recorded success, even after the hold expires. A request using that identity with different input should fail as a conflict. A genuinely new booking must still pass the expiry check. This is one possible extension to the example's business contract.
The handler shown above does not implement that extension. It would need to recognize prior acceptance before applying first-attempt validation again. The persistence contract would also need to distinguish an identical repeat from a conflicting request and coordinate competing submissions atomically. An unprotected lookup followed by an insert would leave a race between callers. A stable ID by itself does not specify any of these outcomes.
I need to agree on those semantics with the people who own booking behavior, then test them against the repository implementation. The signature of RecordDeliveryBooking says little about duplicates or concurrent calls. Until the contract is agreed and implemented, I keep automatic retries disabled. The extraction should preserve existing behavior; changing its repeat semantics deserves a separate decision and tests.
Once the operation is safe to repeat under the agreed conditions, the consumer can retry eligible failures with a bounded policy. If recording the booking must also publish an event atomically from the application's perspective, that creates another consistency problem to design for, often with an outbox or another explicit coordination mechanism.
My backpressure article makes a related distinction between a required event path and a best-effort cache update. An optional projection can sometimes discard work. A booking acceptance path needs its own answer about which work may be lost and which must survive recovery.
Check architectural boundaries in the build
Once the booking handler exists, I want a build to tell me when application code imports MongoDB directly. Otherwise I am relying on every reviewer remembering the original extraction.
A service-specific analyzer can use Go's analysis API to inspect package imports, struct tags, and selected calls.fn:6 In my arrangement, the domain cannot import application or adapter packages, declare serialization tags, or call time.Now. Application code cannot import concrete adapters. The composition root is where those implementations meet.
The details of the check matter. An import alias must not hide a forbidden dependency. Checking a call's resolved object is stronger than searching source text for the spelling time.Now(). I also need to decide which files the rule covers: production code, generated code, and test harnesses have different roles. Those choices should be visible in the analyzer and its tests.
A build target can run a project-specific analyzer through go vet:fn:7
I test the analyzer against deliberately invalid packages and examples that should remain valid. A changed package path or a rule that reports every harmless import can make a check ineffective just as easily as a missing rule can.
This is the part of evolutionary architecture I find practical: identify a property worth preserving and give it repeatable feedback as the system changes.fn:8 An import rule covers a particular dependency decision. It cannot determine whether RecordDeliveryBooking represents the right business operation, whether the fake models its contract correctly, or whether the delivery policy is acceptable.
I still want the diagram, too. Generating a component diagram from the composed application avoids maintaining a second handwritten inventory of its wiring. After changing the composition, I regenerate it and review the diff. Its scope depends on what the generator discovers; an object graph does not explain every dynamic runtime interaction.
Prepare the context for an agent's change
I can now describe a bounded task to a coding agent:
Extract booking orchestration from the HTTP endpoint into an application handler that another adapter can call. Preserve the existing HTTP behavior and hold-expiry rule. Keep database details in the adapter. Report any unclear repeat behavior before changing it.
The agent still needs to find the current endpoint and its tests, follow its persistence dependency, and inspect the composition that connects them. The architecture check and its baseline explain which dependencies the change must preserve. A similar handler elsewhere in the repository can help with the extraction, provided its business policy is not copied along with its structure.
I use agentic enrichment to mean gathering relevant repository knowledge around a change. For the booking extraction, that means following the endpoint to its dependencies and finding the test that states what happens at expiry. The agent can read the import rule when deciding where to put the extracted code. Selecting and retrieving information as work progresses is also part of the context-engineering approach described by Anthropic.fn:9
A context note for this extraction might read:
The domain constructor rejects a hold at its deadline. Keep that decision in
booking.NewDeliveryBooking. The application handler should supply the time value and call the repository port. Preserve the HTTP adapter's error mapping. Identical retries after expiry remain an open policy decision.
In the repository, I would attach the inspected revision and links to the constructor and the existing HTTP test. The agent then has a reason to preserve the clock input as it moves the orchestration, and a specific policy question to leave open during the extraction.
I want to know where the agent's conclusions came from. Tooling can inspect an import, while a decision record may explain why that dependency was forbidden. A test gives evidence about the scenario it exercises. If the agent suggests that repeated bookings should be harmless, it has proposed a policy. Before that becomes implementation, I need agreement from the people responsible for booking behavior.
If a port or its callers change, an earlier summary may no longer describe the operation. I want the context to identify the repository revision and point to the relevant files and checks, so the agent can inspect them again when the code changes. A generated dependency graph helps locate code; its arrows cannot explain the meaning of an accepted booking.
In my experimental JAMES project, an architecture profile describes roles and their path bindings, along with conventions such as port ownership and decorator order. The profile helps an agent relate an application handler to its place in the repository. A declared rule only becomes enforced when a supported validator executes it and the workflow uses its result. You can start with repository instructions and existing build targets; a separate orchestration tool is optional.
Review the change and the evidence
For the booking extraction, I first ask the agent to identify the behavior already covered and the cases the change could disturb. Before moving code, I temporarily let an expired hold through and confirm that the relevant test fails. I restore the implementation before continuing with the extraction. That tells me the test detects this particular mistake; other faults still need their own checks.
During the move, suppose the agent puts a MongoDB call in the application handler. The import analyzer should reject it. The agent can repair the dependency by putting the contract beside its consumer and leaving the concrete adapter outside. That repair still needs the behavior tests: correct imports would allow an implementation that quietly discards a storage error.
For a move confined to orchestration, I start with the booking rule and handler tests. Changed mappings need adapter tests too. If the diff touches wiring or startup, I include the corresponding composition or built-service checks. The test scopes described earlier help me choose which parts must run for real.
The agent's report should let a reviewer follow a claim to the check that supports it. If it says HTTP behavior is unchanged, I want the relevant scenario and result. Commands and their results belong with that report, including anything that could not run. I also want the gaps stated plainly: a function-fake test gives me no evidence about a MongoDB index or a consumer's offset handling.
Tests and rules can need changes too, and I review those changes explicitly. A failing check should send the agent back to investigate; deleting an assertion or broadening the baseline needs a justification of its own. When the same agent writes the implementation and its tests, they can share the same mistaken interpretation. I compare the change with existing characterization tests and the agreed requirement, and keep the analyzer's own fixtures under test.

The extraction is finished when the protected booking behavior still holds, the consumer owns its repository contract, the application no longer imports its adapter, and the wiring is checked at an appropriate scope. Any resolved baseline entries leave with the change.
For the next caller, I can concentrate on its request mapping and delivery behavior. The booking operation remains shared. If that caller needs a different answer to the retry-after-expiry question, we can discuss the affected application and persistence contracts before changing them.
The full presentation
The accompanying talk, Architecture you can run, follows the approach through its diagrams and code examples. Use the slide controls or arrow keys to move through it.
References
[fn:1] The Go team. Go Code Review Comments: Interfaces. Guidance on placing interfaces in the package that consumes them.
[fn:2] Alistair Cockburn. Hexagonal architecture, the original article. Ports and adapters and testing an application independently of its eventual UI and database.
[fn:3] The Go team. The Go Memory Model. Synchronization requirements for data accessed concurrently by goroutines.
[fn:4] Testcontainers. Testcontainers for Go. Provisioning containerized dependencies from Go tests.
[fn:5] Apache Kafka. Message delivery semantics. Processing, offset persistence, and the failure window when writing to an external system.
[fn:6] Go tools. The analysis package. Analyzer contracts, package information, and diagnostics. Its analysistest package supports fixtures with expected diagnostics.
[fn:7] The Go team. The vet command. Running additional analyses through a custom vet tool.
[fn:8] Neal Ford, Rebecca Parsons, and Patrick Kua. Building Evolutionary Architectures. Incremental architectural change and fitness functions.
[fn:9] Anthropic. Effective context engineering for AI agents. Selecting relevant information and retrieving additional context as an agent works.