Building Production Services
- Build an HTTP API on the standard library: Go 1.22+
ServeMuxpatterns, a middleware chain, strict JSON decoding and validation. - Configure a
pgxpoolfor production and write a transaction helper that retries serialization failures safely. - Stand up a gRPC service with interceptors, health checking and connection rebalancing.
- Instrument with
log/slogand OpenTelemetry (traces + metrics) without leaking PII or exploding metric cardinality. - Ship it: liveness vs readiness, graceful shutdown, and a minimal, non-root, multi-stage container image.
TL;DR
- The standard library is enough for most APIs: since Go 1.22,
mux.HandleFunc("POST /v1/payments/{id}/capture", h)gives method matching, wildcards andr.PathValue("id"). - Middleware is
func(http.Handler) http.Handler; order matters — recover outermost, then request ID, logging, tracing, auth, rate limiting, handler. - Every boundary has a limit: server timeouts (
ReadHeaderTimeoutat minimum),http.MaxBytesReader, clientTimeout, DBstatement_timeout, context deadlines. - Decode JSON strictly (
DisallowUnknownFields, single object, size cap) and validate explicitly; amounts are integers in minor units. - Size DB pools from the database's connection budget, not from request rate; retry only serialization/deadlock errors, and only for transactions with no external side effects.
slogJSON logs with request and trace IDs from context; OTel traces with parent-based sampling; metrics with low-cardinality attributes only./livezchecks the process;/readyzchecks it can serve (DB reachable, not draining). Never put a downstream PSP in liveness.- Image: multi-stage build,
CGO_ENABLED=0 -trimpath, distrolessstatic:nonroot, version stamped via-ldflags -X.
Why it matters
The difference between a Go program and a production service is mostly failure handling and operability:
- During a flash sale, a missing
ReadHeaderTimeoutlets slow clients hold thousands of connections (Slowloris); a missing client timeout lets one hung PSP connection pin goroutines until memory runs out. - A bank's incident review asks "which requests did this payment go through, and why did it take 4 s?" — answerable only with trace IDs in logs and spans across services.
- Regulators and security teams scan images for CVEs; a 900 MB image with a shell, package manager and root user produces findings and change tickets; a 15 MB distroless image produces almost none.
- Rolling deploys happen during business hours; without readiness and graceful shutdown, every deploy drops in-flight card authorizations.
Core concepts
Request lifecycle
Routing with net/http (Go 1.22+)
func (h *Handler) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/payments", h.createPayment)
mux.HandleFunc("GET /v1/payments/{id}", h.getPayment)
mux.HandleFunc("POST /v1/payments/{id}/capture", h.capturePayment)
mux.HandleFunc("POST /v1/payments/{id}/refunds", h.createRefund)
mux.HandleFunc("GET /livez", h.livez)
mux.HandleFunc("GET /readyz", h.readyz)
return Chain(mux,
Recover(h.log),
RequestID,
Logging(h.log, mux),
func(next http.Handler) http.Handler { return otelhttp.NewHandler(next, "payments-api") },
h.auth.Middleware,
)
}
func (h *Handler) getPayment(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") // wildcard value from the pattern
// ...
}
Pattern rules worth knowing:
"GET /v1/payments/{id}"matches GET and HEAD. A path that matches but with the wrong method gets an automatic 405 with anAllowheader.{id}matches one path segment;{rest...}matches the remainder; a trailing{$}matches only the exact path ("/{$}"is "only the root").- When two patterns match, the more specific wins; registering two patterns that conflict (neither more specific) panics at startup — good, you find out in CI.
- Since Go 1.23
r.Patternholds the matched pattern inside the handler, andmux.Handler(r)returns it ahead of time — ideal as a low-cardinalityroutelabel in logs and metrics.
Routers like chi remain fine choices (route groups, middleware per subtree), but a new service no longer needs one.
Server timeouts
srv := &http.Server{
Addr: ":8080",
Handler: h.Routes(),
ReadHeaderTimeout: 5 * time.Second, // Slowloris protection
ReadTimeout: 15 * time.Second, // whole request incl. body
WriteTimeout: 30 * time.Second, // must exceed your slowest handler
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 1 << 20,
}
The zero value has no timeouts at all. WriteTimeout is a hard cap that cuts responses off mid-write; for per-route budgets, prefer context.WithTimeout inside handlers or http.TimeoutHandler, and disable write deadlines per-request for streaming with http.NewResponseController(w).SetWriteDeadline.
Middleware
type Middleware func(http.Handler) http.Handler
// Chain applies middleware so that mws[0] is the outermost.
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
type ctxKey int
const requestIDKey ctxKey = iota
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 == "" || len(id) > 64 {
id = rand.Text() // crypto/rand, Go 1.24
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, id)))
})
}
// statusRecorder captures the status code; Unwrap keeps Flush etc. reachable.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Write(b []byte) (int, error) {
if s.status == 0 {
s.status = http.StatusOK
}
return s.ResponseWriter.Write(b)
}
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
// Logging writes one access-log line per request. The route label comes from
// mux.Handler, which returns the pattern that will match (empty if none).
func Logging(log *slog.Logger, mux *http.ServeMux) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
_, route := mux.Handler(r) // e.g. "GET /v1/payments/{id}"
rec := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
log.LogAttrs(r.Context(), slog.LevelInfo, "http request",
slog.String("method", r.Method),
slog.String("route", route),
slog.Int("status", rec.status),
slog.Duration("duration", time.Since(start)),
)
})
}
}
Why not read r.Pattern (Go 1.23) after next.ServeHTTP? The mux sets it on the *http.Request it receives; any middleware in between that calls r.WithContext (request ID, tracing, auth all do) hands the mux a copy, so the outer logger's r.Pattern stays empty. Inside handlers, r.Pattern is reliable. Keep the Recover middleware from Error Handling outermost, and log outside auth so 401s and 429s are logged too.
JSON decoding and validation
type createPaymentRequest struct {
OrderID string `json:"order_id"`
AmountMinor int64 `json:"amount_minor"` // integers only: 150000 = 150,000 VND
Currency string `json:"currency"`
}
var supportedCurrencies = map[string]bool{"VND": true, "USD": true}
type FieldError struct{ Field, Msg string }
func (e FieldError) Error() string { return e.Field + ": " + e.Msg }
func (r createPaymentRequest) Validate() error {
var errs []error
if r.OrderID == "" {
errs = append(errs, FieldError{"order_id", "required"})
}
if r.AmountMinor <= 0 {
errs = append(errs, FieldError{"amount_minor", "must be positive"})
}
if r.AmountMinor > 500_000_000 {
errs = append(errs, FieldError{"amount_minor", "exceeds single-payment limit"})
}
if !supportedCurrencies[r.Currency] {
errs = append(errs, FieldError{"currency", "unsupported"})
}
return errors.Join(errs...) // all problems at once, nil if valid
}
// decodeJSON reads exactly one JSON object of at most maxBytes, rejecting unknown fields.
func decodeJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64) (T, error) {
var v T
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBytes))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, fmt.Errorf("decode body: %w", err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return v, errors.New("body must contain a single JSON object")
}
return v, nil
}
func (h *Handler) createPayment(w http.ResponseWriter, r *http.Request) {
req, err := decodeJSON[createPaymentRequest](w, r, 64<<10)
if err != nil {
h.writeProblem(w, r, http.StatusBadRequest, "invalid body", err)
return
}
if err := req.Validate(); err != nil {
h.writeProblem(w, r, http.StatusUnprocessableEntity, "validation failed", err)
return
}
key := r.Header.Get("Idempotency-Key")
if key == "" {
h.writeProblem(w, r, http.StatusBadRequest, "Idempotency-Key header required", nil)
return
}
p, err := h.payments.Create(r.Context(), key, req.OrderID, req.AmountMinor, req.Currency)
if err != nil {
h.writeError(w, r, err) // domain error mapping, see Error Handling
return
}
writeJSON(w, http.StatusCreated, toPaymentResponse(p))
}
JSON rules for money APIs:
- Amounts as integers in minor units (
amount_minor) or as decimal strings ("150000.00") — never JSON floats. A JavaScript client can only represent integers exactly up to 2^53; IDs and large amounts beyond that must be strings. - When decoding arbitrary JSON into
any, numbers becomefloat64; usedec.UseNumber()to keep them asjson.Numberstrings. omitzero(Go 1.24) omits zero values includingtime.Time{};omitemptynever did for structs.- Go 1.25 ships an experimental
encoding/json/v2(GOEXPERIMENT=jsonv2) with stricter defaults and better performance; v1 remains the stable API.
Database access with pgx
func newPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.MaxConns = 20 // per pod; replicas × 20 must fit the DB budget
cfg.MinConns = 2 // avoid cold-start latency
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" // ms, server-side cap
cfg.ConnConfig.RuntimeParams["application_name"] = "payments-api"
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, err
}
pctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return pool, nil
}
type paymentRow struct {
ID string `db:"id"`
AmountMinor int64 `db:"amount_minor"`
Currency string `db:"currency"`
Status string `db:"status"`
}
func (r *Repo) ByOrder(ctx context.Context, orderID string) ([]paymentRow, error) {
rows, err := r.pool.Query(ctx,
`SELECT id, amount_minor, currency, status FROM payments WHERE order_id = $1`, orderID)
if err != nil {
return nil, fmt.Errorf("query payments for %s: %w", orderID, err)
}
return pgx.CollectRows(rows, pgx.RowToStructByName[paymentRow]) // closes rows
}
- Pool sizing: total connections = replicas ×
MaxConns(+ workers, migrations, admin) must stay under PostgreSQL'smax_connections, usually via PgBouncer. A pool larger than the DB can serve just moves queueing into the database. See PostgreSQL Deep Dive. - Native pgx vs
database/sql: native pgx is faster and exposes PostgreSQL features (COPY,LISTEN/NOTIFY, rich types);database/sqlwith thepgx/v5/stdlibdriver is portable and works with libraries expecting*sql.DB. Withdatabase/sql, always setSetMaxOpenConns,SetMaxIdleConnsandSetConnMaxLifetime— the default is unlimited open connections. - Query building: hand-written SQL plus
sqlc(type-safe generated code) is the common Go choice for financial systems; ORMs like GORM trade control over SQL and locking for convenience.
A retrying transaction helper
Under SERIALIZABLE (or with row locks in different orders), PostgreSQL aborts some transactions with SQLSTATE 40001 (serialization failure) or 40P01 (deadlock). The correct response is to retry the whole transaction.
// InTx runs fn in a transaction, retrying serialization failures and deadlocks.
// fn must have no side effects outside the database: it may run more than once.
func InTx(ctx context.Context, pool *pgxpool.Pool, opts pgx.TxOptions, fn func(pgx.Tx) error) error {
const maxAttempts = 4
for attempt := 1; ; attempt++ {
err := pgx.BeginTxFunc(ctx, pool, opts, fn) // commit on nil, rollback otherwise
if err == nil || attempt == maxAttempts || !retryable(err) {
return err
}
backoff := time.Duration(attempt*attempt) * 10 * time.Millisecond
select {
case <-time.After(backoff + rand.N(backoff)): // jitter (math/rand/v2)
case <-ctx.Done():
return ctx.Err()
}
}
}
func retryable(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && (pgErr.Code == "40001" || pgErr.Code == "40P01")
}
// Usage: a ledger transfer under SERIALIZABLE.
func (s *Ledger) Transfer(ctx context.Context, t TransferCmd) error {
return InTx(ctx, s.pool, pgx.TxOptions{IsoLevel: pgx.Serializable}, func(tx pgx.Tx) error {
if err := debit(ctx, tx, t.From, t.Amount); err != nil {
return err
}
if err := credit(ctx, tx, t.To, t.Amount); err != nil {
return err
}
return insertEntries(ctx, tx, t) // double-entry rows + idempotency key
})
}
The rule in the comment is the important part: no PSP calls, no Kafka publishes, no emails inside fn — those can't be rolled back and would repeat on retry. Use the outbox pattern for events. See Transactions & Isolation Levels and Double-Entry Ledger Design.
gRPC service
syntax = "proto3";
package payments.v1;
service PaymentService {
rpc CapturePayment(CapturePaymentRequest) returns (CapturePaymentResponse);
}
message CapturePaymentRequest {
string payment_id = 1;
}
message CapturePaymentResponse {
string status = 1;
}
type PaymentServer struct {
// Embedding the generated Unimplemented type keeps the server compiling
// when new RPCs are added to the proto.
paymentsv1.UnimplementedPaymentServiceServer
capture *app.CaptureService
}
func (s *PaymentServer) CapturePayment(ctx context.Context,
req *paymentsv1.CapturePaymentRequest) (*paymentsv1.CapturePaymentResponse, error) {
if req.GetPaymentId() == "" {
return nil, status.Error(codes.InvalidArgument, "payment_id is required")
}
if err := s.capture.Capture(ctx, req.GetPaymentId()); err != nil {
return nil, err // mapped to a status code by the error interceptor
}
return &paymentsv1.CapturePaymentResponse{Status: "CAPTURED"}, nil
}
func newGRPCServer(log *slog.Logger, ps *PaymentServer) (*grpc.Server, *health.Server) {
srv := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()), // traces + metrics
grpc.ChainUnaryInterceptor(
recoveryInterceptor(log),
ErrorInterceptor, // domain error -> codes.*, see Error Handling
),
// Force clients to reconnect periodically so long-lived HTTP/2
// connections rebalance across pods behind L4 load balancers.
grpc.KeepaliveParams(keepalive.ServerParameters{MaxConnectionAge: 5 * time.Minute}),
)
paymentsv1.RegisterPaymentServiceServer(srv, ps)
hs := health.NewServer()
healthpb.RegisterHealthServer(srv, hs)
hs.SetServingStatus("payments.v1.PaymentService", healthpb.HealthCheckResponse_SERVING)
return srv, hs
}
- Deadlines propagate automatically from client to server (
ctxin the handler carries them) — checkctx.Err()before expensive work. - Shutdown: set health to
NOT_SERVING, thensrv.GracefulStop()(with a timer that falls back toStop()). - gRPC uses long-lived HTTP/2 connections; with Kubernetes
Service(L4) load balancing, all requests from one client stick to one pod.MaxConnectionAge, client-side load balancing, or a service mesh/L7 proxy fix this. See RPC & gRPC.
Structured logging with log/slog
func newLogger(level *slog.LevelVar) *slog.Logger {
h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level})
return slog.New(contextHandler{h})
}
// contextHandler adds request and trace IDs from ctx to every record.
type contextHandler struct{ slog.Handler }
func (h contextHandler) Handle(ctx context.Context, r slog.Record) error {
if id, ok := ctx.Value(requestIDKey).(string); ok {
r.AddAttrs(slog.String("request_id", id))
}
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
r.AddAttrs(slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()))
}
return h.Handler.Handle(ctx, r)
}
// Without these, logger.With(...) would return the unwrapped inner handler.
func (h contextHandler) WithAttrs(as []slog.Attr) slog.Handler {
return contextHandler{h.Handler.WithAttrs(as)}
}
func (h contextHandler) WithGroup(name string) slog.Handler {
return contextHandler{h.Handler.WithGroup(name)}
}
// PAN never reaches a log line: only the last four digits are rendered.
type PAN string
func (p PAN) LogValue() slog.Value {
if len(p) < 4 {
return slog.StringValue("****")
}
return slog.StringValue("****" + string(p[len(p)-4:]))
}
- Always use the
...Contextmethods (log.InfoContext(ctx, ...)) so the handler can add IDs. - A
slog.LevelVarlets an admin endpoint switch to DEBUG temporarily without a restart. - Redact at the type level (
LogValuer) — PCI DSS forbids storing full PANs in logs; see Compliance: PCI DSS, KYC/AML, Data Protection. slog.NewMultiHandler(Go 1.26) fans out to several handlers, e.g. JSON to stdout plus an audit sink.
OpenTelemetry traces and metrics
func setupTelemetry(ctx context.Context, service, version string) (func(context.Context) error, error) {
res, err := resource.New(ctx, resource.WithAttributes(
attribute.String("service.name", service),
attribute.String("service.version", version),
))
if err != nil {
return nil, err
}
traceExp, err := otlptracegrpc.New(ctx) // endpoint from OTEL_EXPORTER_OTLP_ENDPOINT
if err != nil {
return nil, err
}
tp := sdktrace.NewTracerProvider(
sdktrace.WithBatcher(traceExp),
sdktrace.WithResource(res),
// Keep the caller's decision; sample 10% of new traces.
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(0.1))),
)
metricExp, err := otlpmetricgrpc.New(ctx)
if err != nil {
return nil, err
}
mp := sdkmetric.NewMeterProvider(
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExp)),
sdkmetric.WithResource(res),
)
otel.SetTracerProvider(tp)
otel.SetMeterProvider(mp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{}, propagation.Baggage{}))
return func(ctx context.Context) error { // call during shutdown to flush
return errors.Join(tp.Shutdown(ctx), mp.Shutdown(ctx))
}, nil
}
Instrumenting a use case:
var (
tracer = otel.Tracer("gitlab.bank.internal/payments/internal/payment/app")
meter = otel.Meter("gitlab.bank.internal/payments/internal/payment/app")
captures, _ = meter.Int64Counter("payments.captures",
metric.WithDescription("Capture attempts by outcome"))
)
func (s *CaptureService) Capture(ctx context.Context, id string) (err error) {
ctx, span := tracer.Start(ctx, "CaptureService.Capture",
trace.WithAttributes(attribute.String("payment.id", id))) // fine on spans
defer func() {
outcome := "ok"
if err != nil {
outcome = errorKind(err) // "declined", "timeout", ... (bounded set)
span.RecordError(err)
span.SetStatus(codes.Error, outcome)
}
// Metrics get only low-cardinality attributes: never payment or user IDs.
captures.Add(ctx, 1, metric.WithAttributes(attribute.String("outcome", outcome)))
span.End()
}()
return s.capture(ctx, id)
}
- Wrap outbound HTTP clients with
otelhttp.NewTransportso trace context propagates to the PSP gateway and other services. - Cardinality: each unique attribute combination is a time series.
payment_idon a metric creates millions of series and takes down Prometheus; put it on spans and logs instead. - Export via an OpenTelemetry Collector sidecar/daemonset: the app speaks OTLP; the collector handles batching, tail sampling (keep all error traces), and fan-out to Tempo/Jaeger, Prometheus and Loki.
- The Observability & SLOs page covers what to measure (RED/USE, SLOs, burn-rate alerts).
Health, readiness and startup
func (h *Handler) livez(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) // process is up and serving HTTP; no dependency checks
}
func (h *Handler) readyz(w http.ResponseWriter, r *http.Request) {
if h.draining.Load() {
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
defer cancel()
if err := h.pool.Ping(ctx); err != nil {
http.Error(w, "database unavailable", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
| Probe | Question | Should check | Must not check |
|---|---|---|---|
| Liveness | Is the process wedged? Restart it? | That the HTTP server responds | Database, PSP, Kafka — a DB outage would restart every pod |
| Readiness | Should traffic be routed here now? | Draining flag, DB reachable, caches warmed | Slow or optional dependencies (degrade instead) |
| Startup | Has it finished booting? | Migrations checked, config loaded | — |
Serve probes on the main listener (they then also prove the server works) or on a separate admin port together with net/http/pprof — never expose pprof publicly.
Graceful shutdown
The full sequence (fail readiness → wait for endpoint removal → srv.Shutdown → stop consumers → flush telemetry → close pools) and an errgroup-based run function are in Concurrency Patterns. For this service add: hs.SetServingStatus(..., NOT_SERVING) and GracefulStop for gRPC, and the telemetry shutdown(ctx) last so the final spans are exported.
Outbound HTTP clients
func newPSPHTTPClient() *http.Client {
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = 200
t.MaxIdleConnsPerHost = 50 // default is 2: far too low for one busy upstream
t.IdleConnTimeout = 90 * time.Second
t.TLSHandshakeTimeout = 5 * time.Second
t.ResponseHeaderTimeout = 10 * time.Second
return &http.Client{
Transport: otelhttp.NewTransport(t),
Timeout: 15 * time.Second, // overall cap; the request ctx can be shorter
}
}
Always defer resp.Body.Close() and drain bodies you don't read (io.Copy(io.Discard, resp.Body)) so connections are reused. Retries need idempotency keys (see Resilience Patterns).
Container image
# syntax=docker/dockerfile:1
FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
ARG VERSION=dev
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux go build -trimpath \
-ldflags="-s -w -X main.version=${VERSION}" \
-o /out/payments-api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/payments-api /payments-api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/payments-api"]
- Multi-stage: the toolchain stays in the build stage; the final image holds one static binary, CA certificates and timezone data (both included in distroless
static). CGO_ENABLED=0gives a static binary that runs onstatic/scratchimages. If you need cgo (some HSM or Oracle drivers), usedistroless/baseand a matching libc.-trimpathremoves local paths;-s -wstrips symbol tables (smaller image;pprofsymbolisation still works from the Go runtime's own tables).-X main.version=...stamps the version;debug.ReadBuildInfo()also exposes the VCS revision.nonrootuser, read-only root filesystem in the pod spec, no shell — fewer CVE findings and less attack surface.- Runtime env:
GOMEMLIMITfrom the memory limit (see Memory, GC & Escape Analysis); leaveGOMAXPROCSunset on Go 1.25+ so it follows the CPU limit.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
net/http ServeMux (1.22+) | Zero dependencies, method + wildcard routing | No route groups; middleware composition is manual | Most services |
chi | Groups, per-route middleware, net/http compatible | One dependency | Larger APIs with many route groups |
gin / echo | Batteries included, popular | Own context type; less idiomatic with net/http middleware | Teams already standardised on them |
| Native pgx | Fast, full PostgreSQL feature set | PostgreSQL-only API | PostgreSQL shops (most fintech) |
database/sql + driver | Portable, standard interfaces | Lowest-common-denominator types | Multiple databases, library compatibility |
sqlc | Type-safe, SQL stays visible | Codegen step | Financial queries you must review |
| ORM (GORM) | Fast CRUD | Hidden queries, locking surprises | Admin back-offices, not ledgers |
| REST/JSON | Universal clients, easy debugging | Weaker contracts | Public and partner APIs |
| gRPC | Contracts, streaming, deadline propagation | L4 load-balancing issues, browser support via proxies | Internal service-to-service |
slog | Standard library, fast enough, structured | Fewer features than zap/zerolog | Default for new services |
| OpenTelemetry | Vendor-neutral, one SDK for traces/metrics/logs | Setup verbosity | Default; export to any backend |
In practice
A production-readiness checklist for a Go payment service:
- Server timeouts set; request bodies capped; client timeouts and
MaxIdleConnsPerHostset. - Every handler and DB call uses the request context;
statement_timeoutconfigured. - Strict JSON decoding; integer minor units; explicit validation with field errors.
- Idempotency keys on all money-moving POSTs (see Idempotency & Exactly-Once).
- Domain errors mapped once at the edge; panics recovered and counted.
- JSON logs with request/trace IDs; PAN and secrets redacted by type.
- Traces across HTTP, gRPC, DB and Kafka; RED metrics per route with bounded labels.
-
/livez,/readyz, startup probe; pprof on an internal admin port. - Graceful shutdown within the grace period; outbox for events.
- Distroless non-root image, version-stamped, scanned in CI;
GOMEMLIMITset.
Common pitfalls
http.ListenAndServe(":8080", mux)in production — no timeouts at all.http.Get/http.DefaultClientfor upstream calls — no timeout; one hung PSP connection hangs the goroutine forever.- Not closing or draining response bodies — connection leaks, then "too many open files".
- Unbounded request bodies — a 2 GB POST exhausts memory; use
MaxBytesReader. - Float amounts in JSON — rounding errors, precision loss above 2^53 in JS clients.
- Retrying a transaction that called a PSP — double side effects on serialization retries.
- Pool larger than the DB can handle —
too many clientserrors at scale-out, or PostgreSQL thrashing. - High-cardinality metric labels (
user_id,order_id, raw URL path) — metrics backend overload; label by route pattern instead. - Liveness probe checks the database — a DB blip restarts every pod at once.
- Custom
slog.Handlerwrapper withoutWithAttrs/WithGroup— context enrichment silently disappears for loggers created with.With. - Running as root with a full OS image — CVE noise, larger blast radius.
Interview angle
Prompts: "Walk me through building a payment API in Go", "How do you make a Go service production-ready?", "How do you handle DB transactions and retries?", "Liveness vs readiness?", "How do you trace a request across services?", "What's in your Dockerfile?"
A strong answer moves along the request path: server timeouts → middleware order → strict decoding and validation → use case with context → pgx with a sized pool and statement_timeout → retry only 40001/40P01 with side-effect-free transactions → domain error mapping → logs with trace IDs, low-cardinality metrics → probes → graceful shutdown → distroless image. Mention numbers you'd actually configure and why.
Follow-ups: "Why does gRPC load balance badly on Kubernetes?" (sticky HTTP/2 connections), "How big should the DB pool be?" (from the DB's connection budget and query latency, not traffic), "How do you avoid logging PANs?" (LogValuer types, linting, log scanning).
Red flags: default http.Client, floats for amounts, retrying around external calls, payment_id as a metric label, liveness depending on the DB.
Self-check
1. What does the pattern "GET /v1/payments/{id}" match, and what happens to a DELETE on that path?
GET and HEAD requests for /v1/payments/<one segment>; r.PathValue("id") returns the segment. A DELETE matches the path but not the method, so ServeMux responds 405 Method Not Allowed with Allow: GET, HEAD.
2. Why is ReadHeaderTimeout the one server timeout you must always set?
Without it, a client can open a connection and send headers byte by byte forever (Slowloris), holding a goroutine and file descriptor per connection. The zero-value http.Server has no timeouts; ReadHeaderTimeout bounds header reading without constraining body streaming or handler time.
3. Your transfer transaction runs under SERIALIZABLE. Which errors do you retry, and what must be true of the function you retry?
Retry SQLSTATE 40001 (serialization failure) and 40P01 (deadlock detected), with bounded attempts, backoff and jitter, and only while the context allows. The function must have no effects outside the database (no PSP calls, no publishes) because it may run several times; events go to an outbox table in the same transaction.
4. A custom slog handler adds trace_id from context, but logs from logger.With("component", "psp") lack it. Why?
The wrapper embeds slog.Handler but doesn't override WithAttrs/WithGroup, so With calls the embedded handler's method and returns the inner handler, dropping the wrapper. Override both to re-wrap the result.
5. Why must payment_id never be a metric attribute, but is fine on spans?
Every unique attribute combination is a separate time series held in memory by the metrics backend; millions of payment IDs mean millions of series. Spans are individual events sampled and stored per request, designed for high-cardinality attributes. Use bounded labels (route, outcome, PSP) on metrics.
6. Scenario: during a PostgreSQL failover (30 s), all payment pods restart in a loop. What's misconfigured?
The liveness probe checks the database. When the DB is down, liveness fails and Kubernetes restarts every pod, adding cold starts and connection storms to the outage. Liveness should only check the process; readiness can fail on DB unavailability so traffic is shed while pods stay up and reconnect when the DB returns.
7. What does each part of CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=1.4.2" do?
CGO_ENABLED=0 builds a fully static binary with no libc dependency, so it runs on distroless static. -trimpath removes local filesystem paths from the binary. -s -w strips the symbol table and DWARF debug info to shrink it. -X main.version=1.4.2 sets the string variable main.version at link time.
Exercise
Build payments-api end to end:
- Routes:
POST /v1/payments(idempotency key required),GET /v1/payments/{id},POST /v1/payments/{id}/capture; strict decoding, validation, problem-details errors. - PostgreSQL via
pgxpool(testcontainers in tests),InTxwith retries; prove retries happen by running 50 concurrent conflicting transfers under SERIALIZABLE and asserting balances. - A gRPC
PaymentService.CapturePaymentsharing the same use case, with the error interceptor and health service. slogJSON logs with request/trace IDs; OTel traces to a local collector + Jaeger (docker compose); apayments.capturescounter by outcome./livez,/readyz, graceful shutdown; verify with a load test duringdocker stopthat no request fails.- Multi-stage distroless image under 25 MB; scan it with Trivy.
Done when: a trace shows HTTP → use case → SQL spans for one payment; the shutdown test has zero errors; the image runs as non-root. The Hands-on Go Labs page has a guided version.
Further reading
net/httppackage documentation and the Go blog post "Routing Enhancements for Go 1.22".- Go blog: "Structured Logging with slog" (Jonathan Amsterdam).
- pgx documentation and README (github.com/jackc/pgx) — pool configuration,
CollectRows,BeginTxFunc. - gRPC-Go documentation: interceptors, health checking, keepalive.
- OpenTelemetry Go documentation (opentelemetry.io/docs/languages/go).
- Mat Ryer, "How I write HTTP services in Go after 13 years" (Grafana Labs blog).
- Filippo Valsorda / Cloudflare blog: "The complete guide to Go net/http timeouts".
- Google distroless images (github.com/GoogleContainerTools/distroless).
- Kubernetes documentation: "Configure Liveness, Readiness and Startup Probes".
Related
- Error Handling — the error mapping and recover middleware used here.
- Concurrency Patterns — graceful shutdown and rate limiting.
- Project Layout & Clean Architecture in Go — where these adapters live.
- Observability & SLOs — what to do with the telemetry.
- API Design (REST, gRPC, GraphQL) — designing the contracts.
- RPC & gRPC — HTTP/2, load balancing and deadlines.
- Cloud-Native, Kubernetes & Deployment Strategies — probes and rollouts.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).