Backend Engineer: Decoupling Core Domain Logic from Third-Party Connectors with Hexagonal Adapters in Go
When business rules in a Go (Golang) microservice import vendor SDKs directly—such as AWS SDK v2 structs, SQL driver rows, or third-party payment REST payloads—unit testing requires spinning up heavy network mocks, and swapping an external provider forces edits across dozens of domain files. As a Backend Engineer, I structure Go microservices around Hexagonal Architecture (Ports and Adapters) using consumer-defined Go interfaces, zero-dependency domain packages, and compile-time interface guards.
1. Consumer-Defined Domain Ports & Zero-Dependency Core Logic
In idiomatic Go hexagonal design, the internal/domain package defines pure value objects and narrow port interfaces without importing database/sql, net/http, or cloud SDKs. Concrete infrastructure adapters in internal/adapters implement those interfaces and verify compliance at compile time via var _ domain.QuoteRepository = (*PostgresQuoteRepo)(nil):
package domain
import (
"context"
"errors"
"time"
)
var ErrInsufficientInventory = errors.New("insufficient available inventory")
type PartQuote struct {
MPN string
UnitPriceCents int64
AvailableQty int64
QuotedAt time.Time
}
// Outbound Port defined by the domain consumer
type SupplierCatalogPort interface {
FetchBestQuote(ctx context.Context, mpn string, minQty int64) (PartQuote, error)
}
type OrderReservationPort interface {
SaveReservation(ctx context.Context, tenantID string, quote PartQuote, qty int64) (string, error)
}
type QuotingService struct {
catalog SupplierCatalogPort
reservation OrderReservationPort
}
func NewQuotingService(cat SupplierCatalogPort, res OrderReservationPort) *QuotingService {
return &QuotingService{catalog: cat, reservation: res}
}
func (s *QuotingService) ReservePartQuote(ctx context.Context, tenantID, mpn string, qty int64) (string, error) {
quote, err := s.catalog.FetchBestQuote(ctx, mpn, qty)
if err != nil {
return "", err
}
if quote.AvailableQty < qty {
return "", ErrInsufficientInventory
}
return s.reservation.SaveReservation(ctx, tenantID, quote, qty)
}
2. Resilient Outbound HTTP Adapters with Circuit Breakers & Context Deadlines
The concrete HTTP supplier adapter translates external JSON quirks, enforces per-call context.WithTimeout deadlines, and wraps calls in a circuit breaker before mapping responses into pure domain.PartQuote structs. Combine this pattern with our Hexagonal & Clean Architecture Microservices blueprint and Backend Engineer high-concurrency Go & PostgreSQL guide.
Need a Backend Engineer to refactor a coupled Go or Python codebase into clean Hexagonal Architecture? Book a 1-Day Engineering Sprint.