Skip to main content

Design Patterns That Matter

Learning objectives
  • Implement the patterns that recur in Go payment and commerce backends in their idiomatic Go shape, not their Java shape
  • Choose between functional options, config structs and builders for constructing clients and values
  • Integrate external PSPs with adapters and decorators that map errors correctly and stack resilience concerns in the right order
  • Model an order lifecycle as an explicit state machine and a fraud check as a rule chain
  • Use repository and unit of work to keep transactions in the domain's vocabulary, and argue the anemic-domain-model debate

TL;DR​

  • Patterns are names for solutions to recurring problems. In interviews, lead with the problem ("we integrate five PSPs with different error semantics") and then name the pattern (adapter + strategy).
  • Go's versions are lighter: a function type is often the whole strategy, functional options replace telescoping constructors, and middleware is the decorator everyone already uses.
  • Adapters are where PSP integrations succeed or fail: map statuses and errors explicitly and never map "unknown" to "approved" or "declined".
  • Decorators stack cross-cutting concerns (metrics, retries, circuit breakers); the stacking order changes behavior.
  • State machines make order and payment lifecycles explicit; a transition table plus optimistic locking beats status strings mutated anywhere.
  • Repository + unit of work keep persistence in domain terms and transactions atomic within one service; across services you need sagas and the outbox.
  • Anti-patterns to name: God object, service locator, and an anemic domain model where invariants matter (ledgers, wallets, orders).

Why it matters​

Bank and e-commerce backends share the same recurring forces: many external providers with incompatible APIs, money that must never be lost or duplicated, long-lived entities with lifecycles (orders, payments, disputes), rules that change weekly (fraud, promotions), and strict audit needs. Patterns give your team a shared vocabulary for those forces — "put it behind an adapter", "add a decorator", "that's a new rule in the chain" — so design discussions and reviews are short and precise.

They also have a cost: every pattern adds indirection. The architect's job is to apply them where the force is real and to stop them where it is not.

Core concepts​

PatternProblem in bank / e-commerceIdiomatic Go shape
Functional optionsPSP client with many optional knobs and safe defaultsfunc NewClient(url string, opts ...Option)
BuilderMulti-step construction of a validated value (payout batch)Builder struct with Build() (T, error)
FactoryPick a provider by market and methodfunc ProviderFor(...) (Provider, error)
StrategyInterchangeable providers, routing or fee rulesSmall interface or function type
AdapterEach PSP has its own types, statuses, errorsPackage per PSP satisfying a domain port
Decorator / middlewareMetrics, retries, breakers, auth, loggingWrapper with the same interface; func(http.Handler) http.Handler
Observer / pub-subReact to OrderPlaced without couplingIn-process bus after commit; broker + outbox across services
StateOrder and payment lifecyclesTransition table on the aggregate
Chain of responsibilityValidation and fraud rulesSlice of rules evaluated in order
RepositoryPersistence in domain vocabularyOne interface per aggregate
Unit of workAtomic changes across repositoriesDo(ctx, func(tx Tx) error) error
SpecificationComposable eligibility rules (BNPL, promotions)Generic Spec[T] with And/Or/Not

Creational patterns​

Functional options​

The problem: a PSP client needs a base URL (required) plus a timeout, retry count, logger, HTTP transport and TLS settings (optional, with safe defaults). Telescoping constructors (NewClient, NewClientWithTimeout, …) do not scale, and a zero-valued config struct cannot distinguish "not set" from "set to zero".

type Client struct {
baseURL string
httpClient *http.Client
timeout time.Duration
retries int
logger *slog.Logger
}

type Option func(*Client)

func WithTimeout(d time.Duration) Option { return func(c *Client) { c.timeout = d } }
func WithRetries(n int) Option { return func(c *Client) { c.retries = n } }
func WithLogger(l *slog.Logger) Option { return func(c *Client) { c.logger = l } }

func NewClient(baseURL string, opts ...Option) (*Client, error) {
c := &Client{
baseURL: baseURL,
timeout: 5 * time.Second, // conservative default for authorization calls
retries: 2,
logger: slog.Default(),
}
for _, opt := range opts {
opt(c)
}
if c.timeout <= 0 {
return nil, errors.New("psp: timeout must be positive")
}
c.httpClient = &http.Client{Timeout: c.timeout}
return c, nil
}

// Call site reads like configuration:
// client, err := psp.NewClient(cfg.URL, psp.WithTimeout(3*time.Second), psp.WithLogger(log))

Options shine for libraries and widely shared clients: new options can be added without breaking callers. For an internal service component configured once from environment variables, a plain Config struct with a Validate() method is simpler and makes all defaults visible in one place.

Builder​

A builder earns its keep when construction is multi-step and must end in a validated, immutable value — a bank payout batch, a settlement file, an ISO 20022 message. For ordinary structs, a literal plus a constructor is enough; Go does not need a builder per type.

type BatchBuilder struct {
bank string
valueOn civil.Date
lines []PayoutLine
errs []error
}

func NewBatchBuilder(bank string, valueOn civil.Date) *BatchBuilder {
return &BatchBuilder{bank: bank, valueOn: valueOn}
}

func (b *BatchBuilder) AddCredit(to Beneficiary, amount money.Money, ref string) *BatchBuilder {
if !amount.IsPositive() {
b.errs = append(b.errs, fmt.Errorf("line %d: amount must be positive", len(b.lines)+1))
}
b.lines = append(b.lines, PayoutLine{To: to, Amount: amount, Reference: ref})
return b
}

// Build validates the whole batch: totals, duplicate references, cut-off.
func (b *BatchBuilder) Build() (Batch, error) {
if len(b.lines) == 0 {
b.errs = append(b.errs, errors.New("batch has no lines"))
}
if dup := firstDuplicateReference(b.lines); dup != "" {
b.errs = append(b.errs, fmt.Errorf("duplicate reference %q", dup))
}
if err := errors.Join(b.errs...); err != nil {
return Batch{}, err
}
return Batch{Bank: b.bank, ValueDate: b.valueOn, Lines: slices.Clone(b.lines)}, nil
}

The other common Go use is the test data builder — see Testing Strategy.

Factory​

In Go, NewX constructors are the everyday factory: they enforce invariants and return a ready-to-use value. A factory that chooses an implementation at runtime is the one place where returning an interface is the point:

func ProviderFor(market Market, method MethodCode, cfg Config) (Provider, error) {
switch {
case method == MethodWallet && market == MarketVN:
return momo.New(cfg.MoMo), nil
case method == MethodCard:
return adyen.New(cfg.Adyen), nil
case method == MethodBankTransfer:
return virtualaccount.New(cfg.VA), nil
default:
return nil, fmt.Errorf("%w: %s/%s", ErrNoProvider, market, method)
}
}

Keep factories in the composition root or a small wiring package; domain code should receive the providers, not build them.

Behavioral and structural patterns​

Strategy​

The problem: several interchangeable algorithms behind one decision — which PSP to use, how to compute a fee, how to route a payment. Strategy puts each behind the same interface and selects at runtime.

type Router interface {
Pick(p *Payment) ProviderCode
}

// CostRouter sends domestic cards to the local acquirer (usually cheaper)
// and everything else to the global PSP.
type CostRouter struct{}

func (CostRouter) Pick(p *Payment) ProviderCode {
if p.Card.IssuerCountry == p.MerchantCountry {
return ProviderLocalAcquirer
}
return ProviderGlobalPSP
}

func (s *PaymentService) Authorize(ctx context.Context, p *Payment) (AuthResult, error) {
code := s.router.Pick(p)
provider, ok := s.providers[code]
if !ok {
return AuthResult{}, fmt.Errorf("%w: %s", ErrNoProvider, code)
}
return provider.Authorize(ctx, newAuthRequest(p))
}

When the strategy is a single stateless computation, a function type is the idiomatic Go strategy: type FeeFunc func(amount money.Money) money.Money. No interface, no struct.

Adapter​

Every PSP has its own request types, amount formats, status strings and error codes. An adapter translates one external API into your domain port, so nothing outside the adapter package ever sees provider types. In DDD terms this is an anti-corruption layer.

// Package acmepay adapts the (fictional) AcmePay API to payment.Provider.
type Adapter struct {
api *acmesdk.Client
}

var _ payment.Provider = (*Adapter)(nil)

func (a *Adapter) Authorize(ctx context.Context, req payment.AuthRequest) (payment.AuthResult, error) {
resp, err := a.api.CreateCharge(ctx, acmesdk.ChargeRequest{
Reference: string(req.PaymentID),
Amount: req.Amount.DecimalString(), // AcmePay wants "125000.00"
Currency: req.Amount.Currency().Code(),
Token: req.CardToken,
IdempotencyKey: req.IdempotencyKey,
})
if err != nil {
return payment.AuthResult{}, mapError(req.PaymentID, err)
}
return payment.AuthResult{ProviderRef: resp.ChargeID, Status: mapStatus(resp.Status)}, nil
}

func mapStatus(s string) payment.AuthStatus {
switch s {
case "succeeded":
return payment.AuthApproved
case "requires_action":
return payment.AuthChallenge // 3-D Secure step-up
case "declined":
return payment.AuthDeclined
default:
return payment.AuthUnknown // never guess approved or declined
}
}

func mapError(id payment.ID, err error) error {
var apiErr *acmesdk.APIError
switch {
case errors.Is(err, context.DeadlineExceeded):
// The charge may have gone through: the caller must reconcile, not retry blindly.
return &payment.UnknownOutcomeError{PaymentID: id, Cause: err}
case errors.As(err, &apiErr) && apiErr.Code == "insufficient_funds":
return payment.ErrInsufficientFunds
default:
return fmt.Errorf("acmepay: %w", err)
}
}

What a reviewer checks in an adapter: amount units and rounding, currency codes, idempotency key passed through, every status mapped (with a safe default), timeouts mapped to unknown outcome, and no provider types leaking into the domain. See Payments & Card Flows for the domain semantics being mapped.

Decorator and middleware​

A decorator wraps a value with the same interface and adds behavior before or after delegating. HTTP middleware is the decorator every Go developer already writes:

func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if id == "" {
id = uuid.NewString()
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
})
}

// Outermost first: recover from panics, then tag, log, authenticate, dedupe.
func newHandler(mux http.Handler) http.Handler {
return Recover(RequestID(AccessLog(Authenticate(Idempotency(mux)))))
}

The same shape decorates domain ports — metrics, retries, circuit breaking around a PSP provider:

type instrumented struct {
next payment.Provider
name string
latency *prometheus.HistogramVec
}

func (p instrumented) Authorize(ctx context.Context, req payment.AuthRequest) (payment.AuthResult, error) {
start := time.Now()
res, err := p.next.Authorize(ctx, req)
p.latency.WithLabelValues(p.name, "authorize", outcome(res, err)).Observe(time.Since(start).Seconds())
return res, err
}

func (p instrumented) Capture(ctx context.Context, ref string, amount money.Money) error {
start := time.Now()
err := p.next.Capture(ctx, ref, amount)
p.latency.WithLabelValues(p.name, "capture", outcome(payment.AuthResult{}, err)).Observe(time.Since(start).Seconds())
return err
}

Order matters. With metrics outermost you see breaker rejections and total latency including retries; with the breaker outside the retry, one logical call counts once toward the failure threshold; the per-attempt timeout sits inside the retry so each attempt has its own deadline. Retries of Authorize are only safe because the same idempotency key is reused (see Idempotency & Exactly-Once and Resilience Patterns).

A Go-specific trap: embedding the wrapped interface (type instrumented struct{ payment.Provider }) forwards every method automatically — convenient, but a method added to the interface later is forwarded un-instrumented without any compiler warning. For critical decorators, implement every method explicitly.

Observer and pub-sub​

The problem: when an order is placed, notifications, loyalty points, analytics and the warehouse all need to react — and PlaceOrder should not know about any of them.

  • In-process observer: handlers registered on a bus, called synchronously. Cheap, but only for side effects that may be lost or re-derived (cache invalidation, in-memory metrics).
  • Pub-sub across services: the event goes through a broker (Kafka, RabbitMQ). To avoid the dual-write problem (DB commit succeeds, publish fails), write the event to an outbox table in the same transaction and relay it (see Transactional Outbox & CDC).
type OrderPlaced struct {
OrderID order.ID
CustomerID customer.ID
Total money.Money
PlacedAt time.Time
}

type Handler[E any] func(ctx context.Context, evt E) error

type Bus[E any] struct {
handlers []Handler[E]
}

func (b *Bus[E]) Subscribe(h Handler[E]) { b.handlers = append(b.handlers, h) }

// Publish runs every handler and joins their errors so one failing
// subscriber does not starve the others. Call it only AFTER commit.
func (b *Bus[E]) Publish(ctx context.Context, evt E) error {
var errs []error
for _, h := range b.handlers {
if err := h(ctx, evt); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}

Classic bugs: publishing before commit (the e-mail goes out for an order that then rolls back), running observers inside the transaction (an SMTP timeout holds row locks), and spawning an unbounded goroutine per event. Subscribers to broker events must be idempotent because delivery is at-least-once. More in Event-Driven Architecture.

State (order state machine)​

Order and payment lifecycles are state machines whether or not you model them as one. Making them explicit stops "status string set from five places" bugs such as refunding an order that was never paid, or shipping one that was cancelled.

In Go, a transition table on the aggregate is usually clearer than the GoF version with one type per state:

type Status string

const (
PendingPayment Status = "PENDING_PAYMENT"
Paid Status = "PAID"
Fulfilling Status = "FULFILLING"
Shipped Status = "SHIPPED"
Delivered Status = "DELIVERED"
Cancelled Status = "CANCELLED"
Refunded Status = "REFUNDED"
)

type Event string

const (
EvPaymentCaptured Event = "payment_captured"
EvCancel Event = "cancel"
EvPickStarted Event = "pick_started"
EvHandedOver Event = "handed_over"
EvDelivered Event = "delivered"
EvReturnAccepted Event = "return_accepted"
)

var transitions = map[Status]map[Event]Status{
PendingPayment: {EvPaymentCaptured: Paid, EvCancel: Cancelled},
Paid: {EvPickStarted: Fulfilling, EvCancel: Refunded},
Fulfilling: {EvHandedOver: Shipped},
Shipped: {EvDelivered: Delivered},
Delivered: {EvReturnAccepted: Refunded},
}

func (o *Order) Apply(ev Event, at time.Time) error {
next, ok := transitions[o.Status][ev]
if !ok {
return fmt.Errorf("%w: %s in state %s", ErrInvalidTransition, ev, o.Status)
}
o.history = append(o.history, Transition{From: o.Status, To: next, Event: ev, At: at})
o.Status = next
return nil
}

Persist with optimistic concurrency (UPDATE orders SET status = $1, version = version + 1 WHERE id = $2 AND version = $3) so two consumers processing payment_captured and cancel concurrently cannot both win. Switch to the GoF State pattern (a type per state with its own methods) when behavior per state diverges heavily — for example, Cancel() voids an authorization in one state, issues a refund in another, and requests a carrier intercept in a third. The full domain treatment is in Order Management & State Machines.

Chain of responsibility (validation and fraud rules)​

The problem: a payment attempt passes through sanctions screening, velocity limits, amount limits, device and geo checks. Rules are added weekly by the risk team, must run in a defined order, and every decision needs reasons for audit.

type Decision int

const (
Allow Decision = iota
Review
Block
)

type Rule interface {
Name() string
Evaluate(ctx context.Context, a *PaymentAttempt) (Decision, string)
}

type Chain []Rule

// Evaluate runs rules in order and stops at the first Block. Decisions only
// escalate: a later rule can turn Review into Block but never into Allow.
func (c Chain) Evaluate(ctx context.Context, a *PaymentAttempt) (Decision, []string) {
final := Allow
var reasons []string
for _, r := range c {
d, why := r.Evaluate(ctx, a)
if d == Allow {
continue
}
reasons = append(reasons, r.Name()+": "+why)
final = max(final, d)
if final == Block {
break
}
}
return final, reasons
}

// Wiring: cheap and decisive rules first, expensive remote calls last.
var checks = Chain{
SanctionsListRule{list: sanctions},
AmountLimitRule{perTxn: money.MustNew(50_000_000, "VND")},
VelocityRule{store: counters, maxAttempts: 5, window: 10 * time.Minute},
DeviceRiskRule{client: riskAPI},
}

The GoF version links handlers with a next pointer; in Go a slice of rules is clearer and easier to reorder from configuration. HTTP middleware is the same idea applied to requests. See Fraud & Risk Systems for how such rule engines evolve toward ML scoring.

Persistence and domain patterns​

Repository​

A repository is a collection-like interface for one aggregate, expressed in domain terms. It hides SQL, ORMs and caching from the domain.

type OrderRepository interface {
Get(ctx context.Context, id order.ID) (*order.Order, error) // ErrNotFound if absent
Save(ctx context.Context, o *order.Order) error // ErrConflict on stale version
ListAwaitingPaymentBefore(ctx context.Context, cutoff time.Time, limit int) ([]*order.Order, error)
}

Rules of thumb: one repository per aggregate (not per table); query methods named after domain needs (ListAwaitingPaymentBefore), not Query(sql string) or Where(map[string]any); return domain objects, not rows; reporting and search queries belong in read models, not in the aggregate repository (see CQRS). A generic Repository[T] with FindAll usually leaks a query language and invites N+1 queries.

Unit of work​

A unit of work groups changes to several repositories into one atomic transaction. The idiomatic Go form is a callback, so commit and rollback cannot be forgotten:

type Tx interface {
Orders() OrderRepository
Payments() PaymentRepository
Outbox() OutboxWriter
}

type UnitOfWork interface {
Do(ctx context.Context, fn func(tx Tx) error) error
}

type PgUnitOfWork struct {
pool *pgxpool.Pool
}

func (u *PgUnitOfWork) Do(ctx context.Context, fn func(tx Tx) error) (err error) {
pgtx, err := u.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() {
if err != nil {
_ = pgtx.Rollback(ctx) // keep the original error; it is more useful
}
}()
if err = fn(pgTx{tx: pgtx}); err != nil {
return err
}
return pgtx.Commit(ctx)
}
// Use case: mark the order paid and record the event atomically.
err := s.uow.Do(ctx, func(tx Tx) error {
o, err := tx.Orders().Get(ctx, cmd.OrderID)
if err != nil {
return err
}
if err := o.Apply(order.EvPaymentCaptured, s.clock.Now()); err != nil {
return err
}
if err := tx.Orders().Save(ctx, o); err != nil {
return err
}
return tx.Outbox().Add(ctx, events.OrderPaid{OrderID: o.ID, Total: o.Total})
})

Two boundaries to respect: never make network calls (PSP, other services) inside the callback — they hold row locks for the call's duration — and a unit of work is local to one database. Atomicity across services needs a saga or similar (see Distributed Transactions).

Specification​

A specification is a composable, named business predicate. It helps when eligibility rules are combined in many ways, must explain which clause failed, or are assembled from configuration — BNPL eligibility, promotion targeting, KYC tier checks.

type Spec[T any] interface {
IsSatisfiedBy(v T) bool
}

type SpecFunc[T any] func(v T) bool

func (f SpecFunc[T]) IsSatisfiedBy(v T) bool { return f(v) }

func And[T any](specs ...Spec[T]) Spec[T] {
return SpecFunc[T](func(v T) bool {
for _, s := range specs {
if !s.IsSatisfiedBy(v) {
return false
}
}
return true
})
}

func Not[T any](s Spec[T]) Spec[T] {
return SpecFunc[T](func(v T) bool { return !s.IsSatisfiedBy(v) })
}

// Readable by a product owner:
var bnplEligible = And[Checkout](
MinTotal(money.MustNew(500_000, "VND")),
MaxTotal(money.MustNew(20_000_000, "VND")),
Not(ContainsCategory(CategoryGiftCards)),
CustomerKYCAtLeast(KYCVerified),
)

The cost: translating specifications into SQL to query by them tends to grow into a home-made query language. If a rule has one use and never changes shape, a plain func IsBNPLEligible(c Checkout) bool is better. Promotions engines are the classic home for this pattern — see Pricing & Promotions.

Anti-patterns​

God object​

OrderManager: 4,000 lines, 60 methods, 25 injected dependencies; pricing, payments, fulfilment, notifications and reporting in one type. Symptoms: every PR touches it, constant merge conflicts, tests need every dependency mocked, nobody knows its invariants. The fix is incremental: split by actor (SRP), give each use case its own type (PlaceOrder, CancelOrder, RefundOrder), and move rules into the aggregates they protect — see Code Smells & Refactoring.

The anemic domain model debate​

Fowler (2003) called a domain model whose objects hold only data, with all logic in services, an anti-pattern: you pay for an object model and get procedural code. The counter-position is strong in Go, where plain structs plus functions are idiomatic and many services are CRUD with light rules — a transaction script (Fowler's own name for the procedural style) is simpler and perfectly fine there.

The pragmatic answer interviewers want: put behavior where invariants live. Ledgers (postings must balance), wallets (no negative balance without an overdraft facility), and orders (valid transitions only) need the rule enforced in exactly one place, which means methods on the aggregate and unexported fields so nothing can bypass them.

// Anemic: any package can write Balance; the invariant lives in N services
// and one of them will forget it.
type AnemicWallet struct {
ID string
Balance int64
}

// Rich: the only way to change the balance enforces the invariant.
type Wallet struct {
id ID
balance money.Money
version int64
}

func (w *Wallet) Debit(amount money.Money) error {
if !amount.IsPositive() {
return ErrInvalidAmount
}
if w.balance.LessThan(amount) {
return ErrInsufficientFunds
}
w.balance = w.balance.Sub(amount)
return nil
}

In Go, encapsulation is per package, so the aggregate and its constructor live in a package that the rest of the code cannot reach into. See Domain-Driven Design and Double-Entry Ledger Design.

Service locator​

A global registry that code queries for its dependencies: registry.MustGet("payments").(PaymentService). It hides what a type depends on (the constructor signature lies), fails at runtime instead of compile time, requires type assertions, and forces tests to mutate global state — so they cannot run in parallel. Go-flavored variants: package-level var DB *sql.DB set in init, and stuffing the database handle or clients into context.Context. The fix is plain constructor injection wired in main (see SOLID in Go). Context values are for request-scoped data such as trace IDs and auth principals, not for dependencies.

Trade-offs​

PatternStrengthsWeaknessesChoose when
Functional optionsBackward-compatible, self-documenting call sitesMore code than a struct; defaults hidden in the constructorShared libraries and clients with many optional knobs
Config structAll settings and defaults visible; easy to load from envZero value ambiguity; breaking changes on renameInternal components configured once at startup
BuilderValidated, immutable result from multi-step assemblyCeremony for simple typesPayout batches, settlement files, test data
StrategySwap algorithms or providers without touching callersIndirection; selection logic must live somewhereReal variation on an axis (PSPs, routing, fees)
AdapterIsolates provider quirks; enables swapping PSPsOne more layer to maintain per providerEvery external integration
DecoratorCross-cutting concerns composable and testableOrdering bugs; embedded forwarding hides gapsMetrics, retries, breakers, auth, logging
Pub-sub via outboxDecoupled reactions; reliable deliveryEventual consistency; idempotent consumers requiredCross-service reactions to domain events
Explicit state machineInvalid transitions impossible; auditable historyUpfront modeling; migrations when states changeOrders, payments, disputes, KYC cases
Chain of rulesRules added independently; ordered, explainableOrder-dependent behavior; latency adds upValidation, fraud, eligibility pipelines
Repository + unit of workDomain-language persistence; atomic multi-aggregate writesAbstraction over SQL can hide performance issuesServices with real domain logic and invariants
SpecificationComposable, explainable rulesBecomes a query language if pushed to SQLPromotions, eligibility assembled from config

In practice​

How the patterns compose in a single payment request:

Practical guidance:

  • Start with the force, not the pattern. Two PSPs with similar APIs do not need a routing strategy; a third provider and a cost-routing requirement do.
  • Adapters are tested against recorded or sandbox responses, including the ugly ones: timeouts, HTTP 500 with a body, unknown status strings, duplicate webhook deliveries.
  • Keep the PSP call outside the database transaction. A common shape: transaction 1 creates the payment as PENDING with an idempotency key; call the PSP; transaction 2 records the outcome (or leaves it PENDING for reconciliation on unknown outcome).
  • Make state machines data. Keeping the transition table as data lets you render it as a diagram, test it exhaustively and review changes as a diff.
  • Name things after the pattern only when it helps. CostRouter and acmepay.Adapter are good; PaymentStrategyFactoryImpl is not.

Common pitfalls​

  • Adapter maps unknown statuses to "declined". Symptom: the customer is charged, the order is cancelled, and support tickets spike after a PSP adds a new status.
  • Retry decorator without idempotency keys. Symptom: rare double charges that correlate with PSP latency spikes.
  • Decorator order reversed. Symptom: metrics show far fewer failures than the PSP dashboard because retries hide them; or the circuit breaker never opens.
  • Observers called before commit. Symptom: confirmation e-mails and loyalty points for orders that do not exist.
  • Status mutated directly (o.Status = "SHIPPED") outside the state machine. Symptom: impossible states in the database; refunds on unpaid orders.
  • Unit of work spanning a PSP call. Symptom: lock waits and connection-pool exhaustion during PSP slowdowns, exactly at peak traffic.
  • Generic repositories with query builders. Symptom: slow endpoints from N+1 queries and missing indexes nobody can trace to a call site.
  • Pattern cargo-culting. Symptom: four files and two interfaces to add a field; new joiners take weeks to find where logic lives.

Interview angle​

  • Prompts: "Which design patterns do you use and why?", "How would you integrate a new PSP?", "How do you model an order lifecycle?", "How do you add fraud rules without redeploying everything?"
  • A strong answer frames each pattern by its force in the domain, shows the Go-idiomatic shape, and names the failure mode it prevents — for example: adapter per PSP with explicit status and error mapping including unknown outcome; decorators for metrics, breaker and retry with idempotency keys; order state machine with optimistic locking; outbox for events.
  • Expect follow-ups: "What happens if the PSP times out?", "Where do you put the transaction boundary?", "Rich or anemic domain model — which do you use?", "How do you test the state machine?" (exhaustively over the transition table).
  • Red flags: listing GoF patterns from memory without domain context, singletons and service locators presented as good practice, abstract factories for one implementation, or not knowing that decorator order matters.

Self-check​

1. When do you choose functional options over a config struct?

Functional options suit libraries and shared clients with many optional settings, where you want backward-compatible additions and readable call sites, and where "not set" must differ from "zero". A config struct suits internal components configured once from environment or files: all defaults are visible in one place and it is easy to validate and log. Many teams use a config struct internally and options only for reusable packages.

2. Why must a PSP adapter map unrecognized statuses and timeouts to "unknown"?

Because the money may or may not have moved. Mapping to "declined" can cancel an order the customer paid for; mapping to "approved" ships goods without payment. "Unknown" keeps the payment pending and triggers status polling or reconciliation, which is the only way to learn the truth. This is the single most important rule in payment adapters.

3. You stack metrics, circuit breaker, retry and per-attempt timeout around a PSP provider. In what order, and why?

From outside in: metrics, circuit breaker, retry, per-attempt timeout, adapter. Metrics outermost see the true end-to-end result including breaker rejections. The breaker outside retry counts one logical call per attempt sequence and can stop retry storms. The timeout inside retry gives each attempt its own deadline. Retries are only safe with a stable idempotency key, and the whole stack should still respect the caller's context deadline.

4. Why must in-process observers run after commit, and what do you use for cross-service events?

If observers run before or inside the transaction, they can act on changes that later roll back (an e-mail for a non-existent order) or hold locks while doing slow I/O. Run them after commit, and only for side effects that tolerate loss. For cross-service events, write the event to an outbox table in the same transaction and relay it to the broker, with idempotent consumers.

5. Transition table or GoF State pattern for an order lifecycle?

A transition table when states mainly differ in which events are allowed — it is data, easy to test exhaustively and to render as a diagram. The GoF State pattern (a type per state) when behavior per state differs substantially, such as Cancel() voiding an authorization, issuing a refund or requesting a carrier intercept depending on state. Both need optimistic locking when persisted.

6. What belongs in a repository interface, and what does not?

Belongs: load and save of one aggregate, a few domain-named queries the use cases need, and documented error semantics (ErrNotFound, ErrConflict). Does not belong: raw SQL or generic query builders, cross-aggregate reporting queries (use read models), transaction control (use a unit of work), and caching policy visible to callers.

7. Scenario: a teammate argues the wallet service should use plain structs and service functions because "anemic models are idiomatic Go". How do you respond?

Plain structs and functions are idiomatic for data-centric code, but a wallet has a critical invariant: the balance must not go negative except under an explicit overdraft rule, and every change must be recorded. If any function can write the balance field, every new code path must re-implement the check. Put Debit/Credit on the wallet with unexported fields, in its own package, so the invariant is enforced in one place — and keep transaction scripts for the CRUD-like parts.

8. Why is a service locator considered an anti-pattern, and what are its Go disguises?

It hides dependencies (constructors do not show what a type needs), moves wiring errors from compile time to runtime, requires type assertions, and forces tests to mutate shared global state. In Go it appears as package-level clients set in init, global registries, and dependencies stuffed into context.Context. Constructor injection wired in main fixes all of these.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Build a small payments module (in-memory adapters are fine) that exercises the core patterns:

  1. A payment.Provider port and two adapters for fictional PSPs with different status vocabularies and error formats. Map every status, map timeouts to UnknownOutcomeError.
  2. A CostRouter strategy selecting the provider, and decorators for metrics and retry; write a test proving retries reuse the same idempotency key.
  3. A payment state machine (PENDING → AUTHORIZED → CAPTURED → REFUNDED, plus FAILED and UNKNOWN) as a transition table, with a test that iterates over every state/event pair and asserts only listed transitions succeed.
  4. A fraud Chain with three rules (amount limit, velocity, blocked BIN) and reasons in the result.
  5. A unit of work that saves the payment and an outbox event atomically (use SQLite or Postgres via testcontainers).

Done when: tests cover a PSP timeout leading to a PENDING payment with no outbox "captured" event; a duplicate request with the same idempotency key returns the original result; an invalid transition returns ErrInvalidTransition; and you can explain the decorator order you chose.

Further reading​

  • Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1994).
  • Martin Fowler, Patterns of Enterprise Application Architecture (2002) — Repository, Unit of Work, Transaction Script, Domain Model, Service Layer.
  • Eric Evans, Domain-Driven Design (2003) — aggregates, repositories, anti-corruption layer; and Eric Evans and Martin Fowler, "Specifications" (paper).
  • Rob Pike, "Self-referential functions and the design of options" (blog post, 2014).
  • Dave Cheney, "Functional options for friendly APIs" (blog post, 2014).
  • Martin Fowler, "AnemicDomainModel" (bliki, 2003).
  • Mark Seemann, "Service Locator is an Anti-Pattern" (blog post, 2010).
  • Michael Nygard, Release It!, 2nd ed. (2018) — circuit breakers, timeouts, bulkheads around integrations.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).