Skip to content

Project: Broker, Auth, Logger & Mailer Microservices with REST, RPC, gRPC and RabbitMQ ​

"Almost all the successful microservice stories have started with a monolith that got too big and was broken up" — Martin Fowler, "MonolithFirst", martinfowler.com, 3 June 2015

Summary: A complete project walkthrough of five small Go services: a broker service that is the only front door, an authentication service on Postgres with bcrypt, a logger service on MongoDB reachable over REST, net/rpc and gRPC, a mailer service that renders templates and sends SMTP via go-mail, and a listener service that consumes RabbitMQ events. One Go module, tests for every service, no running brokers or databases in the tests. Focus: the four communication styles side by side (REST/JSON between services, RPC with net/rpc, gRPC, RabbitMQ events), when to use which, service contracts and shared types, configuration and service discovery via DNS names in Docker Compose, health checks, graceful shutdown of all servers in one process, request IDs and OpenTelemetry traces across every hop, timeouts and retries per hop, idempotency, a circuit breaker with sony/gobreaker, error propagation and status mapping, a testing strategy built on httptest, bufconn and GoChannel fakes, the Makefile multi-binary build, Dockerfiles and the Compose topology, failure scenarios, and what a monolith version would look like. Learning goal: Read a request entering the broker and say, for every hop it causes, which transport it uses and why, how long it may take, whether it is retried and with which key, what the caller sees when that hop fails, and how the hop shows up in logs and traces; then build, test and describe the deployment of the whole system.

This page is a project: it assembles pieces that other chapters teach in depth and links to them instead of re-teaching. The HTTP server and client, routing and server timeouts are in net/http; protobuf, codegen, interceptors and bufconn in gRPC & Protobuf in Go; Watermill, the AMQP topology, publisher confirms, outbox and inbox in Event-Driven Go; database/sql and pgx in database/sql & pgx; the MongoDB driver in MongoDB with Go; project layout, Makefiles and Docker images in Project Layout, Linting & Builds; signals in OS Processes, Signals & Graceful Shutdown; and context itself in context. The architecture side is in Microservices Architecture, Service Communication, API Gateway, BFF & Service Mesh, Service Discovery, Circuit Breaker, RabbitMQ and Request-Reply over REST and AMQP.

Facts below were checked against the Go 1.27 source of net/rpc, encoding/gob, net/http and net/http/httptest on go.dev, the Go 1.18 release notes and workspace tutorial, grpc.io (Go basics, deadlines, health checking), the grpc-go bufconn, server.go and health sources, the RabbitMQ tutorials 3 to 7 and the confirms and exchanges guides, the amqp091-go, go-mail, gomail and gobreaker READMEs, the gobreaker v2.4.0 source, the Watermill GoChannel and AMQP docs and sources, Docker's Compose networking, startup-order and multi-stage pages, the OpenTelemetry Go getting-started and propagation pages, the W3C Trace Context recommendation, microservices.io patterns, Fowler and Lewis on microservices, and the Laravel 13 queues, Octane, Horizon and HTTP client docs. The snippet module declares go 1.24.0 and pins the last releases whose go.mod still says 1.24: google.golang.org/grpc v1.80.0, github.com/wneessen/go-mail v0.7.2 (v0.8.0 needs 1.25), go.opentelemetry.io/contrib/.../otelhttp and otelgrpc v0.66.0 (v0.67.0 needs 1.25) with go.opentelemetry.io/otel v1.41.0, plus github.com/sony/gobreaker/v2 v2.4.0, github.com/ThreeDotsLabs/watermill v1.5.1, watermill-amqp/v3 v3.1.0, rabbitmq/amqp091-go v1.17.0, jackc/pgx/v5 v5.8.0, mongo-driver/v2 v2.8.2 and golang.org/x/crypto v0.48.0. Everything was compiled, vetted and tested with -race on Go 1.27.4 (macOS); the Postgres, MongoDB, RabbitMQ and SMTP adapters compile but are exercised only through fakes, and the Docker Compose file is written, validated with docker compose config and described, not run.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why split into services at all, and the priceWhy it exists
Where the pieces come fromWhere it comes from
The naive broker and the finished oneGo
Project walkthrough: broker service, front door, JSON action routerBroker service
Authentication service: Postgres, bcryptAuthentication service
Logger service: MongoDB, one core and three transportsLogger service
Mailer service: SMTP via go-mail/gomail, templatesMailer service
Listener service: RabbitMQ consumerListener service
Communication styles side by side: REST/JSON between servicesREST/JSON
RPC with net/rpc: gob, Register, Dial, Call, limitsnet/rpc
gRPC: proto, codegen, client/server, deadlinesgRPC
RabbitMQ events: exchange, routing keys, publisher confirms, consumerRabbitMQ events
When to use which: sync vs async, request/reply vs eventWhen to use which
Service contracts and shared types: go.work or a shared module vs duplicationContracts
Configuration and service discovery via DNS names in Docker Compose (describe, no lab run)Configuration and discovery
Health checksHealth checks
Graceful shutdown of all servers in one processGraceful shutdown
Structured logging with request IDs across services, propagationRequest IDs
Timeouts and retries per hop, idempotencyTimeouts, retries, idempotency
Circuit breaker, sony/gobreakerCircuit breaker
Error propagation and status mappingStatus mapping
Testing strategy: unit per service, contract tests, httptest/bufconn/GoChannel fakesTesting strategy
Makefile multi-binary build, Dockerfiles, Compose topology (describe)Build and deploy
Observability: OpenTelemetry traces across REST/gRPC/AMQPObservability
One request on the wire, exact error textsMechanics
Failure scenarios: broker down, DB down, slow mailerSolving the classic problems
What to use whenChoosing
What a monolith version would look like, and the scaling pathIn architecture
Reproduce it on your machineLab
Laravel equivalent: queues, Octane, Horizon, comparisonFor PHP/Laravel developers

Everything in one minute ​

The five services. Every row is unpacked in the concept catalogue. Names are the Docker Compose service names, which are also their DNS names.

ServiceOwnsListens onCalled byTalks toStore
broker-serviceThe front door: one JSON envelope, routed by action:80 (published as 8080)Front endauth (REST), logger (REST, net/rpc, gRPC), mailer (REST), RabbitMQ (publish)None
authentication-serviceUsers and passwords:80BrokerPostgres, logger (audit, REST)Postgres users, bcrypt hashes
logger-serviceLog entries:80 REST, :5001 net/rpc, :50001 gRPCBroker, auth, listenerMongoDBMongoDB logs.logs
mailer-serviceRendering and sending mail:80BrokerSMTP server (Mailpit in development)None
listener-serviceTurning events into log writesNo portRabbitMQ (push)logger (REST)None (queue listener.logs)

The four communication styles side by side.

StyleContractEncodingDeadline travels?Errors come back asCaller waits?Used here for
REST/JSONJSON shape + shared Go typesJSONNo (only the client's own timeout)HTTP status + JSON messageYesFront end to broker, broker to auth and mailer
net/rpcExported Go types (Go to Go only)gobNo: Call takes no contextA string (rpc.ServerError)YesOne logger path, to show its limits
gRPC.proto + generated codeProtobuf over HTTP/2Yes: grpc-timeoutcodes.* statusYesFast typed logger path
RabbitMQ eventVersioned event JSONJSON body, AMQP headersNo (TTL at most)Nack, retry, poison queueNo: 202 after publishDefault logger path

What each failure looks like to the user.

FailureBroker answersWhy that statusDetail
Wrong password401 + "invalid credentials"A 4xx from downstream is the caller's business; it passes throughStatus mapping
Postgres (DB down)502 "authentication failed: Bad Gateway"Auth answers 503; the broker reports a bad upstream, hides internalsDB down
Mailer hangs (slow mailer)504 after the mail hop's budgetPer-attempt timeout, then the request budgetSlow mailer
Mailer keeps failing503 immediatelyCircuit breaker open: no call is madeCircuit breaker
RabbitMQ (broker down)503 "event bus unavailable, retry later" for log via event; other actions unaffectedThe bus is infrastructure: the client should retry laterBroker down
Logger down while events flow202 to the user; listener retries; nothing lostAsync path: the queue absorbs itListener service
Unknown action400Validation at the front doorBroker service

Why it exists ​

The project exists to show, in code you can run, what changes when one application becomes several processes. In one binary a call to auth.Authenticate costs nanoseconds, never times out, shares one log stream, fails only with your own errors and is covered by one transaction. Split it into services and every one of those properties becomes a decision: which transport, which contract, which timeout, which retry and with which idempotency key, what the caller sees on failure, how a log line in the logger is tied to the request that caused it, and how all of it is started, health-checked and stopped. The payoff is independent deployment and scaling, separate stores and fault isolation; the price is that you now own a distributed system.

One process (monolith)Five services
Function call; types checked by the compilerNetwork call; contract checked by tests or codegen
Fails with your error valuesFails with timeouts, refused connections, 5xx, partial success
One log stream, one stack traceLogs in five places; request ID and trace ID join them
One transaction can cover auth and loggingNo shared transaction; idempotency and events instead
One deploy, one scale knobIndependent deploys and scaling per service
Start and stop is mainStart order, health checks, graceful shutdown per service
Cheap to build and testMore code per feature; the tests must run without the network

An everyday picture. A hotel front desk. Guests talk only to the desk (the broker service). For a key card the desk phones security and waits on the line (REST, synchronous). For a wake-up call it drops a slip in the housekeeping tray and tells the guest "done" (an event: the work happens later, and the tray keeps the slip if housekeeping is on a break). Two old internal lines exist: a direct intercom only the old building understands (net/rpc) and a modern line with a fixed form and a "must be answered within" field (gRPC). Every request gets a ticket number written on every slip (the request ID). If the laundry service keeps failing, the desk stops calling for a while and tells guests at once (the circuit breaker). At closing time the desk stops taking new guests, finishes those at the counter, and only then locks up (graceful shutdown).

Three common misunderstandings, up front ​

  1. "Microservices make the system more reliable." Each hop adds a way to fail. Reliability comes from the per-hop policy (timeouts, retries with idempotency keys, a breaker, a queue in front of slow work), and the broker test suite proves each one.
  2. "A shared contracts package couples the services." It couples them to the wire format, which they share anyway. Copying the structs into each service does not remove the coupling, it hides it until a field is renamed on one side.
  3. "Async is always better." The login must be answered now, so it is a request/reply call. Only work the user does not wait for (a log entry, a confirmation email) belongs on a queue.

Where it comes from ​

The word and its list of characteristics come from James Lewis and Martin Fowler's article "Microservices" (25 March 2014), with headings such as "Smart endpoints and dumb pipes" and "Design for failure". Fowler's "MonolithFirst" (3 June 2015) adds the warning quoted above. Chris Richardson's microservices.io catalogue names the patterns this project uses: the API gateway as "the single entry point for all clients", database per service ("Keep each microservice’s persistent data private to that service and accessible only via its API"), server-side discovery and the circuit breaker. Sam Newman's Building Microservices (2nd edition, a complete rewrite) is the standard book; only its public summary page was read for this chapter.

On the Go side, net/rpc and encoding/gob have been in the standard library since Go 1; the package doc now says "The net/rpc package is frozen and is not accepting new features." gRPC brought protobuf contracts, HTTP/2 and deadlines (grpc-go v1.80.0 here). RabbitMQ's official Go client is github.com/rabbitmq/amqp091-go; Watermill wraps it and other brokers behind one message.Publisher/message.Subscriber API, with an in-memory GoChannel implementation that makes consumer tests possible without a broker. Go 1.18 added workspaces (go.work). Go 1.22 added method and wildcard patterns to http.ServeMux, which the services use (POST /handle, POST /{$}). Mat Ryer's "How I write HTTP services after eight years" (2018; the 2024 "after 13 years" version on grafana.com refused scripted fetches) popularised the shape used here: a service struct, a Routes method, and handlers as methods.

Go ​

Before ​

The broker as it is often first written. It works on a quiet day. It posts with http.DefaultClient (no timeout), drops the request context, creates no request ID, retries nothing and turns every answer that is not 202 into a 500, so the front end cannot tell a wrong password from an outage.

go
// Package before is the broker as it is often first written: it works
// on a quiet day. It uses http.DefaultClient (no timeout), drops the
// request context, invents no request ID, retries nothing, and turns
// every downstream answer that is not 202 into a 500, so the front end
// cannot tell a wrong password from an outage.
package before

import (
	"bytes"
	"encoding/json"
	"net/http"
)

type RequestPayload struct {
	Action string          `json:"action"`
	Auth   json.RawMessage `json:"auth,omitempty"`
	Mail   json.RawMessage `json:"mail,omitempty"`
}

type Broker struct {
	AuthURL string // "http://authentication-service/authenticate"
	MailURL string // "http://mailer-service/send"
}

func (b *Broker) Handle(w http.ResponseWriter, r *http.Request) {
	var p RequestPayload
	_ = json.NewDecoder(r.Body).Decode(&p) // no size limit, error ignored

	url, body := "", []byte(nil)
	switch p.Action {
	case "auth":
		url, body = b.AuthURL, p.Auth
	case "mail":
		url, body = b.MailURL, p.Mail
	}
	// No ctx: if the client leaves, this call carries on. No timeout:
	// a hung mailer holds this goroutine and its connection forever.
	resp, err := http.Post(url, "application/json", bytes.NewReader(body))
	if err != nil || resp.StatusCode != http.StatusAccepted {
		http.Error(w, `{"error":true,"message":"error calling service"}`, http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()
	w.WriteHeader(http.StatusAccepted)
	_, _ = w.Write([]byte(`{"error":false,"message":"ok"}`))
}

The tests prove both defects: a 401 from auth becomes a 500, and a mailer that sleeps holds the broker for the whole delay.

go
package before

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func TestWrongPasswordLooksLikeAnOutage(t *testing.T) {
	auth := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, `{"error":true,"message":"invalid credentials"}`, http.StatusUnauthorized)
	}))
	defer auth.Close()
	b := &Broker{AuthURL: auth.URL}
	rec := httptest.NewRecorder()
	b.Handle(rec, httptest.NewRequest(http.MethodPost, "/handle", strings.NewReader(`{"action":"auth","auth":{}}`)))
	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("got %d", rec.Code)
	}
}

func TestSlowMailerHoldsTheBrokerForAsLongAsItLikes(t *testing.T) {
	mail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(300 * time.Millisecond) // could be 300 s
		w.WriteHeader(http.StatusAccepted)
	}))
	defer mail.Close()
	b := &Broker{MailURL: mail.URL}
	start := time.Now()
	rec := httptest.NewRecorder()
	b.Handle(rec, httptest.NewRequest(http.MethodPost, "/handle", strings.NewReader(`{"action":"mail","mail":{}}`)))
	if el := time.Since(start); el < 300*time.Millisecond {
		t.Fatalf("returned after %v: expected the full mailer delay", el)
	}
}

After ​

The finished broker: one JSON action router, a client per downstream and transport, a policy per hop (timeout, retries, breaker) and one place that maps errors to statuses. Each piece is explained in the catalogue below.

go
// Package broker is the broker service, the project's front door. The
// front end posts one JSON envelope to POST /handle; the JSON action
// router sends "auth" to the authentication service over REST, "mail"
// to the mailer over REST, and "log" over the transport named in
// log.via: REST, net/rpc, gRPC, or a RabbitMQ event (the default).
// Every hop has its own timeout, retry policy and, for the mailer, a
// circuit breaker; every error is mapped to one HTTP status.
package broker

import (
	"context"
	"errors"
	"log/slog"
	"net/http"

	"github.com/sony/gobreaker/v2"

	"academy/microservices-project/contracts"
	"academy/microservices-project/platform/health"
	"academy/microservices-project/platform/resilience"
	"academy/microservices-project/platform/web"
)

// Authenticator is the auth-service client.
type Authenticator interface {
	Authenticate(ctx context.Context, p contracts.AuthPayload) (contracts.AuthUser, error)
}

// LogWriter is a logger-service client over one transport.
type LogWriter interface {
	WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error)
}

// Mailer is the mailer-service client.
type Mailer interface {
	Send(ctx context.Context, key string, p contracts.MailPayload) error
}

// EventPublisher publishes log events to RabbitMQ.
type EventPublisher interface {
	PublishLog(ctx context.Context, key, severity string, p contracts.LogPayload) error
}

// Broker holds one client per downstream and the per-hop policies.
type Broker struct {
	Auth   Authenticator
	Logs   map[string]LogWriter // keyed by contracts.ViaREST, ViaRPC, ViaGRPC
	Events EventPublisher
	Mail   Mailer
	Log    *slog.Logger

	AuthHop, LogHop, MailHop, EventHop resilience.Hop
	MailBreaker                        *gobreaker.CircuitBreaker[struct{}]
}

// Routes returns the broker's handler.
func (b *Broker) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /{$}", func(w http.ResponseWriter, r *http.Request) {
		web.WriteJSON(w, http.StatusOK, contracts.JSONResponse{Message: "Hit the broker"})
	})
	mux.HandleFunc("POST /handle", b.handle)
	health.Handler{}.Register(mux)
	return web.RequestIDMiddleware(mux)
}

func (b *Broker) handle(w http.ResponseWriter, r *http.Request) {
	var p contracts.RequestPayload
	if err := web.ReadJSON(w, r, &p); err != nil {
		web.ErrorJSON(w, http.StatusBadRequest, err)
		return
	}
	// One key per client request: every retry of every hop reuses it,
	// so downstream services can drop duplicates.
	key := r.Header.Get(contracts.HeaderIdempotencyKey)
	if key == "" {
		key = web.RequestID(r.Context())
	}
	ctx := r.Context()
	switch {
	case p.Action == contracts.ActionAuth && p.Auth != nil:
		b.authenticate(ctx, w, *p.Auth)
	case p.Action == contracts.ActionLog && p.Log != nil:
		b.log(ctx, w, key, *p.Log)
	case p.Action == contracts.ActionMail && p.Mail != nil:
		b.mail(ctx, w, key, *p.Mail)
	default:
		web.ErrorJSON(w, http.StatusBadRequest, errors.New("unknown action or missing payload"))
	}
}

func (b *Broker) authenticate(ctx context.Context, w http.ResponseWriter, p contracts.AuthPayload) {
	var u contracts.AuthUser
	err := resilience.Do(ctx, b.AuthHop, func(ctx context.Context) error {
		var err error
		u, err = b.Auth.Authenticate(ctx, p)
		return err
	})
	if err != nil {
		b.fail(ctx, w, "authentication", err)
		return
	}
	b.Log.InfoContext(ctx, "authenticated", "user_id", u.ID)
	web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: "Authenticated", Data: u})
}

func (b *Broker) log(ctx context.Context, w http.ResponseWriter, key string, p contracts.LogPayload) {
	via := p.Via
	if via == "" {
		via = contracts.ViaEvent
	}
	if via == contracts.ViaEvent {
		err := resilience.Do(ctx, b.EventHop, func(ctx context.Context) error {
			return b.Events.PublishLog(ctx, key, "info", p)
		})
		if code := resilience.HTTPStatus(err); err != nil && code >= 400 && code < 500 {
			b.fail(ctx, w, "event publish", err) // validation (monolith adapter): pass through
			return
		}
		if err != nil {
			// RabbitMQ is infrastructure, not an upstream answer: whatever
			// the error type, tell the client to retry later.
			b.Log.ErrorContext(ctx, "event publish failed", "err", err)
			web.ErrorJSON(w, http.StatusServiceUnavailable, errors.New("event bus unavailable, retry later"))
			return
		}
		// The only trace of an accepted event in the broker's own log:
		// one INFO line per publish, joinable by request_id.
		b.Log.InfoContext(ctx, "event published", "routing_key", contracts.RoutingKey("info"), "event_id", key)
		// 202: accepted for processing; the listener writes it later.
		web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: "queued via RabbitMQ"})
		return
	}
	lw, ok := b.Logs[via]
	if !ok {
		web.ErrorJSON(w, http.StatusBadRequest, errors.New("log.via must be rest, rpc, grpc or event"))
		return
	}
	var id string
	err := resilience.Do(ctx, b.LogHop, func(ctx context.Context) error {
		var err error
		id, err = lw.WriteLog(ctx, key, p)
		return err
	})
	if err != nil {
		b.fail(ctx, w, "logging via "+via, err)
		return
	}
	b.Log.InfoContext(ctx, "log written", "via", via, "id", id)
	web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: "logged via " + via, Data: map[string]string{"id": id}})
}

func (b *Broker) mail(ctx context.Context, w http.ResponseWriter, key string, p contracts.MailPayload) {
	err := resilience.Do(ctx, b.MailHop, func(ctx context.Context) error {
		return resilience.Guard(b.MailBreaker, func() error { return b.Mail.Send(ctx, key, p) })
	})
	if err != nil {
		b.fail(ctx, w, "mail", err)
		return
	}
	b.Log.InfoContext(ctx, "mail accepted", "idempotency_key", key)
	web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: "Message sent to " + p.To})
}

// fail maps err to a status. 4xx messages from downstream are the
// caller's business and pass through; 5xx details stay in the log.
func (b *Broker) fail(ctx context.Context, w http.ResponseWriter, what string, err error) {
	code := resilience.HTTPStatus(err)
	var ue *resilience.UpstreamError
	if code < 500 && errors.As(err, &ue) {
		web.ErrorJSON(w, code, errors.New(ue.Message))
		return
	}
	b.Log.ErrorContext(ctx, what+" failed", "err", err, "status", code)
	web.ErrorJSON(w, code, errors.New(what+" failed: "+http.StatusText(code)))
}
go
package broker

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"testing"
	"time"

	"academy/microservices-project/contracts"
	"academy/microservices-project/platform/resilience"
	"academy/microservices-project/platform/web"
)

type fakeAuth struct{ err error }

func (f fakeAuth) Authenticate(ctx context.Context, p contracts.AuthPayload) (contracts.AuthUser, error) {
	return contracts.AuthUser{ID: 1, Email: p.Email}, f.err
}

type fakeLogs struct {
	mu   sync.Mutex
	keys []string
	errs []error // returned in order, then nil
}

func (f *fakeLogs) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.keys = append(f.keys, key)
	if len(f.errs) > 0 {
		err := f.errs[0]
		f.errs = f.errs[1:]
		return "", err
	}
	return "id-" + key, nil
}

type fakeEvents struct {
	topics []string
	err    error
}

func (f *fakeEvents) PublishLog(ctx context.Context, key, sev string, p contracts.LogPayload) error {
	if f.err != nil {
		return f.err
	}
	f.topics = append(f.topics, contracts.RoutingKey(sev))
	return nil
}

type slowMailer struct {
	delay time.Duration
	err   error
	calls int
}

func (s *slowMailer) Send(ctx context.Context, key string, p contracts.MailPayload) error {
	s.calls++
	if s.err != nil {
		return s.err
	}
	t := time.NewTimer(s.delay)
	defer t.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-t.C:
		return nil
	}
}

func newBroker(mail Mailer, logs *fakeLogs, auth Authenticator) (*Broker, *fakeEvents) {
	ev := &fakeEvents{}
	return &Broker{
		Auth: auth, Logs: map[string]LogWriter{"rest": logs, "rpc": logs, "grpc": logs}, Events: ev, Mail: mail,
		Log:         slog.New(slog.DiscardHandler),
		AuthHop:     resilience.Hop{Name: "auth", Timeout: time.Second, Attempts: 1},
		LogHop:      resilience.Hop{Name: "log", Timeout: time.Second, Attempts: 3, Backoff: time.Millisecond},
		MailHop:     resilience.Hop{Name: "mail", Timeout: 40 * time.Millisecond, Attempts: 2, Backoff: time.Millisecond},
		EventHop:    resilience.Hop{Name: "event", Timeout: time.Second, Attempts: 1},
		MailBreaker: resilience.NewBreaker("mailer", 3, time.Hour, nil),
	}, ev
}

func do(t *testing.T, h http.Handler, body string) (*httptest.ResponseRecorder, contracts.JSONResponse) {
	t.Helper()
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodPost, "/handle", strings.NewReader(body))
	req.Header.Set(contracts.HeaderRequestID, "r-1")
	h.ServeHTTP(rec, req)
	var resp contracts.JSONResponse
	_ = json.Unmarshal(rec.Body.Bytes(), &resp)
	return rec, resp
}

func TestActionRouter(t *testing.T) {
	b, ev := newBroker(&slowMailer{}, &fakeLogs{}, fakeAuth{})
	h := b.Routes()
	cases := []struct {
		body string
		code int
	}{
		{`{"action":"auth","auth":{"email":"a@example.test","password":"x"}}`, 202},
		{`{"action":"log","log":{"name":"event","data":"d","via":"rest"}}`, 202},
		{`{"action":"log","log":{"name":"event","data":"d","via":"grpc"}}`, 202},
		{`{"action":"log","log":{"name":"event","data":"d"}}`, 202}, // default: RabbitMQ event
		{`{"action":"log","log":{"name":"event","via":"carrier-pigeon"}}`, 400},
		{`{"action":"mail","mail":{"to":"a@example.test","subject":"s","message":"m"}}`, 202},
		{`{"action":"auth"}`, 400},
		{`{"action":"delete-everything"}`, 400},
	}
	for _, c := range cases {
		if rec, resp := do(t, h, c.body); rec.Code != c.code {
			t.Errorf("%s: got %d (%s), want %d", c.body, rec.Code, resp.Message, c.code)
		}
	}
	if len(ev.topics) != 1 || ev.topics[0] != "log.info" {
		t.Fatalf("events %v", ev.topics)
	}
}

func TestAuth401PassesThroughAndOutageBecomes502(t *testing.T) {
	b, _ := newBroker(&slowMailer{}, &fakeLogs{}, fakeAuth{err: &resilience.UpstreamError{Service: "auth", Status: 401, Message: "invalid credentials"}})
	rec, resp := do(t, b.Routes(), `{"action":"auth","auth":{"email":"a@example.test","password":"x"}}`)
	if rec.Code != 401 || resp.Message != "invalid credentials" {
		t.Fatalf("got %d %q", rec.Code, resp.Message)
	}
	b.Auth = fakeAuth{err: &resilience.UpstreamError{Service: "auth", Status: 503, Message: "user store unavailable"}}
	rec, resp = do(t, b.Routes(), `{"action":"auth","auth":{"email":"a@example.test","password":"x"}}`)
	if rec.Code != 502 || strings.Contains(resp.Message, "user store") {
		t.Fatalf("got %d %q", rec.Code, resp.Message)
	}
}

func TestRetriesReuseOneIdempotencyKey(t *testing.T) {
	logs := &fakeLogs{errs: []error{&resilience.UpstreamError{Status: 503}, context.DeadlineExceeded}}
	b, _ := newBroker(&slowMailer{}, logs, fakeAuth{})
	rec, _ := do(t, b.Routes(), `{"action":"log","log":{"name":"event","data":"d","via":"rpc"}}`)
	if rec.Code != 202 || len(logs.keys) != 3 {
		t.Fatalf("code %d calls %d", rec.Code, len(logs.keys))
	}
	if logs.keys[0] != "r-1" || logs.keys[1] != logs.keys[0] || logs.keys[2] != logs.keys[0] {
		t.Fatalf("keys %v: every attempt must carry the same key", logs.keys)
	}
}

func TestSlowMailerIsCutAt504(t *testing.T) {
	m := &slowMailer{delay: time.Second}
	b, _ := newBroker(m, &fakeLogs{}, fakeAuth{})
	start := time.Now()
	rec, _ := do(t, b.Routes(), `{"action":"mail","mail":{"to":"a@example.test","subject":"s","message":"m"}}`)
	if rec.Code != http.StatusGatewayTimeout {
		t.Fatalf("got %d", rec.Code)
	}
	if el := time.Since(start); el > 500*time.Millisecond {
		t.Fatalf("broker waited %v for a slow mailer", el)
	}
	if m.calls != 2 {
		t.Fatalf("calls %d, want 2 attempts", m.calls)
	}
}

func TestMailerDownOpensBreaker(t *testing.T) {
	m := &slowMailer{err: errors.New("dial tcp mailer-service:80: connect: connection refused")}
	b, _ := newBroker(m, &fakeLogs{}, fakeAuth{})
	h := b.Routes()
	body := `{"action":"mail","mail":{"to":"a@example.test","subject":"s","message":"m"}}`
	// Plain errors are not retryable, so each request makes one call.
	for range 3 {
		do(t, h, body)
	}
	before := m.calls
	rec, _ := do(t, h, body)
	if rec.Code != http.StatusServiceUnavailable || m.calls != before {
		t.Fatalf("open breaker: code %d, calls %d -> %d", rec.Code, before, m.calls)
	}
}

func TestRabbitMQDownOnlyBreaksTheEventPath(t *testing.T) {
	b, ev := newBroker(&slowMailer{}, &fakeLogs{}, fakeAuth{})
	ev.err = errors.New("Exception (504) Reason: \"channel/connection is not open\"")
	h := b.Routes()
	if rec, _ := do(t, h, `{"action":"log","log":{"name":"event","data":"d"}}`); rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("event path: %d, want 503", rec.Code)
	}
	if rec, _ := do(t, h, `{"action":"log","log":{"name":"event","data":"d","via":"grpc"}}`); rec.Code != http.StatusAccepted {
		t.Fatalf("grpc path must still work: %d", rec.Code)
	}
}

func TestSuccessIsLoggedWithRequestID(t *testing.T) {
	var buf bytes.Buffer
	b, _ := newBroker(&slowMailer{}, &fakeLogs{}, fakeAuth{})
	b.Log = web.NewLogger(&buf, "broker-service")
	rec, _ := do(t, b.Routes(), `{"action":"log","log":{"name":"event","data":"hello"}}`)
	if rec.Code != http.StatusAccepted {
		t.Fatalf("code %d", rec.Code)
	}
	line := strings.TrimSpace(buf.String())
	t.Log(line)
	if !strings.Contains(line, `"msg":"event published"`) || !strings.Contains(line, `"request_id":"r-1"`) || !strings.Contains(line, `"routing_key":"log.info"`) {
		t.Fatalf("no success line with the request id: %q", line)
	}
}

The Go angle ​

Go suits this shape because the pieces a service needs are in the standard library or one import away and they all agree on context.Context: net/http for REST and health endpoints, net/rpc and encoding/gob for Go-to-Go RPC, log/slog for structured logs, signal.NotifyContext for shutdown, httptest for in-process servers; grpc-go, amqp091-go/Watermill, pgx and the MongoDB driver all take ctx first. Static binaries make the Docker images small (the six binaries here are 5.6 to 19.9 MB with -trimpath -ldflags "-s -w"), and one module with a cmd/<service> directory per binary keeps shared contracts compiled together. The design rule that makes the whole project testable: every service has a transport-free core (auth.Service.Authenticate, logger.Service.Write, mailer.Service.Send) and thin transports around it, so the same core runs behind HTTP, net/rpc, gRPC, a consumer, or a plain function call in the monolith version.

Five services, one front door, four ways to talkFront endbrowser / curlbroker-servicePOST /handleJSON action routerJSONauthentication-servicePOST /authenticatePostgresusers (bcrypt)REST/JSONSQLlogger-service:80 REST:5001 net/rpc (gob):50001 gRPCMongoDBlogs collectionRESTRPCgRPCinsertaudit RESTRabbitMQexchange logs_topic(topic)publish log.infolistener-servicequeue listener.logsbinding log.*deliverREST + event idmailer-servicePOST /sendtemplatesMailpit / SMTPREST + breakerInside Docker Compose every name above is a DNS name on the default network

The concept catalogue ​

The module is academy/microservices-project: contracts (wire types), platform/web|health|lifecycle|resilience|config (shared plumbing), one package per service (broker, auth, logger, mailer, listener), clients (the typed clients), tracing, gen/logs/v1 (generated gRPC code), allinone (every service in one process, the end-to-end test), monolith, before, and cmd/<service> mains.

Project walkthrough: broker service, the front door and its JSON action router Must-know ​

In plain words: The front end knows one URL. It posts {"action": "...", ...} to POST /handle; the broker reads action, picks the right downstream and transport, applies that hop's policy, and answers with the shared {"error", "message", "data"} envelope.

Common misunderstanding: "The broker is a reverse proxy." A proxy forwards bytes; this broker owns a contract (the action envelope), validates it, chooses a transport per action, owns the per-hop timeouts and retries, and translates every downstream failure into one status the front end understands. That is what microservices.io calls an API gateway ("the single entry point for all clients"), in its simplest form. The production-grade relatives (Kong, Envoy, a BFF per client type) are in API Gateway, BFF & Service Mesh.

Definition: broker.Broker holds one interface per downstream (Authenticator, LogWriter per transport, EventPublisher, Mailer) and a resilience.Hop per downstream. Routes() registers POST /{$} (a ping), POST /handle and the health endpoints, wrapped in the request-ID middleware. handle decodes with web.ReadJSON (1 MiB limit, unknown fields rejected, exactly one JSON value), derives one idempotency key per client request (the client's Idempotency-Key header, or the request ID) and dispatches on action + payload presence.

     front end                broker-service                          downstream
1    POST /handle {"action":"mail",...}  X-Request-ID: r-1
2                             ReadJSON -> RequestPayload{Action:"mail"}
3                             key = "r-1"; hop = MailHop{3s, 2 attempts}
4                             breaker closed -> MailREST.Send(ctx 3s) ─────▶ POST http://mailer-service/send
5                                                                           Idempotency-Key: r-1, X-Request-ID: r-1
6                             ◀───────────────────────────────────────────── 202 {"error":false,"message":"sent to ..."}
7    ◀── 202 {"error":false,"message":"Message sent to a@example.test"}

Real scenario: a single-page app that must not know internal hostnames; a mobile client that wants one round trip and one error format; a security review that wants exactly one public port; a team that moves logging from REST to events without touching the front end.

ActionPayloadDownstream and transportHop policySuccess
authauth: {email, password}auth, REST2 s, 2 attempts (read-only)202 + user
log (no via or "event")log: {name, data}RabbitMQ publish, log.info1 s, 3 attempts202 "queued via RabbitMQ"
log + via: "rest", "rpc", "grpc"samelogger over that transport1 s, 3 attempts, same key202 + entry id
mailmail: {from, to, subject, message}mailer, REST, through the breaker5 s in cmd/broker (3 s in the all-in-one system), 2 attempts, same key202
anything else—none—400

Fix / how to use it: keep the router dumb and the policy explicit. The test TestActionRouter above checks every row of this table, including the 400s; TestRetriesReuseOneIdempotencyKey checks that three attempts carry the same key.

Authentication service: Postgres and bcrypt Must-know ​

In plain words: POST /authenticate takes an email and a password, loads the user from Postgres, compares the password with the stored bcrypt hash, logs the login through the logger service and returns the user without the hash.

Common misunderstanding: "Return 404 for an unknown email and 401 for a wrong password." That tells an attacker which emails exist. The service answers the same 401 body for both and spends the same bcrypt time on the unknown-email path by comparing against a dummy hash. A second one: "DB down is a failed login." It is not; it is a 503 so the broker can report an outage instead of telling a user their password is wrong.

Definition: auth.Service.Authenticate(ctx, AuthPayload) is transport-free; Routes() adds POST /authenticate and /healthz, /readyz (readiness pings Postgres). bcrypt.CompareHashAndPassword(hash, password) from golang.org/x/crypto/bcrypt returns nil on match; bcrypt.DefaultCost is 10 and tests use bcrypt.MinCost (4) to stay fast. PostgresStore uses database/sql with the pgx driver (sql.Open("pgx", dsn), QueryRowContext with a 500 ms budget). Password hashing in depth is in Hashing & Crypto and Authentication in Go.

     broker                    authentication-service                Postgres          logger-service
1    POST /authenticate ─────▶ ReadJSON {email, password}
2                              ByEmail(ctx 500ms) ─────────────────▶ SELECT ... WHERE email = $1
3                              ◀──────────────────────────────────── row (hash $2a$10$...)
4                              CompareHashAndPassword: ok
5                              Audit.Log(ctx) ──────────────────────────────────────────────▶ POST /log
6    ◀── 202 {"data":{"id":1,"email":...}}     (no hash in the body; audit failure only logs a warning)

Real scenario: a login form; a CLI that exchanges credentials for a token; an admin tool that checks a password before a dangerous action; a migration where the user table moves out of the monolith first.

CaseStatusBody messageWhy
Right password202Authenticated <email>The broker's contract uses 202 for every accepted action
Wrong password401invalid credentialsSame as unknown email
Unknown email401invalid credentialsDummy bcrypt compare keeps the timing similar
Inactive user401invalid credentialsDo not reveal account state
Postgres unreachable503user store unavailableOutage, not a credential problem; no internal address leaked
Malformed JSON400bad JSON: ...Validation

The schema the service owns (no other service reads it; database per service):

sql
-- authentication-service owns this table; nobody else connects to it
CREATE TABLE IF NOT EXISTS users (
    id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email         text        NOT NULL UNIQUE,
    first_name    text        NOT NULL DEFAULT '',
    last_name     text        NOT NULL DEFAULT '',
    password_hash bytea       NOT NULL,          -- bcrypt, 60 bytes, "$2a$10$..."
    active        boolean     NOT NULL DEFAULT true,
    created_at    timestamptz NOT NULL DEFAULT now(),
    updated_at    timestamptz NOT NULL DEFAULT now()
);
-- seed one user; the hash comes from bcrypt.GenerateFromPassword, never from SQL
INSERT INTO users (email, first_name, last_name, password_hash)
VALUES ('admin@example.test', 'Ada', 'Lovelace', convert_to('$2a$10$REPLACE_WITH_A_REAL_HASH', 'UTF8'));
-- the one query the service runs
SELECT id, email, first_name, last_name, password_hash, active FROM users WHERE email = $1;

Fix / how to use it:

go
// Package auth is the authentication service: POST /authenticate
// checks an email and password against bcrypt hashes stored in
// Postgres, logs the outcome through the logger service, and returns
// the user without the hash.
package auth

import (
	"context"
	"errors"
	"log/slog"
	"net/http"

	"golang.org/x/crypto/bcrypt"

	"academy/microservices-project/contracts"
	"academy/microservices-project/platform/health"
	"academy/microservices-project/platform/web"
)

// ErrNotFound is returned by a Store when no user has that email.
var ErrNotFound = errors.New("user not found")

// ErrInvalidCredentials is the only failure the caller ever sees, for
// an unknown email and for a wrong password alike.
var ErrInvalidCredentials = errors.New("invalid credentials")

// User is a row of the users table.
type User struct {
	ID           int64
	Email        string
	FirstName    string
	LastName     string
	PasswordHash []byte
	Active       bool
}

// Store reads users. Postgres in production, memory in tests.
type Store interface {
	ByEmail(ctx context.Context, email string) (User, error)
	Ping(ctx context.Context) error
}

// Logger sends an audit entry to the logger service.
type Logger interface {
	Log(ctx context.Context, p contracts.LogPayload) error
}

// Service is the auth service's handler set.
type Service struct {
	Store Store
	Audit Logger
	Log   *slog.Logger
	// dummyHash keeps the unknown-email path as slow as a wrong
	// password, so response time does not reveal which emails exist.
	dummyHash []byte
}

// New builds a Service.
func New(store Store, audit Logger, log *slog.Logger) *Service {
	h, _ := bcrypt.GenerateFromPassword([]byte("not-a-real-password"), bcrypt.DefaultCost)
	return &Service{Store: store, Audit: audit, Log: log, dummyHash: h}
}

// Authenticate is the business operation, transport-free so the
// monolith version can call it directly.
func (s *Service) Authenticate(ctx context.Context, p contracts.AuthPayload) (contracts.AuthUser, error) {
	u, err := s.Store.ByEmail(ctx, p.Email)
	switch {
	case errors.Is(err, ErrNotFound):
		_ = bcrypt.CompareHashAndPassword(s.dummyHash, []byte(p.Password))
		return contracts.AuthUser{}, ErrInvalidCredentials
	case err != nil:
		return contracts.AuthUser{}, err // DB down: a 503, not a 401
	}
	if !u.Active || bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(p.Password)) != nil {
		return contracts.AuthUser{}, ErrInvalidCredentials
	}
	if s.Audit != nil {
		// Audit failure must not fail a login: log it and continue.
		if err := s.Audit.Log(ctx, contracts.LogPayload{Name: "authentication", Data: u.Email + " logged in"}); err != nil {
			s.Log.WarnContext(ctx, "audit log failed", "err", err)
		}
	}
	return contracts.AuthUser{ID: u.ID, Email: u.Email, FirstName: u.FirstName, LastName: u.LastName}, nil
}

// Routes returns the service's HTTP handler.
func (s *Service) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /authenticate", s.handleAuthenticate)
	health.Handler{Checks: map[string]health.Check{"postgres": s.Store.Ping}}.Register(mux)
	return web.RequestIDMiddleware(mux)
}

func (s *Service) handleAuthenticate(w http.ResponseWriter, r *http.Request) {
	var p contracts.AuthPayload
	if err := web.ReadJSON(w, r, &p); err != nil {
		web.ErrorJSON(w, http.StatusBadRequest, err)
		return
	}
	u, err := s.Authenticate(r.Context(), p)
	switch {
	case errors.Is(err, ErrInvalidCredentials):
		web.ErrorJSON(w, http.StatusUnauthorized, err)
		return
	case err != nil:
		s.Log.ErrorContext(r.Context(), "user lookup failed", "err", err)
		web.ErrorJSON(w, http.StatusServiceUnavailable, errors.New("user store unavailable"))
		return
	}
	web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: "Authenticated " + u.Email, Data: u})
}

// MemoryStore is an in-memory Store for tests and the monolith demo.
type MemoryStore struct {
	Users map[string]User
	Err   error // set to simulate "DB down"
}

func (m *MemoryStore) ByEmail(ctx context.Context, email string) (User, error) {
	if m.Err != nil {
		return User{}, m.Err
	}
	u, ok := m.Users[email]
	if !ok {
		return User{}, ErrNotFound
	}
	return u, nil
}

func (m *MemoryStore) Ping(ctx context.Context) error { return m.Err }
go
package auth

import (
	"context"
	"database/sql"
	"errors"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver
)

// PostgresStore reads users through database/sql with the pgx driver.
// Compile-only in this module: the tests use MemoryStore.
type PostgresStore struct {
	DB *sql.DB
}

// OpenPostgres opens the pool. dsn uses the Compose service name as the
// host, for example "postgres://auth:secret@postgres:5432/users".
func OpenPostgres(dsn string) (*PostgresStore, error) {
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)
	db.SetConnMaxIdleTime(5 * time.Minute)
	return &PostgresStore{DB: db}, nil
}

const byEmailSQL = `SELECT id, email, first_name, last_name, password_hash, active
FROM users WHERE email = $1`

func (p *PostgresStore) ByEmail(ctx context.Context, email string) (User, error) {
	ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
	defer cancel()
	var u User
	err := p.DB.QueryRowContext(ctx, byEmailSQL, email).
		Scan(&u.ID, &u.Email, &u.FirstName, &u.LastName, &u.PasswordHash, &u.Active)
	if errors.Is(err, sql.ErrNoRows) {
		return User{}, ErrNotFound
	}
	return u, err
}

func (p *PostgresStore) Ping(ctx context.Context) error { return p.DB.PingContext(ctx) }
go
package auth

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"golang.org/x/crypto/bcrypt"

	"academy/microservices-project/contracts"
)

type auditSpy struct{ got []contracts.LogPayload }

func (a *auditSpy) Log(ctx context.Context, p contracts.LogPayload) error {
	a.got = append(a.got, p)
	return nil
}

func newTestService(t *testing.T) (*Service, *MemoryStore, *auditSpy) {
	t.Helper()
	hash, err := bcrypt.GenerateFromPassword([]byte("verysecret"), bcrypt.MinCost)
	if err != nil {
		t.Fatal(err)
	}
	store := &MemoryStore{Users: map[string]User{
		"admin@example.test": {ID: 1, Email: "admin@example.test", FirstName: "Ada", PasswordHash: hash, Active: true},
	}}
	spy := &auditSpy{}
	s := New(store, spy, slog.New(slog.DiscardHandler))
	return s, store, spy
}

func post(t *testing.T, h http.Handler, body string) *httptest.ResponseRecorder {
	t.Helper()
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/authenticate", strings.NewReader(body)))
	return rec
}

func TestAuthenticate(t *testing.T) {
	s, store, spy := newTestService(t)
	h := s.Routes()

	rec := post(t, h, `{"email":"admin@example.test","password":"verysecret"}`)
	if rec.Code != http.StatusAccepted {
		t.Fatalf("good password: %d %s", rec.Code, rec.Body)
	}
	if bytes.Contains(rec.Body.Bytes(), []byte("$2a$")) {
		t.Fatal("hash leaked in response")
	}
	if len(spy.got) != 1 || spy.got[0].Name != "authentication" {
		t.Fatalf("audit entry missing: %+v", spy.got)
	}

	wrong := post(t, h, `{"email":"admin@example.test","password":"nope"}`)
	unknown := post(t, h, `{"email":"ghost@example.test","password":"nope"}`)
	if wrong.Code != 401 || unknown.Code != 401 {
		t.Fatalf("wrong=%d unknown=%d, want 401 for both", wrong.Code, unknown.Code)
	}
	wb, _ := io.ReadAll(wrong.Body)
	ub, _ := io.ReadAll(unknown.Body)
	if !bytes.Equal(wb, ub) {
		t.Fatalf("responses differ, which reveals which emails exist:\n%s\n%s", wb, ub)
	}

	store.Err = errors.New("dial tcp postgres:5432: connect: connection refused")
	down := post(t, h, `{"email":"admin@example.test","password":"verysecret"}`)
	if down.Code != http.StatusServiceUnavailable {
		t.Fatalf("DB down must be 503, got %d", down.Code)
	}
	var resp contracts.JSONResponse
	_ = json.Unmarshal(down.Body.Bytes(), &resp)
	if strings.Contains(resp.Message, "postgres:5432") {
		t.Fatal("internal address leaked to the caller")
	}
}

func TestBadJSON(t *testing.T) {
	s, _, _ := newTestService(t)
	if rec := post(t, s.Routes(), `{"email":`); rec.Code != http.StatusBadRequest {
		t.Fatalf("got %d", rec.Code)
	}
}

Logger service: MongoDB, one core and three transports Must-know ​

In plain words: The logger stores {name, data, request_id} documents in MongoDB. Its one business method, Write, is exposed three ways (REST on :80, net/rpc on :5001, gRPC on :50001) so the same operation can be compared over each transport, and a fourth caller, the listener, reaches it through REST.

Common misunderstanding: "Three transports means three implementations." It means three thin adapters around one core. Validation (ErrInvalid), idempotency and the store live in Service.Write; each adapter only maps its own input and its own error format (422 for REST, a string for net/rpc, codes.InvalidArgument for gRPC).

Definition: logger.Service.Write(ctx, key, payload) validates, uses key as the document _id (or generates one), stamps the request ID from ctx and calls Store.Insert, which must be idempotent on _id. MongoStore.Insert does UpdateOne filtered on _id with $setOnInsert (the other fields; _id comes from the filter) and SetUpsert(true) and reports UpsertedCount == 1 as "inserted". RPCServer.LogInfo(RPCPayload, *string) error is the net/rpc method; GRPCServer.WriteLog implements the generated LogServiceServer and embeds UnimplementedLogServiceServer. MongoDB itself is in MongoDB with Go.

     transport          adapter                            core (Service.Write)          store
1    REST  POST /log    ReadJSON, key = Idempotency-Key ─▶ validate, _id = key ────────▶ UpdateOne(_id, $setOnInsert, upsert)
2    RPC   LogInfo      RPCPayload{Key, RequestID, Trace} ─▶ same
3    gRPC  WriteLog     req.Entry, ctx with grpc-timeout ─▶ same
4    duplicate key      any transport                      upsert matches, UpsertedCount 0 -> "duplicate", no error

Real scenario: an audit trail of logins; the listener draining a backlog of events after an outage; an operator comparing transport latency; an incident where the broker retried after a timeout and the logger must not store the entry twice.

TransportBad inputStore downDeadlineRequest ID arrives via
REST422 JSON503 JSONClient timeout onlyX-Request-ID header
net/rpcrpc.ServerError("log entry needs a name")Fixed string log store unavailable (no internal text)Server invents 2 sRPCPayload.RequestID field
gRPCcodes.InvalidArgumentcodes.Unavailablegrpc-timeout, server ctx expiresLogEntry.request_id field (key in idempotency_key)

Fix / how to use it:

go
// Package logger is the logger service. One business operation (Write)
// is exposed three ways so the broker can compare them: REST/JSON on
// POST /log, net/rpc (RPCServer.LogInfo, gob over TCP) and gRPC
// (logs.v1.LogService/WriteLog). Entries go to MongoDB in production.
package logger

import (
	"context"
	"errors"
	"log/slog"
	"net/http"
	"sync"
	"time"

	"go.opentelemetry.io/otel/trace"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"academy/microservices-project/contracts"
	logsv1 "academy/microservices-project/gen/logs/v1"
	"academy/microservices-project/platform/health"
	"academy/microservices-project/platform/web"
	"academy/microservices-project/tracing"
)

// ErrInvalid is returned for an entry without a name.
var ErrInvalid = errors.New("log entry needs a name")

// ErrUnavailable is the fixed text sent to net/rpc clients when the
// store fails; net/rpc can only carry a string.
var ErrUnavailable = errors.New("log store unavailable")

// Entry is one stored log document.
type Entry struct {
	ID        string    `bson:"_id"`
	Name      string    `bson:"name"`
	Data      string    `bson:"data"`
	RequestID string    `bson:"request_id"`
	CreatedAt time.Time `bson:"created_at"`
}

// Store persists entries. Insert must be idempotent on Entry.ID: a
// second insert with the same ID is not an error and stores nothing.
type Store interface {
	Insert(ctx context.Context, e Entry) (inserted bool, err error)
	Ping(ctx context.Context) error
}

// Service is the transport-free core.
type Service struct {
	Store Store
	Log   *slog.Logger
	Now   func() time.Time
}

// Write validates and stores one entry. key is the idempotency key
// (event ID or Idempotency-Key header); empty means "generate one".
func (s *Service) Write(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	if p.Name == "" {
		return "", ErrInvalid
	}
	if key == "" {
		key = web.NewID()
	}
	now := time.Now
	if s.Now != nil {
		now = s.Now
	}
	inserted, err := s.Store.Insert(ctx, Entry{ID: key, Name: p.Name, Data: p.Data, RequestID: web.RequestID(ctx), CreatedAt: now().UTC()})
	if err != nil {
		return "", err
	}
	s.Log.InfoContext(ctx, "log entry", "id", key, "name", p.Name, "duplicate", !inserted)
	return key, nil
}

// Routes is the REST/JSON transport.
func (s *Service) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /log", func(w http.ResponseWriter, r *http.Request) {
		var p contracts.LogPayload
		if err := web.ReadJSON(w, r, &p); err != nil {
			web.ErrorJSON(w, http.StatusBadRequest, err)
			return
		}
		id, err := s.Write(r.Context(), r.Header.Get(contracts.HeaderIdempotencyKey), p)
		switch {
		case errors.Is(err, ErrInvalid):
			web.ErrorJSON(w, http.StatusUnprocessableEntity, err)
		case err != nil:
			web.ErrorJSON(w, http.StatusServiceUnavailable, errors.New("log store unavailable"))
		default:
			web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: "logged", Data: map[string]string{"id": id}})
		}
	})
	health.Handler{Checks: map[string]health.Check{"mongo": s.Store.Ping}}.Register(mux)
	return web.RequestIDMiddleware(mux)
}

// RPCPayload is the net/rpc argument. Exported type, exported fields:
// gob only encodes exported fields.
type RPCPayload struct {
	Name      string
	Data      string
	RequestID string
	Key       string
	Trace     map[string]string // W3C traceparent, carried by hand
}

// RPCServer is registered with rpc.Register; its exported methods of
// the form func(T1, *T2) error become "RPCServer.<Method>".
type RPCServer struct {
	Svc     *Service
	Timeout time.Duration
	Tracer  trace.Tracer // optional; net/rpc has no instrumentation
}

// LogInfo stores one entry. net/rpc gives the method no context, so it
// builds its own with a fixed timeout: the caller's deadline is lost.
func (r *RPCServer) LogInfo(p RPCPayload, reply *string) error {
	timeout := r.Timeout
	if timeout == 0 {
		timeout = 2 * time.Second
	}
	ctx := tracing.Extract(context.Background(), p.Trace)
	if r.Tracer != nil {
		var span trace.Span
		ctx, span = r.Tracer.Start(ctx, "RPCServer.LogInfo", trace.WithSpanKind(trace.SpanKindServer))
		defer span.End()
	}
	ctx, cancel := context.WithTimeout(web.WithRequestID(ctx, p.RequestID), timeout)
	defer cancel()
	id, err := r.Svc.Write(ctx, p.Key, contracts.LogPayload{Name: p.Name, Data: p.Data})
	switch {
	case errors.Is(err, ErrInvalid):
		return err // the client receives only err.Error() as a string
	case err != nil:
		// Never send internal error text over the wire; the client maps
		// this fixed string to a retryable 503.
		r.Svc.Log.ErrorContext(ctx, "rpc write failed", "err", err)
		return ErrUnavailable
	}
	*reply = "Processed payload via RPC: " + id
	return nil
}

// GRPCServer implements logsv1.LogServiceServer.
type GRPCServer struct {
	logsv1.UnimplementedLogServiceServer
	Svc *Service
}

// WriteLog stores one entry; ctx carries the client's deadline.
func (g *GRPCServer) WriteLog(ctx context.Context, req *logsv1.WriteLogRequest) (*logsv1.WriteLogResponse, error) {
	e := req.GetEntry()
	if e.GetRequestId() != "" {
		ctx = web.WithRequestID(ctx, e.GetRequestId())
	}
	id, err := g.Svc.Write(ctx, e.GetIdempotencyKey(), contracts.LogPayload{Name: e.GetName(), Data: e.GetData()})
	switch {
	case errors.Is(err, ErrInvalid):
		return nil, status.Error(codes.InvalidArgument, err.Error())
	case errors.Is(err, context.DeadlineExceeded):
		return nil, status.Error(codes.DeadlineExceeded, err.Error())
	case err != nil:
		return nil, status.Error(codes.Unavailable, "log store unavailable")
	}
	return &logsv1.WriteLogResponse{Id: id, Result: "logged via gRPC"}, nil
}

// MemoryStore is an idempotent in-memory Store.
type MemoryStore struct {
	mu      sync.Mutex
	Entries []Entry
	seen    map[string]bool
	Err     error
	Delay   time.Duration
}

func (m *MemoryStore) Insert(ctx context.Context, e Entry) (bool, error) {
	if m.Delay > 0 {
		t := time.NewTimer(m.Delay)
		defer t.Stop()
		select {
		case <-ctx.Done():
			return false, ctx.Err()
		case <-t.C:
		}
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.Err != nil {
		return false, m.Err
	}
	if m.seen == nil {
		m.seen = map[string]bool{}
	}
	if m.seen[e.ID] {
		return false, nil
	}
	m.seen[e.ID] = true
	m.Entries = append(m.Entries, e)
	return true, nil
}

func (m *MemoryStore) Ping(ctx context.Context) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.Err
}

// All returns a copy of the stored entries.
func (m *MemoryStore) All() []Entry {
	m.mu.Lock()
	defer m.mu.Unlock()
	return append([]Entry(nil), m.Entries...)
}
go
package logger

import (
	"context"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
	"go.mongodb.org/mongo-driver/v2/mongo/readpref"
)

// MongoStore stores entries in the "logs" collection. Compile-only in
// this module; tests use MemoryStore. See /go/mongodb-with-go.
type MongoStore struct {
	Client *mongo.Client
	Coll   *mongo.Collection
}

// OpenMongo connects with the Compose service name as host, for
// example "mongodb://admin:secret@mongo:27017".
func OpenMongo(uri string) (*MongoStore, error) {
	c, err := mongo.Connect(options.Client().ApplyURI(uri).SetServerSelectionTimeout(2 * time.Second))
	if err != nil {
		return nil, err
	}
	return &MongoStore{Client: c, Coll: c.Database("logs").Collection("logs")}, nil
}

// Insert upserts on _id, so a redelivered event stores nothing new.
func (m *MongoStore) Insert(ctx context.Context, e Entry) (bool, error) {
	res, err := m.Coll.UpdateOne(ctx,
		bson.D{{Key: "_id", Value: e.ID}},
		bson.D{{Key: "$setOnInsert", Value: bson.D{ // _id comes from the filter
			{Key: "name", Value: e.Name},
			{Key: "data", Value: e.Data},
			{Key: "request_id", Value: e.RequestID},
			{Key: "created_at", Value: e.CreatedAt},
		}}},
		options.UpdateOne().SetUpsert(true))
	if err != nil {
		return false, err
	}
	return res.UpsertedCount == 1, nil
}

func (m *MongoStore) Ping(ctx context.Context) error { return m.Client.Ping(ctx, readpref.Primary()) }
go
package logger

import (
	"context"
	"errors"
	"log/slog"
	"net"
	"net/http"
	"net/http/httptest"
	"net/rpc"
	"strings"
	"testing"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"

	"academy/microservices-project/contracts"
	logsv1 "academy/microservices-project/gen/logs/v1"
)

func newSvc() (*Service, *MemoryStore) {
	st := &MemoryStore{}
	return &Service{Store: st, Log: slog.New(slog.DiscardHandler)}, st
}

func TestRESTIsIdempotentOnKey(t *testing.T) {
	svc, st := newSvc()
	srv := httptest.NewServer(svc.Routes())
	defer srv.Close()
	for range 2 { // the broker retried after a timeout
		req, _ := http.NewRequest(http.MethodPost, srv.URL+"/log", strings.NewReader(`{"name":"event","data":"x"}`))
		req.Header.Set(contracts.HeaderIdempotencyKey, "k-1")
		req.Header.Set(contracts.HeaderRequestID, "r-9")
		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Fatal(err)
		}
		resp.Body.Close()
		if resp.StatusCode != http.StatusAccepted {
			t.Fatalf("status %d", resp.StatusCode)
		}
	}
	if got := st.All(); len(got) != 1 || got[0].RequestID != "r-9" {
		t.Fatalf("entries %+v, want exactly one with request id r-9", got)
	}
}

func TestNetRPCRegisterDialCall(t *testing.T) {
	svc, st := newSvc()
	server := rpc.NewServer()
	if err := server.Register(&RPCServer{Svc: svc}); err != nil {
		t.Fatal(err)
	}
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer lis.Close()
	go server.Accept(lis)

	client, err := rpc.Dial("tcp", lis.Addr().String())
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	var reply string
	err = client.Call("RPCServer.LogInfo", RPCPayload{Name: "event", Data: "via rpc", RequestID: "r-5", Key: "k-5"}, &reply)
	if err != nil || !strings.HasPrefix(reply, "Processed payload via RPC") {
		t.Fatalf("reply=%q err=%v", reply, err)
	}
	if e := st.All(); len(e) != 1 || e[0].RequestID != "r-5" {
		t.Fatalf("entries %+v", e)
	}

	// Limit 1: errors cross the wire as strings. errors.Is cannot see
	// ErrInvalid any more; the client gets an rpc.ServerError.
	err = client.Call("RPCServer.LogInfo", RPCPayload{}, &reply)
	var se rpc.ServerError
	if !errors.As(err, &se) || errors.Is(err, ErrInvalid) || string(se) != ErrInvalid.Error() {
		t.Fatalf("got %T %v", err, err)
	}

	// Limit 2: Call takes no context. A deadline needs Go + select, and
	// the server keeps working after the client gave up.
	st.Delay = 200 * time.Millisecond
	ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
	defer cancel()
	call := client.Go("RPCServer.LogInfo", RPCPayload{Name: "slow", Key: "k-6"}, &reply, nil)
	select {
	case <-call.Done:
		t.Fatal("slow call finished before the deadline")
	case <-ctx.Done():
	}
	<-call.Done // the server still finished the work nobody waited for
	if len(st.All()) != 2 {
		t.Fatal("server did not keep working after the client deadline")
	}
}

func TestGRPCOverBufconn(t *testing.T) {
	svc, st := newSvc()
	lis := bufconn.Listen(1 << 20)
	srv := grpc.NewServer()
	logsv1.RegisterLogServiceServer(srv, &GRPCServer{Svc: svc})
	go srv.Serve(lis)
	defer srv.Stop()

	conn, err := grpc.NewClient("passthrough:///bufnet",
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) }),
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	client := logsv1.NewLogServiceClient(conn)

	ctx, cancel := context.WithTimeout(t.Context(), time.Second)
	defer cancel()
	resp, err := client.WriteLog(ctx, &logsv1.WriteLogRequest{Entry: &logsv1.LogEntry{Name: "event", Data: "via grpc", RequestId: "r-7"}})
	if err != nil || resp.GetId() == "" {
		t.Fatalf("resp=%v err=%v", resp, err)
	}
	if e := st.All(); len(e) != 1 || e[0].RequestID != "r-7" {
		t.Fatalf("entries %+v", e)
	}

	// A retried call with the same idempotency key stores nothing new.
	for range 2 {
		if _, err := client.WriteLog(ctx, &logsv1.WriteLogRequest{Entry: &logsv1.LogEntry{Name: "event", IdempotencyKey: "k-g"}}); err != nil {
			t.Fatal(err)
		}
	}
	if e := st.All(); len(e) != 2 {
		t.Fatalf("entries %d, want 2 (one plain, one keyed)", len(e))
	}

	_, err = client.WriteLog(ctx, &logsv1.WriteLogRequest{Entry: &logsv1.LogEntry{}})
	if status.Code(err) != codes.InvalidArgument {
		t.Fatalf("got %v, want InvalidArgument", err)
	}

	// The deadline travels as grpc-timeout; the server's ctx expires too.
	st.Delay = 200 * time.Millisecond
	short, cancel2 := context.WithTimeout(t.Context(), 30*time.Millisecond)
	defer cancel2()
	_, err = client.WriteLog(short, &logsv1.WriteLogRequest{Entry: &logsv1.LogEntry{Name: "slow"}})
	if status.Code(err) != codes.DeadlineExceeded {
		t.Fatalf("got %v, want DeadlineExceeded", err)
	}
}

Mailer service: SMTP via go-mail/gomail and templates Important ​

In plain words: POST /send renders an HTML body and a plain-text body from embedded templates, builds a multipart/alternative message and hands it to SMTP. In development the SMTP server is Mailpit, which keeps every message for you to look at.

Common misunderstanding: "Use text/template for both bodies." The HTML part must use html/template, which escapes <script> into &lt;script&gt;; the plain part uses text/template and stays literal. The test TestRenderEscapesHTMLAndKeepsPlain asserts both. Another: "gomail is the library." gopkg.in/gomail.v2 ("Gomail is a simple and efficient package to send emails") still works, but its latest version on the Go proxy is a 2016 pseudo-version; github.com/wneessen/go-mail is maintained ("a modern, feature-rich library for composing and sending mail with Go") and takes a context (DialAndSendWithContext).

Definition: mailer.New parses templates/mail.html.gohtml and templates/mail.plain.gohtml from an embed.FS once at startup. Service.Send(ctx, key, payload) renders, then claims the idempotency key under a mutex before sending (in memory, per process): a concurrent duplicate, such as an overlapping retry after a timeout, waits for the first send's outcome and reports "already sent" instead of sending again; a failed send releases the claim so a later retry can try (TestConcurrentSameKeySendsOnce, two calls with one key and a blocking sender: one send). SMTPSender uses go-mail v0.7.2: mail.NewMsg(), From, To, Subject, SetMessageID, SetBodyString(mail.TypeTextPlain, ...), AddAlternativeString(mail.TypeTextHTML, ...), mail.NewClient(host, mail.WithPort, mail.WithTLSPolicy, mail.WithSMTPAuth, mail.WithDialContextFunc, mail.WithTimeout, ...) and DialAndSendWithContext(ctx, m). What the context bounds is easy to get wrong: in go-mail v0.7.2 DialAndSendWithContext uses ctx for the dial only; the SMTP conversation after it (SendWithSMTPClient) runs under go-mail's own per-step timeout (DefaultTimeout, 15 s), not under ctx. SMTPSender therefore dials the connection itself through WithDialContextFunc and registers context.AfterFunc(ctx, conn.Close), so a server that accepted the message and then stalls is cut when the caller's ctx ends, and Send returns ctx.Err(); it also lowers go-mail's per-step timeout to what is left of the budget (TestSMTPStallIsBoundedByCtx: a fake SMTP server that never answers after DATA, cut at 150 ms). What is not knowable: whether a server that had already queued the message before the close delivers it, which is why the idempotency key exists. The handler maps ErrInvalid to 422, a context deadline to 504 and any other SMTP error to 502. Template syntax is in Strings, Runes, fmt & text/template and html/template.

     broker                 mailer-service                                   Mailpit (SMTP :1025)
1    POST /send ──────────▶ Render: html/template + text/template
2                           key seen? no
3                           go-mail DialAndSendWithContext(ctx 3s) ────────▶ 220, EHLO, MAIL FROM, RCPT TO, DATA
4                           ◀──────────────────────────────────────────────── 250 queued
5    ◀── 202 "sent to a@example.test"
6    retry with same key ─▶ key seen: 202 "already sent", no second mail

Real scenario: a welcome email after signup; a password-reset email (where a duplicate is harmless but two different reset links confuse users); a slow provider during a marketing send; a staging environment where nobody must receive real mail (Mailpit).

SMTP setupHost:portSMTPConfigNotes
Mailpit in Composemailpit:1025TLS: false, no authWeb UI on :8025 shows every message
Provider, submissionsmtp.provider.example:587TLS: true, username/passwordTLSMandatory: refuse to send in clear
Fake server in tests127.0.0.1:<random>no TLS, no authTestGoMailAgainstFakeSMTP speaks real SMTP to go-mail

Fix / how to use it:

go
// Package mailer is the mailer service: POST /send renders an HTML and
// a plain-text body from templates and hands the message to a Sender.
// In production the Sender is go-mail talking SMTP to Mailpit or a
// provider; in tests it is a fake.
package mailer

import (
	"bytes"
	"context"
	"embed"
	"errors"
	htmltemplate "html/template"
	"log/slog"
	"net/http"
	"sync"
	texttemplate "text/template"

	"academy/microservices-project/contracts"
	"academy/microservices-project/platform/health"
	"academy/microservices-project/platform/web"
)

//go:embed templates
var templateFS embed.FS

// Rendered is a message ready for SMTP.
type Rendered struct {
	From, To, Subject string
	HTML, Plain       string
	Key               string // idempotency key, also used as Message-ID seed
}

// Sender delivers one message.
type Sender interface {
	Send(ctx context.Context, m Rendered) error
}

// ErrInvalid is returned for a message without recipient or subject.
var ErrInvalid = errors.New("mail needs to, subject and message")

// Service renders and sends mail.
type Service struct {
	Sender      Sender
	DefaultFrom string
	Log         *slog.Logger

	html  *htmltemplate.Template
	plain *texttemplate.Template

	mu   sync.Mutex
	sent map[string]*claim // idempotency keys: in flight or sent
}

// New parses the embedded templates once at startup.
func New(sender Sender, from string, log *slog.Logger) (*Service, error) {
	h, err := htmltemplate.ParseFS(templateFS, "templates/mail.html.gohtml")
	if err != nil {
		return nil, err
	}
	p, err := texttemplate.ParseFS(templateFS, "templates/mail.plain.gohtml")
	if err != nil {
		return nil, err
	}
	return &Service{Sender: sender, DefaultFrom: from, Log: log, html: h, plain: p, sent: map[string]*claim{}}, nil
}

// Render builds both bodies. html/template escapes the message.
func (s *Service) Render(ctx context.Context, p contracts.MailPayload) (Rendered, error) {
	if p.To == "" || p.Subject == "" || p.Message == "" {
		return Rendered{}, ErrInvalid
	}
	data := map[string]string{"Message": p.Message, "RequestID": web.RequestID(ctx)}
	var hb, pb bytes.Buffer
	if err := s.html.ExecuteTemplate(&hb, "body", data); err != nil {
		return Rendered{}, err
	}
	if err := s.plain.ExecuteTemplate(&pb, "body", data); err != nil {
		return Rendered{}, err
	}
	from := p.From
	if from == "" {
		from = s.DefaultFrom
	}
	return Rendered{From: from, To: p.To, Subject: p.Subject, HTML: hb.String(), Plain: pb.String()}, nil
}

// claim is the state of one idempotency key: in flight until done is
// closed, then sent (ok) or failed (the claim is removed so a retry may
// try again).
type claim struct {
	done chan struct{}
	ok   bool
}

// Send renders and sends, at most once per idempotency key (in this
// process; a shared store would make it per cluster). The key is
// claimed under the lock BEFORE sending, so a concurrent duplicate (an
// overlapping retry) waits for the first send instead of sending again.
func (s *Service) Send(ctx context.Context, key string, p contracts.MailPayload) (duplicate bool, err error) {
	m, err := s.Render(ctx, p)
	if err != nil {
		return false, err
	}
	m.Key = key
	if key == "" {
		return false, s.deliver(ctx, m)
	}
	for {
		s.mu.Lock()
		c, ok := s.sent[key]
		if !ok { // first: claim the key, send outside the lock
			c = &claim{done: make(chan struct{})}
			s.sent[key] = c
			s.mu.Unlock()
			err := s.deliver(ctx, m)
			s.mu.Lock()
			c.ok = err == nil
			if err != nil {
				delete(s.sent, key) // let a later retry try again
			}
			close(c.done)
			s.mu.Unlock()
			return false, err
		}
		s.mu.Unlock()
		select { // a duplicate: wait for the first send's outcome
		case <-c.done:
		case <-ctx.Done():
			return false, ctx.Err()
		}
		s.mu.Lock()
		sentOK := c.ok
		s.mu.Unlock()
		if sentOK {
			return true, nil
		}
		// the first send failed and released the claim: loop and claim it
	}
}

func (s *Service) deliver(ctx context.Context, m Rendered) error {
	if err := s.Sender.Send(ctx, m); err != nil {
		return err
	}
	s.Log.InfoContext(ctx, "mail sent", "to", m.To, "subject", m.Subject)
	return nil
}

// Routes is the HTTP transport.
func (s *Service) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /send", func(w http.ResponseWriter, r *http.Request) {
		var p contracts.MailPayload
		if err := web.ReadJSON(w, r, &p); err != nil {
			web.ErrorJSON(w, http.StatusBadRequest, err)
			return
		}
		dup, err := s.Send(r.Context(), r.Header.Get(contracts.HeaderIdempotencyKey), p)
		switch {
		case errors.Is(err, ErrInvalid):
			web.ErrorJSON(w, http.StatusUnprocessableEntity, err)
		case errors.Is(err, context.DeadlineExceeded):
			web.ErrorJSON(w, http.StatusGatewayTimeout, errors.New("smtp server too slow"))
		case err != nil:
			s.Log.ErrorContext(r.Context(), "smtp failed", "err", err)
			web.ErrorJSON(w, http.StatusBadGateway, errors.New("smtp delivery failed"))
		default:
			msg := "sent to " + p.To
			if dup {
				msg = "already sent"
			}
			web.WriteJSON(w, http.StatusAccepted, contracts.JSONResponse{Message: msg})
		}
	})
	health.Handler{}.Register(mux)
	return web.RequestIDMiddleware(mux)
}
go
package mailer

import (
	"context"
	"net"
	"sync"
	"time"

	"github.com/wneessen/go-mail"
)

// SMTPConfig is read from the environment in cmd/mailer.
type SMTPConfig struct {
	Host     string // "mailpit" in Docker Compose
	Port     int    // 1025 for Mailpit, 587 for a provider
	Username string
	Password string
	TLS      bool
}

// SMTPSender sends with github.com/wneessen/go-mail.
type SMTPSender struct {
	Cfg SMTPConfig
}

// Send builds a multipart/alternative message and delivers it.
//
// What bounds what: go-mail's DialAndSendWithContext uses ctx for the
// dial only; the SMTP conversation after it (EHLO, MAIL, RCPT, DATA,
// the final 250) runs under go-mail's own per-step timeout (15 s by
// default), not under ctx. So this sender dials the TCP connection
// itself (WithDialContextFunc) and registers context.AfterFunc to close
// that connection when ctx ends: any blocked read or write in the
// session then fails at once, and Send returns ctx.Err(). It also
// lowers go-mail's per-step timeout to what is left of the budget.
// Not bounded: nothing; but a message the server already accepted
// before the close may still be delivered (outcome unknown, hence the
// idempotency key in Service.Send).
func (s SMTPSender) Send(ctx context.Context, r Rendered) error {
	m := mail.NewMsg()
	if err := m.From(r.From); err != nil {
		return err
	}
	if err := m.To(r.To); err != nil {
		return err
	}
	m.Subject(r.Subject)
	m.SetMessageID()
	m.SetBodyString(mail.TypeTextPlain, r.Plain)
	m.AddAlternativeString(mail.TypeTextHTML, r.HTML)

	var mu sync.Mutex
	var stops []func() bool
	defer func() {
		mu.Lock()
		defer mu.Unlock()
		for _, stop := range stops {
			stop()
		}
	}()
	dial := func(dctx context.Context, network, addr string) (net.Conn, error) {
		conn, err := (&net.Dialer{}).DialContext(dctx, network, addr)
		if err != nil {
			return nil, err
		}
		// ctx is the caller's, not go-mail's dial ctx (which ends when
		// the dial returns).
		stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
		mu.Lock()
		stops = append(stops, stop)
		mu.Unlock()
		return conn, nil
	}

	policy := mail.NoTLS
	if s.Cfg.TLS {
		policy = mail.TLSMandatory // STARTTLS on the dialled connection
	}
	opts := []mail.Option{mail.WithPort(s.Cfg.Port), mail.WithTLSPolicy(policy), mail.WithDialContextFunc(dial)}
	if dl, ok := ctx.Deadline(); ok {
		if left := time.Until(dl); left > 0 {
			opts = append(opts, mail.WithTimeout(left))
		}
	}
	if s.Cfg.Username != "" {
		opts = append(opts, mail.WithSMTPAuth(mail.SMTPAuthPlain),
			mail.WithUsername(s.Cfg.Username), mail.WithPassword(s.Cfg.Password))
	}
	c, err := mail.NewClient(s.Cfg.Host, opts...)
	if err != nil {
		return err
	}
	if err := c.DialAndSendWithContext(ctx, m); err != nil {
		if ctx.Err() != nil {
			return ctx.Err() // the close was ours: report the real cause
		}
		return err
	}
	return nil
}
gohtml
{{define "body"}}<!doctype html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1"><meta charset="utf-8"></head>
<body>
<p>{{.Message}}</p>
<p style="color:#777">Request {{.RequestID}}</p>
</body>
</html>{{end}}
go
package mailer

import (
	"bufio"
	"context"
	"errors"
	"log/slog"
	"net"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"academy/microservices-project/contracts"
)

type fakeSender struct {
	mu    sync.Mutex
	sent  []Rendered
	delay time.Duration
}

func (f *fakeSender) Send(ctx context.Context, m Rendered) error {
	if f.delay > 0 {
		t := time.NewTimer(f.delay)
		defer t.Stop()
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-t.C:
		}
	}
	f.mu.Lock()
	defer f.mu.Unlock()
	f.sent = append(f.sent, m)
	return nil
}

func TestRenderEscapesHTMLAndKeepsPlain(t *testing.T) {
	s, err := New(&fakeSender{}, "noreply@example.test", slog.New(slog.DiscardHandler))
	if err != nil {
		t.Fatal(err)
	}
	m, err := s.Render(t.Context(), contracts.MailPayload{To: "a@example.test", Subject: "Hi", Message: "<script>x</script>"})
	if err != nil {
		t.Fatal(err)
	}
	if strings.Contains(m.HTML, "<script>") || !strings.Contains(m.HTML, "&lt;script&gt;") {
		t.Fatalf("html not escaped: %s", m.HTML)
	}
	if !strings.Contains(m.Plain, "<script>x</script>") {
		t.Fatalf("plain part should be literal: %s", m.Plain)
	}
}

func TestSendOncePerIdempotencyKey(t *testing.T) {
	fs := &fakeSender{}
	s, _ := New(fs, "noreply@example.test", slog.New(slog.DiscardHandler))
	h := s.Routes()
	for range 2 {
		req := httptest.NewRequest(http.MethodPost, "/send", strings.NewReader(`{"to":"a@example.test","subject":"Hi","message":"hello"}`))
		req.Header.Set(contracts.HeaderIdempotencyKey, "mail-1")
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		if rec.Code != http.StatusAccepted {
			t.Fatalf("status %d", rec.Code)
		}
	}
	if len(fs.sent) != 1 {
		t.Fatalf("sent %d mails, want 1", len(fs.sent))
	}
}

func TestSlowSMTPIsCutByTheCallerDeadline(t *testing.T) {
	s, _ := New(&fakeSender{delay: time.Second}, "noreply@example.test", slog.New(slog.DiscardHandler))
	ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
	defer cancel()
	req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/send", strings.NewReader(`{"to":"a@example.test","subject":"Hi","message":"hello"}`))
	rec := httptest.NewRecorder()
	start := time.Now()
	s.Routes().ServeHTTP(rec, req)
	if rec.Code != http.StatusGatewayTimeout || time.Since(start) > 500*time.Millisecond {
		t.Fatalf("status %d after %v", rec.Code, time.Since(start))
	}
}

// fakeSMTP is a minimal SMTP server: no TLS, no AUTH, one mailbox.
func fakeSMTP(t *testing.T) (addr string, got chan string) {
	t.Helper()
	return fakeSMTPServer(t, false)
}

// fakeSMTPServer with stall=true reads the message after DATA and then
// never answers: a peer that accepted the TCP connection and hangs.
func fakeSMTPServer(t *testing.T, stall bool) (addr string, got chan string) {
	t.Helper()
	lis, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { lis.Close() })
	got = make(chan string, 1)
	go func() {
		c, err := lis.Accept()
		if err != nil {
			return
		}
		defer c.Close()
		r := bufio.NewReader(c)
		say := func(s string) { c.Write([]byte(s + "\r\n")) }
		say("220 fake ESMTP")
		var data strings.Builder
		for {
			line, err := r.ReadString('\n')
			if err != nil {
				return
			}
			cmd := strings.ToUpper(strings.TrimSpace(line))
			switch {
			case strings.HasPrefix(cmd, "EHLO"), strings.HasPrefix(cmd, "HELO"):
				say("250-fake")
				say("250 8BITMIME")
			case strings.HasPrefix(cmd, "MAIL"), strings.HasPrefix(cmd, "RCPT"), strings.HasPrefix(cmd, "RSET"), strings.HasPrefix(cmd, "NOOP"):
				say("250 OK")
			case cmd == "DATA":
				say("354 end with <CRLF>.<CRLF>")
				for {
					l, err := r.ReadString('\n')
					if err != nil || l == ".\r\n" {
						break
					}
					data.WriteString(l)
				}
				if stall {
					time.Sleep(30 * time.Second) // until the test closes us
					return
				}
				say("250 queued")
				got <- data.String()
			case cmd == "QUIT":
				say("221 bye")
				return
			default:
				say("502 not implemented")
			}
		}
	}()
	return lis.Addr().String(), got
}

func TestGoMailAgainstFakeSMTP(t *testing.T) {
	addr, got := fakeSMTP(t)
	host, portStr, _ := net.SplitHostPort(addr)
	port, _ := strconv.Atoi(portStr)
	s, _ := New(SMTPSender{Cfg: SMTPConfig{Host: host, Port: port}}, "noreply@example.test", slog.New(slog.DiscardHandler))
	ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
	defer cancel()
	if _, err := s.Send(ctx, "", contracts.MailPayload{To: "a@example.test", Subject: "Welcome", Message: "hello"}); err != nil {
		t.Fatal(err)
	}
	msg := <-got
	for _, want := range []string{"Subject: Welcome", "multipart/alternative", "text/plain", "text/html"} {
		if !strings.Contains(msg, want) {
			t.Errorf("message lacks %q:\n%s", want, msg)
		}
	}
}

// blockingSender counts calls and blocks each one until release closes.
type blockingSender struct {
	calls   atomic.Int32
	entered chan struct{}
	release chan struct{}
}

func (b *blockingSender) Send(ctx context.Context, m Rendered) error {
	if b.calls.Add(1) == 1 {
		close(b.entered)
	}
	<-b.release
	return nil
}

func TestConcurrentSameKeySendsOnce(t *testing.T) {
	bs := &blockingSender{entered: make(chan struct{}), release: make(chan struct{})}
	s, _ := New(bs, "noreply@example.test", slog.New(slog.DiscardHandler))
	p := contracts.MailPayload{To: "a@example.test", Subject: "Hi", Message: "hello"}
	type res struct {
		dup bool
		err error
	}
	out := make(chan res, 2)
	for range 2 { // the original request and an overlapping retry
		go func() {
			dup, err := s.Send(t.Context(), "mail-c", p)
			out <- res{dup, err}
		}()
	}
	<-bs.entered
	time.Sleep(50 * time.Millisecond) // let the second call reach the claim
	close(bs.release)
	a, b := <-out, <-out
	if a.err != nil || b.err != nil {
		t.Fatalf("errors: %v %v", a.err, b.err)
	}
	if n := bs.calls.Load(); n != 1 {
		t.Fatalf("sender called %d times for one key, want 1", n)
	}
	if a.dup == b.dup {
		t.Fatalf("exactly one call should report a duplicate: %v %v", a.dup, b.dup)
	}
}

func TestSMTPStallIsBoundedByCtx(t *testing.T) {
	addr, _ := fakeSMTPServer(t, true)
	host, portStr, _ := net.SplitHostPort(addr)
	port, _ := strconv.Atoi(portStr)
	sender := SMTPSender{Cfg: SMTPConfig{Host: host, Port: port}}
	m := Rendered{From: "noreply@example.test", To: "a@example.test", Subject: "s", Plain: "p", HTML: "<p>h</p>"}
	ctx, cancel := context.WithTimeout(t.Context(), 150*time.Millisecond)
	defer cancel()
	done := make(chan error, 1)
	start := time.Now()
	go func() { done <- sender.Send(ctx, m) }()
	select {
	case err := <-done:
		if !errors.Is(err, context.DeadlineExceeded) {
			t.Fatalf("got %v, want context.DeadlineExceeded", err)
		}
		if el := time.Since(start); el > 2*time.Second {
			t.Fatalf("send outlived its ctx by %v", el)
		}
	case <-time.After(5 * time.Second):
		t.Fatal("SMTP send ignored the caller's ctx (still blocked after 5 s)")
	}
}

Listener service: the RabbitMQ consumer Must-know ​

In plain words: The listener has no HTTP port. It owns the queue listener.logs, bound to the logs_topic exchange with the binding key log.*, and turns each LogEvent into a REST call to the logger, using the event ID as the idempotency key.

Common misunderstanding: "A message is delivered exactly once." RabbitMQ delivers at least once: a consumer that dies after writing but before acking gets the message again. The listener makes that harmless by passing the event ID as Idempotency-Key, so the logger's upsert ignores the second copy (TestRedeliveredEventIsStoredOnce). A second one: "retry forever." A message the consumer cannot understand (version: 2) will never succeed; it goes to a poison topic instead (TestUnknownVersionGoesToPoison).

Definition: listener.NewRouter(Config) builds a Watermill message.Router with two middlewares, added in this order: Retry{MaxRetries, InitialInterval, Multiplier: 2} (outermost, because Watermill runs the middleware added first outermost) and PoisonQueueWithFilter (only ErrUnknownVersion goes to contracts.LogPoisonKey, "poison.log", with the reason in the reason_poisoned metadata). The filter therefore parks an unknown version at once and Retry sees success; every other error passes through the filter and is retried, and when retries run out the message is nacked and RabbitMQ requeues it (Nack(false, !NoRequeueOnNack) in watermill-amqp). The handler extracts the trace context from message metadata, starts a consumer span, decodes and checks Version == 1, and calls LogWriter.WriteLog(ctx 2s, ev.ID, ...). Returning an error nacks the message after the retries are spent. In production the listener owns the topology and declares it at startup, before it consumes: amqpbus.DeclareListenerTopology declares the durable topic exchange logs_topic, the durable queue listener.logs bound to log.* and the durable queue listener.poison bound to poison.log (TestListenerDeclaresQueuesAndBindings). Without that second binding a poisoned event would be confirmed by RabbitMQ and dropped, and the original acked: lost. The poison middleware publishes through amqpbus.Publisher (mandatory, confirms), so a missing binding is an error, not silence; TestUnknownVersionLandsInThePoisonQueue drives the real router and finds the version: 2 event in listener.poison with its reason_poisoned header. Consumption uses watermill-amqp (listener.AMQPConfig: NewDurableTopicConfig(uri, "logs_topic", "listener.logs"), Exchange.Durable = true to match the declaration, PrefetchCount = 10). The poison routing key deliberately does not match log.*, or the listener would consume its own poison.

     RabbitMQ (logs_topic, topic)       listener-service                         logger-service
1    log.info evt-1 ───────────────────▶ handler: extract trace, decode v1
2                                        WriteLog(ctx 2s, key evt-1) ───────────▶ 503 (Mongo restarting)
3                                        Retry: wait 200ms, x2 ...
4                                        WriteLog(ctx 2s, key evt-1) ───────────▶ 202 (inserted)
5    ◀── ack
6    log.info evt-1 (redelivered) ─────▶ WriteLog(key evt-1) ───────────────────▶ 202 (duplicate, nothing stored)
7    log.info evt-9 version 2 ─────────▶ ErrUnknownVersion -> publish poison.log, ack original

Real scenario: the logger is redeployed while the broker keeps accepting log actions; a burst of 10,000 events after a batch job; a producer deployed with a new event version before the consumer; a consumer crash between the logger write and the ack.

SituationListener doesMessage endsData effect
Logger answers 202AckRemoved from queueOne entry
Logger down for a few secondsRetry with backoff, then nack (requeue)Delivered again laterOne entry after recovery
Same event delivered twiceCalls logger with the same keyAckedStill one entry
Unknown version or bad JSONPublish to poison.logParked for a humanNone
Listener process killed mid-messageNothing (no ack sent)Redelivered to the next consumerOne entry (idempotent)

Fix / how to use it:

go
// Package listener is the listener service: a RabbitMQ consumer bound
// to the logs_topic exchange with the binding key "log.*". For every
// LogEvent it calls the logger service, with the event ID as the
// idempotency key, because the broker delivers at least once.
package listener

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/message/router/middleware"
	"go.opentelemetry.io/otel/trace"
	"go.opentelemetry.io/otel/trace/noop"

	"academy/microservices-project/contracts"
	"academy/microservices-project/platform/web"
	"academy/microservices-project/tracing"
)

// LogWriter is the logger-service client (REST in this project).
type LogWriter interface {
	WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error)
}

// ErrUnknownVersion marks an event this consumer cannot handle; it goes
// to the poison topic instead of being retried forever.
var ErrUnknownVersion = errors.New("unknown event version")

// Config wires the consumer.
type Config struct {
	Sub    message.Subscriber
	Pub    message.Publisher // for the poison topic
	Topics []string          // ["log.*"] with RabbitMQ; exact names with GoChannel
	Poison string            // contracts.LogPoisonKey ("poison.log")
	Logs   LogWriter
	Log    *slog.Logger
	Tracer trace.TracerProvider
	// Retry policy for a failing logger service.
	MaxRetries      int
	InitialInterval time.Duration
}

// NewRouter builds the Watermill router: one handler per topic, with
// poison-queue and retry middleware.
func NewRouter(cfg Config) (*message.Router, error) {
	r, err := message.NewRouter(message.RouterConfig{CloseTimeout: 5 * time.Second}, watermill.NopLogger{})
	if err != nil {
		return nil, err
	}
	poison, err := middleware.PoisonQueueWithFilter(cfg.Pub, cfg.Poison, func(err error) bool {
		return errors.Is(err, ErrUnknownVersion)
	})
	if err != nil {
		return nil, err
	}
	// Order matters: middleware added first runs outermost. Retry wraps
	// the poison filter, so an unknown version is parked at once (the
	// filter returns nil and Retry sees success); any other error passes
	// through the filter, is retried, and when retries are exhausted the
	// message is nacked back to RabbitMQ.
	r.AddMiddleware(middleware.Retry{
		MaxRetries:      cfg.MaxRetries,
		InitialInterval: cfg.InitialInterval,
		Multiplier:      2,
	}.Middleware, poison)
	tp := cfg.Tracer
	if tp == nil {
		tp = noop.NewTracerProvider()
	}
	h := handler{logs: cfg.Logs, log: cfg.Log, tracer: tp.Tracer("listener")}
	for _, topic := range cfg.Topics {
		r.AddConsumerHandler("log-events-"+topic, topic, cfg.Sub, h.handle)
	}
	return r, nil
}

type handler struct {
	logs   LogWriter
	log    *slog.Logger
	tracer trace.Tracer
}

func (h handler) handle(msg *message.Message) error {
	ctx := tracing.ExtractMessage(msg.Context(), msg)
	ctx, span := h.tracer.Start(ctx, "log-event process", trace.WithSpanKind(trace.SpanKindConsumer))
	defer span.End()

	var ev contracts.LogEvent
	if err := json.Unmarshal(msg.Payload, &ev); err != nil {
		return fmt.Errorf("%w: bad JSON: %v", ErrUnknownVersion, err)
	}
	if ev.Version != 1 {
		return fmt.Errorf("%w: %d", ErrUnknownVersion, ev.Version)
	}
	ctx = web.WithRequestID(ctx, ev.RequestID)
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()
	if _, err := h.logs.WriteLog(ctx, ev.ID, contracts.LogPayload{Name: ev.Name, Data: ev.Data}); err != nil {
		h.log.WarnContext(ctx, "logger call failed, will retry", "event", ev.ID, "err", err)
		return err
	}
	h.log.InfoContext(ctx, "event forwarded", "event", ev.ID, "severity", ev.Severity)
	return nil
}
go
package listener

import (
	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill-amqp/v3/pkg/amqp"

	"academy/microservices-project/contracts"
)

// AMQPConfig is the consumer side of the topology: queue listener.logs
// on the durable topic exchange logs_topic, bound with the topic passed
// to Subscribe ("log.*"), prefetch 10. The exchange and queue arguments
// must match what amqpbus.DeclareListenerTopology declares (durable,
// not auto-deleted), or RabbitMQ answers 406 PRECONDITION_FAILED.
// Publishing (events and poison) goes through amqpbus, not through
// watermill-amqp, so that mandatory returns are detected.
// Compile-only in this module; tests use GoChannel and amqpbus.FakeChannel.
func AMQPConfig(uri string) amqp.Config {
	cfg := amqp.NewDurableTopicConfig(uri, contracts.LogExchange, contracts.LogQueue)
	cfg.Exchange.Durable = true
	cfg.Consume.Qos.PrefetchCount = 10
	return cfg
}

// NewSubscriber returns the listener's subscriber. uri uses the Compose
// service name: "amqp://guest:guest@rabbitmq:5672/".
func NewSubscriber(uri string) (*amqp.Subscriber, error) {
	return amqp.NewSubscriber(AMQPConfig(uri), watermill.NopLogger{})
}
go
package listener

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"sync"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"

	"academy/microservices-project/contracts"
)

// flakyLogs fails the first `fail` calls, then stores idempotently.
type flakyLogs struct {
	mu    sync.Mutex
	fail  int
	calls int
	keys  map[string]contracts.LogPayload
}

func (f *flakyLogs) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	f.calls++
	if f.calls <= f.fail {
		return "", errors.New("dial tcp logger-service:80: connect: connection refused")
	}
	if f.keys == nil {
		f.keys = map[string]contracts.LogPayload{}
	}
	f.keys[key] = p
	return key, nil
}

func (f *flakyLogs) stored() int {
	f.mu.Lock()
	defer f.mu.Unlock()
	return len(f.keys)
}

func start(t *testing.T, logs LogWriter, backoff time.Duration) (*gochannel.GoChannel, <-chan *message.Message) {
	t.Helper()
	pubsub := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	poison, err := pubsub.Subscribe(t.Context(), contracts.LogPoisonKey)
	if err != nil {
		t.Fatal(err)
	}
	r, err := NewRouter(Config{
		Sub: pubsub, Pub: pubsub,
		// GoChannel matches topic names exactly: no "log.*" wildcard.
		Topics: []string{"log.info", "log.error"}, Poison: contracts.LogPoisonKey,
		Logs: logs, Log: slog.New(slog.DiscardHandler),
		MaxRetries: 3, InitialInterval: backoff,
	})
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(t.Context())
	done := make(chan struct{})
	go func() { _ = r.Run(ctx); close(done) }()
	t.Cleanup(func() { cancel(); <-done })
	<-r.Running()
	return pubsub, poison
}

func publish(t *testing.T, pub message.Publisher, topic string, ev contracts.LogEvent) {
	t.Helper()
	b, _ := json.Marshal(ev)
	if err := pub.Publish(topic, message.NewMessage(ev.ID, b)); err != nil {
		t.Fatal(err)
	}
}

func waitFor(t *testing.T, cond func() bool) {
	t.Helper()
	deadline := time.Now().Add(2 * time.Second)
	for !cond() {
		if time.Now().After(deadline) {
			t.Fatal("condition not met in 2s")
		}
		time.Sleep(5 * time.Millisecond)
	}
}

func TestRedeliveredEventIsStoredOnce(t *testing.T) {
	logs := &flakyLogs{}
	pub, _ := start(t, logs, time.Millisecond)
	ev := contracts.LogEvent{ID: "evt-1", Version: 1, Name: "event", Data: "a", Severity: "info"}
	publish(t, pub, "log.info", ev)
	publish(t, pub, "log.info", ev) // at-least-once: the same event twice
	waitFor(t, func() bool { logs.mu.Lock(); defer logs.mu.Unlock(); return logs.calls == 2 })
	if logs.stored() != 1 {
		t.Fatalf("stored %d, want 1", logs.stored())
	}
}

func TestLoggerDownIsRetried(t *testing.T) {
	logs := &flakyLogs{fail: 2}
	pub, _ := start(t, logs, time.Millisecond)
	publish(t, pub, "log.error", contracts.LogEvent{ID: "evt-2", Version: 1, Name: "event", Severity: "error"})
	waitFor(t, func() bool { return logs.stored() == 1 })
}

func TestUnknownVersionGoesToPoison(t *testing.T) {
	logs := &flakyLogs{}
	// A long backoff: if the poison filter ran after Retry, parking would
	// take 200+400+800 ms. It must happen at once.
	pub, poison := start(t, logs, 200*time.Millisecond)
	t0 := time.Now()
	publish(t, pub, "log.info", contracts.LogEvent{ID: "evt-3", Version: 2, Name: "event"})
	select {
	case m := <-poison:
		m.Ack()
		if m.UUID != "evt-3" || m.Metadata.Get("reason_poisoned") == "" {
			t.Fatalf("poison message %s metadata %v", m.UUID, m.Metadata)
		}
		if el := time.Since(t0); el > 150*time.Millisecond {
			t.Fatalf("unknown version was retried before parking (%v)", el)
		}
	case <-time.After(2 * time.Second):
		t.Fatal("no poison message")
	}
	if logs.stored() != 0 {
		t.Fatal("unknown version must not be stored")
	}
}

Communication styles side by side: REST/JSON between services Must-know ​

In plain words: One service sends an HTTP request with a JSON body to another and waits for the answer. Everyone can read it, curl can test it, every language speaks it, and the contract is just "this JSON shape at this URL".

Common misunderstanding: "REST between services is simple, so it needs no policy." The http.Client zero value has no timeout, http.DefaultClient is shared by every library in the process, and a 500 with a JSON body is not an error to client.Do (err == nil). The client helper here (clients.postJSON) builds every request with http.NewRequestWithContext, reads at most 1 MiB, decodes the shared envelope and turns any non-2xx or "error": true into a typed *resilience.UpstreamError{Service, Status, Message}.

Definition: in this project REST/JSON between services means: POST with Content-Type: application/json; the shared contracts.JSONResponse envelope; X-Request-ID and, for writes, Idempotency-Key headers; a ctx deadline per attempt instead of Client.Timeout; clients.HTTPClient(base) wrapping the transport with request-ID propagation (and, in production, otelhttp). Server-side, every service uses web.ReadJSON (http.MaxBytesReader, DisallowUnknownFields, single value) and web.WriteJSON. HTTP itself is in net/http.

1  broker   ctx, cancel := WithTimeout(r.Context(), 2s)       per attempt
2  broker   NewRequestWithContext(ctx, POST, auth/authenticate, body)
3  client   PropagatingTransport adds X-Request-ID: r-1; otelhttp adds traceparent
4  auth     401 {"error":true,"message":"invalid credentials"}
5  broker   postJSON -> &UpstreamError{Service:"authentication-service", Status:401, Message:"invalid credentials"}
6  broker   HTTPStatus -> 401, message passes through to the front end

Real scenario: the broker calling auth and the mailer; a partner integration; a service written in another language joining later; debugging with curl in the Compose network (docker compose exec broker-service ... is not possible on distroless, so a debug container on the same network is used).

ConcernREST/JSON answer in this project
Contractcontracts types + golden JSON files in contracts/testdata
VersioningAdditive fields only; unknown fields rejected server-side, so a new field needs the server first
Timeoutctx per attempt (resilience.Hop.Timeout); no Client.Timeout
ErrorsStatus code + message; mapped by resilience.HTTPStatus
Discoveryhttp://<service-name> via Compose DNS
Toolingcurl, httptest, any proxy

RPC with net/rpc: gob, Register, Dial, Call, and its limits Important ​

In plain words: net/rpc lets a Go program call a method on an object in another Go program as if it were local: the server registers an object, the client dials and calls "Type.Method" with an argument and a pointer for the reply. The bytes on the wire are gob, Go's own binary encoding.

Common misunderstanding: "net/rpc is a lighter gRPC." It is frozen ("The net/rpc package is frozen and is not accepting new features"), Go-only (gob), has no context and therefore no deadline or cancellation on Call, no metadata (so the request ID and the trace context must ride inside the argument struct), and returns errors as plain strings: "The method's return value, if non-nil, is passed back as a string that the client sees as if created by [errors.New]." On the client that string is an rpc.ServerError, so errors.Is(err, logger.ErrInvalid) is false. The test TestNetRPCRegisterDialCall proves each limit.

Definition: a method is exported over RPC only if "the method's type is exported", "the method is exported", "the method has two arguments, both exported (or builtin) types", "the method's second argument is a pointer" and "the method has return type error"; "In effect, the method must look schematically like func (t *T) MethodName(argType T1, replyType *T2) error where T1 and T2 can be marshaled by encoding/gob." Server: rpc.NewServer(), Register(&logger.RPCServer{...}) (exposes "RPCServer.LogInfo"), then Accept(lis) or ServeConn(conn) (or HandleHTTP + http.Serve). Client: rpc.Dial("tcp", "logger-service:5001") (or DialHTTP; both take no context, so clients.LogRPC uses net.Dialer.DialContext and rpc.NewClient(conn) instead), then client.Call("RPCServer.LogInfo", args, &reply) (blocking) or client.Go(...) (async, completion on call.Done). Because only a string crosses the wire, LogInfo returns either ErrInvalid or the fixed ErrUnavailable ("log store unavailable", never the store's own error text), and the client maps exactly those two strings (422, or a retryable 503). A connection lost while a call is pending fails that call with io.ErrUnexpectedEOF (net/rpc converts the server's EOF unless the client itself is closing) or a reset error, and every later call with rpc.ErrShutdown (connection is shut down); clients.LogRPC treats all of them as a broken connection, drops the client and redials on the next attempt (TestRPCUnexpectedEOFIsRedialedAndRetried closes the server side mid-call). Its ctx covers every step: the dial (TestRPCDialIsBoundedByCtx, a blackholed address), the request write, which Client.Go does synchronously before returning (it runs in a goroutine; if ctx ends mid-write the connection is closed and dropped, TestRPCSendIsBoundedByCtx with a peer that never reads), and the wait for the reply (select on call.Done and ctx.Done()).

     broker (clients.LogRPC)                             logger-service :5001
1    DialContext(ctx) + rpc.NewClient(conn) ───────────▶ Accept -> ServeConn(conn)
2    c.Go("RPCServer.LogInfo", RPCPayload{Name, Data,    gob-decode RPCPayload
        RequestID:"r-1", Key:"r-1", Trace:{traceparent}})
3    select { case <-call.Done: ...; case <-ctx.Done(): } LogInfo: ctx = Extract(Trace) + WithTimeout(2s)  (its own budget)
4    ctx expires at 1s -> return ctx.Err()               ...still writing: nobody can tell it to stop
5                                                        reply "Processed payload via RPC: r-1" (discarded)
6    logger dies mid-call -> io.ErrUnexpectedEOF (later calls: rpc.ErrShutdown) -> drop client; next attempt redials

Real scenario: a legacy Go-only internal service; a quick tool between two Go processes on one host; teaching what gRPC adds.

Limit of net/rpcConsequenceWhat this project does
FrozenNo new features, no context support comingKept for comparison only
gob encodingGo-to-Go only; only exported fields travelRPCPayload has exported fields only
No context.ContextNo deadline, no cancellation, no metadataClient: DialContext + rpc.NewClient, Go in a goroutine, select on ctx.Done(); server sets its own 2 s
Errors are stringsNo errors.Is, no codesThe two strings are the contract: log entry needs a name → 422, the server's fixed log store unavailable → retryable 503
No graceful shutdown APIOpen connections block shutdownlifecycle.RPC closes the listener, waits, then closes conns
Connection lossPending call: io.ErrUnexpectedEOF; later calls: rpc.ErrShutdownDrop and redial on the next attempt (TestRPCUnexpectedEOFIsRedialedAndRetried, TestRPCClientRedialsAfterLoggerRestart)

gRPC: proto, codegen, client/server, deadlines Must-know ​

In plain words: The logger's gRPC API is written once in logs.proto; buf generate turns it into Go types and a client/server interface; the broker calls client.WriteLog(ctx, req) and the server implements WriteLog. The deadline in the broker's ctx travels with the call.

Common misunderstanding: "gRPC sets a sensible timeout." grpc.io: "By default, gRPC does not set a deadline which means it is possible for a client to end up waiting for a response effectively forever." The broker's LogHop gives every attempt 1 s, which reaches the server as grpc-timeout; TestGRPCOverBufconn shows a slow store answered with codes.DeadlineExceeded after 30 ms.

Definition: proto/logs/v1/logs.proto declares package logs.v1, go_package = "academy/microservices-project/gen/logs/v1;logsv1", service LogService { rpc WriteLog(WriteLogRequest) returns (WriteLogResponse); }. Codegen with buf 1.75.0, protoc-gen-go v1.36.11 and protoc-gen-go-grpc 1.6.2 (buf.gen.yaml, paths=source_relative) writes gen/logs/v1/logs.pb.go and logs_grpc.pb.go, committed so tests need no compiler. Server: grpc.NewServer(opts...), logsv1.RegisterLogServiceServer(s, &logger.GRPCServer{...}) (which embeds UnimplementedLogServiceServer), plus health.NewServer() registered as grpc.health.v1.Health. Client: grpc.NewClient("dns:///logger-service:50001", grpc.WithTransportCredentials(insecure.NewCredentials())) and logsv1.NewLogServiceClient(conn). Errors: status.Error(codes.InvalidArgument, ...), codes.Unavailable, codes.DeadlineExceeded. Everything deeper (streaming, interceptors, TLS, gateway) is in gRPC & Protobuf in Go.

proto
syntax = "proto3";

// The logger service's gRPC contract. The broker is the client, the
// logger service is the server. Field numbers are part of the contract:
// never reuse or renumber them.
package logs.v1;

option go_package = "academy/microservices-project/gen/logs/v1;logsv1";

service LogService {
  // WriteLog stores one log entry and returns its id.
  rpc WriteLog(WriteLogRequest) returns (WriteLogResponse);
}

message LogEntry {
  string name = 1;
  string data = 2;
  string request_id = 3;
  // Same key on a retry = same entry; the server stores it once.
  string idempotency_key = 4;
}

message WriteLogRequest {
  LogEntry entry = 1;
}

message WriteLogResponse {
  string id = 1;
  string result = 2;
}
     broker (clients.LogGRPC)                 HTTP/2                      logger-service :50001
1    ctx deadline now+1s
2    WriteLog(ctx, {entry{name,data,request_id}}) ── HEADERS :path /logs.v1.LogService/WriteLog
                                                     grpc-timeout: 999m, traceparent: 00-...
3                                                                          server ctx deadline = now+999ms
4                                                                          Svc.Write(ctx) ... store slow
5                                              ◀── trailers grpc-status: 4 (DEADLINE_EXCEEDED)
6    status.Code(err) == codes.DeadlineExceeded -> Retryable -> next attempt if budget remains

Real scenario: a high-volume internal call where JSON parsing shows in profiles; a polyglot team that wants one contract and generated clients; a call that must respect the caller's deadline end to end; health checking with grpc-health-probe or a Kubernetes grpc probe.

PieceFile or callWhere it is taught in depth
Contractproto/logs/v1/logs.proto, buf lint (STANDARD) cleanproto3 and field numbers
Codegenbuf generate → gen/logs/v1/*.pb.gosame chapter, protoc vs buf
Servergrpc.NewServer, RegisterLogServiceServer, GracefulStopsame chapter
Clientgrpc.NewClient("dns:///logger-service:50001")same chapter, resolvers
Deadlinectx → grpc-timeout → server ctxcontext
Testbufconn.Listen + passthrough:///bufnetsame chapter, bufconn

RabbitMQ events: exchange, routing keys, publisher confirms, consumer Must-know ​

In plain words: For log without via, the broker does not call the logger at all. It publishes a LogEvent to the topic exchange logs_topic with the routing key log.info, answers 202, and the listener picks it up from its queue whenever it can.

Common misunderstanding: "Publish returned, so the event is safe." Without publisher confirms a publish is fire-and-forget into the TCP buffer. The RabbitMQ tutorial: "Publisher confirms are a RabbitMQ extension to implement reliable publishing. When publisher confirms are enabled on a channel, messages the client publishes are confirmed asynchronously by the broker, meaning they have been taken care of on the server side." But a confirm does not prove a queue stored the message. The confirms guide: "For unroutable messages, the broker will issue a confirm once the exchange verifies a message won't route to any queue (returns an empty list of queues). If the message is also published as mandatory, the basic.return is sent to the client before basic.ack." On a fresh deployment, before the listener has bound listener.logs, a confirm-only publisher gets an ack and the broker answers 202 for an event that went nowhere. So this project publishes with its own amqpbus.Publisher (amqp091-go directly; watermill-amqp's publisher waits for the ack but ignores returns): confirm mode, mandatory = true, NotifyReturn, one publish at a time per channel; a basic.return for the message ID turns into ErrUnroutable and the broker answers 503 (TestMandatoryPublishReportsUnroutable: before the listener's binding exists, and for an unbound key). A nack ("basic.nack will only be delivered if an internal error occurs in the Erlang process responsible for a queue") is ErrNacked. Even a routed, confirmed message says nothing about whether a consumer processed it; and publishing after a database write without an outbox can lose the event if the process dies in between (see Event-Driven Go, outbox).

Definition: a topic exchange routes on dot-separated words; for binding keys "* (star) can substitute for exactly one word" and "# (hash) can substitute for zero or more words", and routing keys may be "up to the limit of 255 bytes". contracts.RoutingKey("info") is log.info; the listener binds log.*, so log.info, log.warning and log.error all reach listener.logs, while poison.log reaches only listener.poison. The broker declares only the exchange (amqpbus.DeclareExchange); the queues belong to the listener. clients.Events.PublishLog builds the event (ID = the idempotency key, Version: 1, OccurredAt, RequestID), sets the Watermill message UUID to the event ID, copies X-Request-ID and the W3C trace context into the message metadata (AMQP headers), optionally starts a producer span log.info publish, and calls Publisher.Publish(routingKey, msg) in a goroutine, selecting on ctx.Done() (TestEventsPublishIsBoundedByCtx); amqpbus.Publisher also waits for the confirm with DeferredConfirmation.WaitContext(msg.Context()). (amqp091's PublishWithContext checks the context only before sending, and watermill-amqp's publisher waits for the confirm without one.) On a timeout the outcome is unknown; a retry reuses the same message UUID. On the consumer side, in watermill-amqp's NewDurableTopicConfig the Watermill topic is the queue's binding key. The broker itself (exchange types, queues, DLX, quorum queues) is in RabbitMQ.

     broker-service                      RabbitMQ                                   listener-service
1    PublishLog(ctx, key r-1, "info")
2    Publish("log.info", msg{uuid r-1,  ─▶ exchange logs_topic (topic, durable)
       headers X-Request-ID, traceparent})
3                                          match binding "log.*" ─▶ queue listener.logs (durable)
4    ◀── basic.ack (publisher confirm)
5    202 "queued via RabbitMQ"
6                                          deliver (prefetch 10) ──────────────────▶ handler -> logger REST
7                                          ◀──────────────────────────────────────── basic.ack

Real scenario: audit and activity logs; "send a welcome email" after signup; cache invalidation broadcasts; analytics events; any work where the user's response must not wait for, or fail because of, a slow consumer.

KnobValue hereMeaning
Exchangelogs_topic, type topic, durableRoutes by routing key pattern
Routing keylog.<severity>One word per severity
Binding keylog.*Exactly one word after log.
Queuelistener.logs, durableSurvives broker restarts
Publisher confirmsamqpbus.NewPublisher: Confirm(false)Publish returns after the broker's ack (or nack → ErrNacked)
Mandatorymandatory = true + NotifyReturnUnroutable → basic.return before the ack → ErrUnroutable → broker 503
Topology ownerlistener: DeclareListenerTopology; broker: DeclareExchangeQueues and bindings exist before the first consume
PrefetchConsume.Qos.PrefetchCount = 10 (library default 1)At most 10 unacked messages per consumer
Nack behaviourrequeue (NoRequeueOnNack false)Retried by redelivery after Watermill's retries
Poisonkey poison.log → queue listener.poison (declared by the listener)Must not match log.*

The publisher and the topology, and their tests against an in-memory fake channel that implements RabbitMQ's topic matching, mandatory returns and its "ack even when unroutable" rule:

go
// Package amqpbus is the project's RabbitMQ publisher and topology,
// written on amqp091-go directly because two guarantees matter that
// watermill-amqp's publisher does not give:
//
//   - Publisher confirms alone do not prove a message reached a queue:
//     RabbitMQ also confirms messages that route to no queue. Publishing
//     with mandatory=true makes the broker send basic.return first, and
//     Publish reports ErrUnroutable.
//   - The topology (exchange, queues, bindings, including the poison
//     queue) is declared at startup by the service that owns it, not by
//     whichever consumer happens to subscribe first.
//
// Publisher implements Watermill's message.Publisher so the broker's
// clients.Events and the listener's poison middleware use it unchanged.
package amqpbus

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/ThreeDotsLabs/watermill/message"
	amqp "github.com/rabbitmq/amqp091-go"

	"academy/microservices-project/contracts"
)

var (
	// ErrUnroutable: the broker returned a mandatory message (no binding).
	ErrUnroutable = errors.New("amqp: message unroutable (no queue bound for routing key)")
	// ErrNacked: the broker nacked the publish (it could not take it).
	ErrNacked = errors.New("amqp: publish nacked by broker")
)

// Channel is the part of *amqp.Channel this package needs, with the
// publish-and-wait-for-confirm step folded into one method so a fake
// can implement it. RealChannel adapts *amqp.Channel.
type Channel interface {
	ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error
	QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table) (amqp.Queue, error)
	QueueBind(name, key, exchange string, noWait bool, args amqp.Table) error
	Confirm(noWait bool) error
	NotifyReturn(c chan amqp.Return) chan amqp.Return
	// PublishConfirmed publishes and blocks until the broker's ack or
	// nack (or ctx ends). acked == false means a nack.
	PublishConfirmed(ctx context.Context, exchange, key string, mandatory bool, msg amqp.Publishing) (acked bool, err error)
}

// DeclareExchange declares the durable topic exchange. Every service
// that publishes calls it; declaring is idempotent when the arguments
// match (a mismatch fails with 406 PRECONDITION_FAILED).
func DeclareExchange(ch Channel) error {
	return ch.ExchangeDeclare(contracts.LogExchange, "topic", true, false, false, false, nil)
}

// DeclareListenerTopology is run by the listener, which owns both
// queues: listener.logs bound to log.*, listener.poison bound to
// poison.log. Without the second binding a poisoned event is confirmed
// by RabbitMQ and silently dropped.
func DeclareListenerTopology(ch Channel) error {
	if err := DeclareExchange(ch); err != nil {
		return err
	}
	for _, b := range []struct{ queue, key string }{
		{contracts.LogQueue, contracts.LogBindingKey},
		{contracts.LogPoisonQueue, contracts.LogPoisonKey},
	} {
		if _, err := ch.QueueDeclare(b.queue, true, false, false, false, nil); err != nil {
			return fmt.Errorf("declare %s: %w", b.queue, err)
		}
		if err := ch.QueueBind(b.queue, b.key, contracts.LogExchange, false, nil); err != nil {
			return fmt.Errorf("bind %s to %s: %w", b.queue, b.key, err)
		}
	}
	return nil
}

// Publisher publishes persistent, mandatory messages with confirms on.
// One publish at a time per channel, so a basic.return always belongs
// to the publish in progress (RabbitMQ sends the return before the ack).
type Publisher struct {
	ch      Channel
	returns chan amqp.Return
	mu      sync.Mutex
	timeout time.Duration
}

// NewPublisher puts the channel in confirm mode and subscribes to returns.
func NewPublisher(ch Channel) (*Publisher, error) {
	if err := ch.Confirm(false); err != nil {
		return nil, fmt.Errorf("confirm mode: %w", err)
	}
	return &Publisher{ch: ch, returns: ch.NotifyReturn(make(chan amqp.Return, 16)), timeout: 5 * time.Second}, nil
}

// Publish implements message.Publisher. topic is the routing key.
func (p *Publisher) Publish(topic string, msgs ...*message.Message) error {
	for _, m := range msgs {
		if err := p.publish(m.Context(), topic, m); err != nil {
			return err
		}
	}
	return nil
}

func (p *Publisher) publish(ctx context.Context, key string, m *message.Message) error {
	if _, ok := ctx.Deadline(); !ok {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, p.timeout)
		defer cancel()
	}
	headers := amqp.Table{}
	for k, v := range m.Metadata {
		headers[k] = v
	}
	p.mu.Lock()
	defer p.mu.Unlock()
	for len(p.returns) > 0 { // stale returns from an abandoned publish
		<-p.returns
	}
	acked, err := p.ch.PublishConfirmed(ctx, contracts.LogExchange, key, true, amqp.Publishing{
		MessageId:    m.UUID,
		ContentType:  "application/json",
		DeliveryMode: amqp.Persistent,
		Headers:      headers,
		Body:         m.Payload,
	})
	if err != nil {
		return err
	}
	select {
	case r := <-p.returns:
		if r.MessageId == m.UUID {
			return fmt.Errorf("%w: key %q, reply %d %s", ErrUnroutable, key, r.ReplyCode, r.ReplyText)
		}
	default:
	}
	if !acked {
		return ErrNacked
	}
	return nil
}

// Close implements message.Publisher; the connection owner closes it.
func (p *Publisher) Close() error { return nil }

// RealChannel adapts *amqp.Channel to Channel.
type RealChannel struct{ *amqp.Channel }

func (c RealChannel) PublishConfirmed(ctx context.Context, exchange, key string, mandatory bool, msg amqp.Publishing) (bool, error) {
	dc, err := c.PublishWithDeferredConfirmWithContext(ctx, exchange, key, mandatory, false, msg)
	if err != nil {
		return false, err
	}
	return dc.WaitContext(ctx)
}

// Dial opens a connection and a channel; the caller closes conn.
func Dial(uri string) (*amqp.Connection, RealChannel, error) {
	conn, err := amqp.Dial(uri)
	if err != nil {
		return nil, RealChannel{}, err
	}
	ch, err := conn.Channel()
	if err != nil {
		_ = conn.Close()
		return nil, RealChannel{}, err
	}
	return conn, RealChannel{ch}, nil
}
go
package amqpbus

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"

	"academy/microservices-project/contracts"
	"academy/microservices-project/listener"
)

func TestListenerDeclaresQueuesAndBindings(t *testing.T) {
	ch := NewFakeChannel()
	if err := DeclareListenerTopology(ch); err != nil {
		t.Fatal(err)
	}
	if got := ch.Exchanges[contracts.LogExchange]; got != "topic" {
		t.Fatalf("exchange %q type %q", contracts.LogExchange, got)
	}
	want := map[string]string{contracts.LogQueue: contracts.LogBindingKey, contracts.LogPoisonQueue: contracts.LogPoisonKey}
	for q, key := range want {
		if !ch.Durable[q] || ch.Bindings[q] != key {
			t.Fatalf("queue %s: durable=%v binding=%q, want %q", q, ch.Durable[q], ch.Bindings[q], key)
		}
	}
}

func TestMandatoryPublishReportsUnroutable(t *testing.T) {
	ch := NewFakeChannel()
	if err := DeclareExchange(ch); err != nil { // the broker declares only the exchange
		t.Fatal(err)
	}
	pub, err := NewPublisher(ch)
	if err != nil {
		t.Fatal(err)
	}
	// Fresh deployment: no listener has bound its queue yet. RabbitMQ
	// confirms the publish anyway; only the mandatory return shows it.
	err = pub.Publish(contracts.RoutingKey("info"), message.NewMessage("e-1", []byte(`{}`)))
	if !errors.Is(err, ErrUnroutable) {
		t.Fatalf("got %v, want ErrUnroutable", err)
	}
	if err := DeclareListenerTopology(ch); err != nil {
		t.Fatal(err)
	}
	if err := pub.Publish(contracts.RoutingKey("info"), message.NewMessage("e-2", []byte(`{}`))); err != nil {
		t.Fatalf("routed publish: %v", err)
	}
	if n := len(ch.Queues[contracts.LogQueue]); n != 1 {
		t.Fatalf("listener.logs has %d messages, want 1", n)
	}
	if err := pub.Publish("metrics.cpu", message.NewMessage("e-3", []byte(`{}`))); !errors.Is(err, ErrUnroutable) {
		t.Fatalf("unbound key: got %v", err)
	}
}

func TestPublishFailsWhenBrokerNacks(t *testing.T) {
	ch := NewFakeChannel()
	_ = DeclareListenerTopology(ch)
	ch.Nack = true
	pub, _ := NewPublisher(ch)
	if err := pub.Publish("log.info", message.NewMessage("e-4", nil)); !errors.Is(err, ErrNacked) {
		t.Fatalf("got %v", err)
	}
}

func TestUnknownVersionLandsInThePoisonQueue(t *testing.T) {
	ch := NewFakeChannel()
	if err := DeclareListenerTopology(ch); err != nil {
		t.Fatal(err)
	}
	poisonPub, _ := NewPublisher(ch) // what cmd/listener passes as Config.Pub
	in := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	r, err := listener.NewRouter(listener.Config{
		Sub: in, Pub: poisonPub, Topics: []string{"log.info"}, Poison: contracts.LogPoisonKey,
		Logs: nopLogs{}, Log: slog.New(slog.DiscardHandler), MaxRetries: 1, InitialInterval: time.Millisecond,
	})
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(t.Context())
	defer cancel()
	go func() { _ = r.Run(ctx) }()
	<-r.Running()
	b, _ := json.Marshal(contracts.LogEvent{ID: "evt-9", Version: 2, Name: "event"})
	_ = in.Publish("log.info", message.NewMessage("evt-9", b))
	deadline := time.Now().Add(2 * time.Second)
	for len(ch.QueueSnapshot(contracts.LogPoisonQueue)) == 0 {
		if time.Now().After(deadline) {
			t.Fatal("unknown version did not reach listener.poison")
		}
		time.Sleep(5 * time.Millisecond)
	}
	got := ch.QueueSnapshot(contracts.LogPoisonQueue)[0]
	if got.MessageId != "evt-9" || got.Headers["reason_poisoned"] == nil {
		t.Fatalf("poison message %+v", got)
	}
}

type nopLogs struct{}

func (nopLogs) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	return key, nil
}
Communication styles side by sideREST/JSONcontract: JSON shape+ shared Go typesencoding: JSON textdeadline: not carriederrors: HTTP status+ JSON messagecaller waits: yesnet/rpccontract: Go types(Go to Go only)encoding: gobdeadline: none, no ctxerrors: string only(rpc.ServerError)caller waits: yesgRPCcontract: .proto+ codegenencoding: protobufdeadline: grpc-timeouterrors: status codes+ detailscaller waits: yesRabbitMQ eventcontract: event JSON+ version fieldencoding: JSON bodydeadline: TTL / noneerrors: nack, retry,poison queuecaller waits: no (202)sync request/reply (left three): the caller holds a goroutine and a budget until the answerasync event (right): the caller is done when the broker confirms; the work happens later, at least oncetighter couplinglooser coupling

When to use which: sync vs async, request/reply vs event Must-know ​

In plain words: If the user needs the answer to continue (am I logged in?), it is synchronous request/reply. If the user only needs to know the work will happen (write this log line, send this email), publish an event and answer 202.

Common misunderstanding: "Request/reply over RabbitMQ gives me both." It gives you a synchronous call with a broker in the middle: the caller still waits, now with a reply queue and a correlation ID to manage (RabbitMQ tutorial 6 uses ReplyTo and CorrelationId). It is worth it only when the broker's buffering or routing is the point; see Request-Reply over REST and AMQP and Service Communication.

Definition: sync vs async is about whether the caller's thread of work waits for the callee's completion. Request/reply vs event is about the message's meaning: a request asks a specific service to do something and expects an answer; an event states that something happened and does not know who listens. The four transports map onto that grid: REST, net/rpc and gRPC are sync request/reply; RabbitMQ carries async events here (and could carry async commands or request/reply).

sync request/reply (auth)                      async event (log)
1  front end waits                             1  front end waits
2  broker waits on auth                        2  broker waits only for the publisher confirm
3  auth waits on Postgres                      3  202 to the front end
4  answer flows back; total = sum of hops      4  later: listener -> logger -> MongoDB
5  any hop down = request fails                5  logger down = backlog grows, nothing fails for the user

Real scenario: login (sync); "add to cart" (sync); "order placed" fan-out to billing, shipping, email (event); "generate a PDF report" (async command, user polls or gets notified); price lookup in a hot path (gRPC).

NeedPickWhyCost
User needs the result nowREST or gRPCSimple, immediate errorsAvailability = product of the hops
Public or polyglot APIREST/JSONUniversal, debuggableText encoding, no deadline propagation
Internal, typed, fast, deadline-awaregRPCContract + codegen, grpc-timeout, status codesToolchain, HTTP/2, harder to curl
Go-only legacynet/rpcZero dependenciesFrozen, no ctx, string errors
Work the user does not wait forRabbitMQ eventDecoupled in time, absorbs outagesAt-least-once, eventual consistency, ops
Many consumers of one factEvent on a topic exchangeProducer does not know consumersVersioning discipline

Service contracts and shared types: go.work or a shared module vs duplication Important ​

In plain words: Every service must agree on the JSON shapes, the event shape, header names and routing keys. You can copy those structs into each service, put them in one shared package, or generate them (protobuf). This project keeps one contracts package and tests the wire format with golden files.

Common misunderstanding: "A shared types module creates a distributed monolith." Sharing wire types is not the problem; sharing domain logic or a database is. The real risk of a shared module is lockstep upgrades: if contracts changes incompatibly, every service must redeploy together. The rule that avoids it is the same as for protobuf: additive changes only, never rename or reuse a field, version events (LogEvent.Version).

Definition: three layouts. (1) One module, many binaries (this project): contracts is a package; the compiler checks every service against it; one go.mod, one go.sum. (2) Several modules in one repository developed together with a workspace: a go.work file "specifies relative paths to the module directories of each of the modules in the workspace"; Go 1.18 release notes: "In workspace mode, the go.work file will be used to determine the set of main modules used as the roots for module resolution", and GOWORK=off turns it off. CI usually builds each module without the workspace, against tagged versions of contracts. (3) Duplication: each service keeps its own copy of the structs; zero build coupling, but drift is found in production unless contract tests run against the other side. Protobuf (gen/logs/v1) is a fourth option for the gRPC path: the .proto is the contract and code is generated per language.

text
# go.work for layout (2): shown here, not committed (a go.work inside the
# snippet tree would change how the go command resolves this module)
go 1.24.0

use (
    ./contracts
    ./broker
    ./authentication
    ./logger
    ./mailer
    ./listener
)
# go work init ./contracts ./broker ...   then   go work use ./newservice

Real scenario: a monorepo with one team (one module); several teams, one repo, separate release cadence (modules + go.work locally, tagged contracts in CI); a polyglot system (protobuf or JSON Schema, generated types); an external partner (OpenAPI document, not Go types).

OptionDrift detected byDeploy couplingGood for
One module, shared packageCompiler + golden testsShared go.mod; services still deploy separatelyOne team, one repo
Multi-module + go.workCompiler locally; tags in CIVersion bumps of contractsSeveral teams, one repo
Duplicated structsContract tests onlyNone at build timeStrict team autonomy
Protobuf / codegenbuf breaking + codegenGenerated code per consumerPolyglot, high volume
go
// Package contracts holds the wire types every service agrees on: the
// broker's action envelope, the JSON response shape, the payloads for
// auth, log and mail, and the RabbitMQ event. Services import this one
// package instead of each keeping a private copy that drifts.
package contracts

import "time"

// Actions the broker's JSON action router understands.
const (
	ActionAuth = "auth"
	ActionLog  = "log"
	ActionMail = "mail"
)

// Transports a log action can travel over (LogPayload.Via).
const (
	ViaREST  = "rest"
	ViaRPC   = "rpc"
	ViaGRPC  = "grpc"
	ViaEvent = "event"
)

// Header names shared by every hop.
const (
	HeaderRequestID      = "X-Request-ID"
	HeaderIdempotencyKey = "Idempotency-Key"
)

// RequestPayload is what the front end posts to the broker's /handle.
type RequestPayload struct {
	Action string       `json:"action"`
	Auth   *AuthPayload `json:"auth,omitempty"`
	Log    *LogPayload  `json:"log,omitempty"`
	Mail   *MailPayload `json:"mail,omitempty"`
}

// AuthPayload is the body of POST /authenticate on the auth service.
type AuthPayload struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

// LogPayload is the body of POST /log on the logger service.
type LogPayload struct {
	Name string `json:"name"`
	Data string `json:"data"`
	Via  string `json:"via,omitempty"`
}

// MailPayload is the body of POST /send on the mailer service.
type MailPayload struct {
	From    string `json:"from"`
	To      string `json:"to"`
	Subject string `json:"subject"`
	Message string `json:"message"`
}

// JSONResponse is the one response envelope all services return.
type JSONResponse struct {
	Error   bool   `json:"error"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

// AuthUser is what the auth service returns in Data on success.
// It never contains the password hash.
type AuthUser struct {
	ID        int64  `json:"id"`
	Email     string `json:"email"`
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
}

// LogEvent is the RabbitMQ message the broker publishes and the
// listener consumes. Version lets the consumer reject shapes it does
// not know instead of guessing.
type LogEvent struct {
	ID         string    `json:"id"`
	Version    int       `json:"version"`
	Name       string    `json:"name"`
	Data       string    `json:"data"`
	Severity   string    `json:"severity"`
	OccurredAt time.Time `json:"occurred_at"`
	RequestID  string    `json:"request_id"`
}

// Exchange and routing keys of the event flow. The routing key is
// "log.<severity>" on a topic exchange; the listener binds "log.*".
const (
	LogExchange   = "logs_topic"
	LogQueue      = "listener.logs"
	LogBindingKey = "log.*"
	// LogPoisonKey must NOT match LogBindingKey, or the listener would
	// consume its own poison messages. Bind a parking queue to it.
	LogPoisonKey = "poison.log"
	// LogPoisonQueue is the parking queue bound to LogPoisonKey. The
	// listener declares it at startup (it owns both queues).
	LogPoisonQueue = "listener.poison"
)

// RoutingKey returns the topic routing key for a severity.
func RoutingKey(severity string) string {
	if severity == "" {
		severity = "info"
	}
	return "log." + severity
}
go
package contracts

import (
	"bytes"
	"encoding/json"
	"os"
	"testing"
)

// Golden files are the contract: producer tests marshal into them and
// consumer tests unmarshal from them. A rename of a JSON tag breaks
// this test before it breaks production.
func TestGoldenRoundTrip(t *testing.T) {
	cases := []struct {
		file string
		into any
	}{
		{"testdata/request-log.json", &RequestPayload{}},
		{"testdata/log-event-v1.json", &LogEvent{}},
		{"testdata/auth-response-ok.json", &JSONResponse{Data: &AuthUser{}}},
	}
	for _, c := range cases {
		t.Run(c.file, func(t *testing.T) {
			want, err := os.ReadFile(c.file)
			if err != nil {
				t.Fatal(err)
			}
			dec := json.NewDecoder(bytes.NewReader(want))
			dec.DisallowUnknownFields()
			if err := dec.Decode(c.into); err != nil {
				t.Fatalf("decode: %v", err)
			}
			got, err := json.Marshal(c.into)
			if err != nil {
				t.Fatal(err)
			}
			if !bytes.Equal(bytes.TrimSpace(want), got) {
				t.Fatalf("round trip changed the wire shape\nwant %s\ngot  %s", want, got)
			}
		})
	}
}

func TestRoutingKey(t *testing.T) {
	if got := RoutingKey(""); got != "log.info" {
		t.Fatalf("got %q", got)
	}
	if got := RoutingKey("error"); got != "log.error" {
		t.Fatalf("got %q", got)
	}
}

Configuration and service discovery via DNS names in Docker Compose (describe, no lab run) Must-know ​

In plain words: Each service finds the others by name: http://logger-service, logger-service:5001, postgres:5432, amqp://rabbitmq:5672. Inside Docker Compose those names are DNS names, so there is no registry to run. Everything that differs between environments comes from environment variables with those names as defaults.

Common misunderstanding: "depends_on means the dependency is ready." Plain depends_on only orders container start. Waiting for readiness needs condition: service_healthy, which Docker defines as "a dependency is expected to be “healthy”, which is defined with healthcheck, before starting a dependent service". And even then services must retry: a dependency can restart later. A second one: "DNS discovery load-balances." Compose DNS returns the IPs of a service's containers; HTTP clients reuse connections, so scaling a service with --scale does not spread existing keep-alive traffic evenly.

Definition: Docker's networking page: "Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by its service name." platform/config.Env(key, def) reads AUTH_URL, LOGGER_URL, LOGGER_RPC, LOGGER_GRPC, MAILER_URL, AMQP_URL, DSN, MONGO_URL, MAIL_HOST, MAIL_PORT with Compose names as defaults. gRPC uses the dns:///logger-service:50001 target so grpc-go's DNS resolver re-resolves. This is server-side discovery by the platform (Docker's embedded DNS; in Kubernetes, a Service name), not a registry like Consul; the patterns are compared in Service Discovery. This chapter describes the Compose setup; it does not run it.

     broker-service container                Docker embedded DNS                     logger-service container
1    LOGGER_URL=http://logger-service
2    GET A logger-service ─────────────────▶ 172.20.0.5 (on network academy-microservices_default)
3    TCP 172.20.0.5:80 ───────────────────────────────────────────────────────────────▶ listening :80
4    logger restarts with a new IP; next dial resolves again (keep-alive conns fail, are redialed)

Real scenario: local development with make up; a CI job that runs the stack for end-to-end tests; a single-host staging; the same images later in Kubernetes where logger-service becomes a Service DNS name with no code change.

VariableDefault (Compose name)Used by
AUTH_URLhttp://authentication-servicebroker
LOGGER_URLhttp://logger-servicebroker, auth, listener
LOGGER_RPClogger-service:5001broker
LOGGER_GRPCdns:///logger-service:50001broker
MAILER_URLhttp://mailer-servicebroker
AMQP_URLamqp://guest:guest@rabbitmq:5672/broker, listener
DSNpostgres://auth:secret@postgres:5432/users?sslmode=disableauth
MONGO_URLmongodb://admin:secret@mongo:27017logger
MAIL_HOST / MAIL_PORTmailpit / 1025mailer

Fix / how to use it: every outbound address is a variable with a Compose-name default, and every client tolerates the name not resolving yet (retry, or exit and let restart: unless-stopped bring the container back).

go
// Package config reads service configuration from the environment.
// Defaults are the Docker Compose service names, so inside the Compose
// network "http://logger-service" resolves through Docker's embedded
// DNS and no registry is needed.
package config

import (
	"net"
	"os"
	"strconv"
)

// Env returns the variable or def.
func Env(key, def string) string {
	if v, ok := os.LookupEnv(key); ok && v != "" {
		return v
	}
	return def
}

// Int returns the variable as an int or def.
func Int(key string, def int) int {
	if n, err := strconv.Atoi(os.Getenv(key)); err == nil {
		return n
	}
	return def
}

// Listen opens a TCP listener on ":" + port (all interfaces inside the
// container; Compose publishes only the broker's port to the host).
func Listen(port string) (net.Listener, error) {
	return net.Listen("tcp", ":"+port)
}

Health checks Important ​

In plain words: Each HTTP service answers /healthz (the process is alive) and /readyz (the dependencies it needs answer right now). Compose and Kubernetes call these to decide whether to route traffic or restart a container.

Common misunderstanding: "Liveness should check the database." If Postgres is down and liveness fails, the orchestrator restarts every auth container in a loop, which fixes nothing and adds load when Postgres comes back. Liveness says "this process is not wedged"; readiness says "send me traffic". TestReadinessFailsWhenADependencyIsDown shows /readyz at 503 while /healthz stays 200.

Definition: health.Handler{Checks, Timeout} registers GET /healthz (always 200) and GET /readyz, which runs every named check in parallel under one timeout (1 s default) and answers 200 or 503 with a JSON map of results. Auth checks Store.Ping (Postgres PingContext), the logger checks MongoDB Ping(readpref.Primary()), the broker and mailer have no checks. The logger also serves the standard gRPC health service (grpc.health.v1.Health, from google.golang.org/grpc/health). Images are distroless (no curl), so cmd/healthcheck is a 5.6 MB binary that GETs /readyz and exits 0 or 1; Compose runs it as test: ["CMD", "/healthcheck", "http://127.0.0.1/readyz"].

t=0s    docker compose up: postgres starting, auth container starts (depends_on: postgres service_healthy waits)
t=6s    postgres healthcheck pg_isready -> healthy
t=6s    auth starts; /readyz -> postgres ok -> 200 -> healthy after first interval
t=40s   postgres stops: auth /readyz -> 503 {"postgres":"... connection refused"}; /healthz -> 200
t=40s   container marked unhealthy, NOT restarted for liveness; broker gets 503 from auth -> answers 502

Real scenario: Compose start order; a Kubernetes readiness probe removing a pod from a Service during a database failover; a load balancer health check; an on-call dashboard of readiness per service.

EndpointChecksFails whenOrchestrator should
/healthzNothing beyond "the handler runs"Process wedged or crashedRestart
/readyz (auth)Postgres pingPostgres down or slowStop routing traffic
/readyz (logger)MongoDB pingMongoDB downStop routing traffic
gRPC Health/Check (logger)Status set by the serverNOT_SERVINGStop routing gRPC
listenerNo portProcess exits on lost broker connectionrestart: unless-stopped
go
// Package health serves liveness (/healthz: the process is up) and
// readiness (/readyz: the dependencies this service needs answer).
// Docker Compose healthchecks and Kubernetes probes call these.
package health

import (
	"context"
	"net/http"
	"sync"
	"time"

	"academy/microservices-project/platform/web"
)

// Check reports whether one dependency is usable.
type Check func(ctx context.Context) error

// Handler holds named readiness checks.
type Handler struct {
	Checks  map[string]Check
	Timeout time.Duration
}

// Register adds the two endpoints to mux.
func (h Handler) Register(mux *http.ServeMux) {
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
		web.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"})
	})
	mux.HandleFunc("GET /readyz", h.ready)
}

func (h Handler) ready(w http.ResponseWriter, r *http.Request) {
	timeout := h.Timeout
	if timeout == 0 {
		timeout = time.Second
	}
	ctx, cancel := context.WithTimeout(r.Context(), timeout)
	defer cancel()

	var mu sync.Mutex
	var wg sync.WaitGroup
	result := map[string]string{}
	ok := true
	for name, check := range h.Checks {
		wg.Add(1)
		go func() {
			defer wg.Done()
			err := check(ctx)
			mu.Lock()
			defer mu.Unlock()
			if err != nil {
				result[name] = err.Error()
				ok = false
				return
			}
			result[name] = "ok"
		}()
	}
	wg.Wait()
	status := http.StatusOK
	if !ok {
		status = http.StatusServiceUnavailable
	}
	web.WriteJSON(w, status, result)
}
go
package health

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func TestReadinessFailsWhenADependencyIsDown(t *testing.T) {
	mux := http.NewServeMux()
	Handler{Timeout: 50 * time.Millisecond, Checks: map[string]Check{
		"postgres": func(ctx context.Context) error {
			return errors.New("dial tcp postgres:5432: connect: connection refused")
		},
		"mongo": func(ctx context.Context) error {
			<-ctx.Done() // a hung dependency is cut by the probe's own timeout
			return ctx.Err()
		},
	}}.Register(mux)

	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil))
	if rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("status %d", rec.Code)
	}
	if !strings.Contains(rec.Body.String(), "connection refused") || !strings.Contains(rec.Body.String(), "deadline exceeded") {
		t.Fatalf("body %s", rec.Body)
	}

	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
	if rec.Code != http.StatusOK {
		t.Fatalf("liveness must not depend on dependencies, got %d", rec.Code)
	}
}

Graceful shutdown of all servers in one process Must-know ​

In plain words: The logger runs three servers in one process (HTTP, net/rpc, gRPC). On SIGTERM all three must stop accepting new work, let in-flight requests finish, and stop within a grace period, and if any one of them dies, the others must stop too so the container restarts as a whole.

Common misunderstanding: "srv.Shutdown(ctx) stops everything." It stops one http.Server. gRPC has GracefulStop (which "blocks until all the pending RPCs are finished", with no timeout of its own) and Stop; net/rpc has no shutdown API at all; a consumer stops when its context is canceled. Each needs its own adapter, and all must be driven by one root context. Another one: "Shutdown cancels request contexts." http.Server.Shutdown works "by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle"; it does not cancel handlers' contexts.

Definition: lifecycle.Run(ctx, grace, servers...) starts every Server (Name, Serve, Shutdown(ctx)) in an errgroup; when the root ctx (from signal.NotifyContext(..., os.Interrupt, syscall.SIGTERM)) is canceled or any Serve returns an error, it calls every Shutdown in parallel under context.WithTimeout(context.WithoutCancel(ctx), grace) and returns the first error. Adapters: HTTP (Serve treats http.ErrServerClosed as success; Shutdown), GRPC (grpc.ErrServerStopped; GracefulStop in a goroutine, Stop when the grace expires), RPC (tracks connections; closes the listener, waits for ServeConn to return, closes connections when the grace expires), Func (a run function canceled through its own ctx, used for the Watermill router). Docker's stop_grace_period: 15s must be longer than the 10 s grace. Signals themselves are in OS Processes, Signals & Graceful Shutdown.

     t      root ctx            http :80                grpc :50001              rpc :5001                 consumer
1    0      SIGTERM -> cancel
2    0                          Shutdown: close lis     GracefulStop: no new     close lis                 cancel router ctx
3    0-150ms                    in-flight GET finishes  pending RPCs finish      ServeConn ends on hang-up in-flight msg acked
4    150ms  all Shutdown returned -> Run returns nil -> main exits 0 (well before SIGKILL at 15 s)
   test: TestRunStopsAllServersAndFinishesInFlightRequest (a 150 ms request started before cancel gets "done")
Graceful shutdown of all servers in one processsignal / RunHTTP :80gRPC :50001net/rpc :5001consumert0 SIGTERMin-flight work drainst0 + grace (10 s) or doneNotifyContext cancelsShutdown: stop acceptwait for active requestsGracefulStoppending RPCs finishStop() on timeoutclose listenerServeConn ends on hang-upclose connscancel router ctxack or nack in-flightexit 0

Real scenario: a rolling deploy in Compose or Kubernetes; the logger losing MongoDB and exiting so the restart policy recovers it; a listener that must finish acking its in-flight message; an all-in-one development binary.

ServerStop acceptingWait for in-flightForce after graceAdapter
net/httpShutdown closes listenersYes, idle conns closed, active waitedReturn ctx error (conns left to process exit)lifecycle.HTTP
grpc-goGracefulStopYes, pending RPCsStop() closes everythinglifecycle.GRPC
net/rpcClose the listener (by hand)Until each ServeConn returns (client hang-up)Close tracked connslifecycle.RPC
Watermill routerCancel its ctxRouter waits CloseTimeout (5 s) for handlersRouter returnslifecycle.Func

Fix / how to use it: the in-process test starts HTTP, gRPC, net/rpc and a consumer, sends a slow request, cancels the root ctx and asserts the request completes, every server stops and the listener refuses new connections; a second test proves one failing server stops the others. In the all-in-one system the broker's net/rpc client is closed during shutdown too, because a net/rpc server cannot tell an idle client connection from a busy one.

go
// Package lifecycle runs several servers (HTTP, gRPC, net/rpc, a
// message consumer) in one process and shuts all of them down
// gracefully when the root context ends or when any one of them fails.
package lifecycle

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/rpc"
	"sync"
	"time"

	"golang.org/x/sync/errgroup"
	"google.golang.org/grpc"
)

// Server is anything with a blocking Serve and a graceful Shutdown.
// Serve must return nil after a requested shutdown.
type Server interface {
	Name() string
	Serve() error
	Shutdown(ctx context.Context) error
}

// Run starts every server and blocks until ctx is done or one Serve
// returns an error. Then it shuts all servers down in parallel, each
// bounded by grace, and returns the first error.
func Run(ctx context.Context, grace time.Duration, servers ...Server) error {
	g, gctx := errgroup.WithContext(ctx)
	for _, s := range servers {
		g.Go(func() error {
			if err := s.Serve(); err != nil {
				return fmt.Errorf("%s: %w", s.Name(), err)
			}
			return nil
		})
	}
	g.Go(func() error {
		<-gctx.Done() // root ctx canceled (signal) or a sibling failed
		sctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grace)
		defer cancel()
		var wg sync.WaitGroup
		errs := make([]error, len(servers))
		for i, s := range servers {
			wg.Add(1)
			go func() {
				defer wg.Done()
				if err := s.Shutdown(sctx); err != nil {
					errs[i] = fmt.Errorf("%s shutdown: %w", s.Name(), err)
				}
			}()
		}
		wg.Wait()
		return errors.Join(errs...)
	})
	return g.Wait()
}

// HTTP adapts *http.Server.
type HTTP struct {
	N   string
	Srv *http.Server
	Lis net.Listener
}

func (h HTTP) Name() string { return h.N }

func (h HTTP) Serve() error {
	if err := h.Srv.Serve(h.Lis); !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	return nil
}

func (h HTTP) Shutdown(ctx context.Context) error { return h.Srv.Shutdown(ctx) }

// GRPC adapts *grpc.Server. GracefulStop waits for pending RPCs, so it
// runs in a goroutine and falls back to Stop when ctx expires.
type GRPC struct {
	N   string
	Srv *grpc.Server
	Lis net.Listener
}

func (g GRPC) Name() string { return g.N }

func (g GRPC) Serve() error {
	if err := g.Srv.Serve(g.Lis); !errors.Is(err, grpc.ErrServerStopped) {
		return err
	}
	return nil
}

func (g GRPC) Shutdown(ctx context.Context) error {
	done := make(chan struct{})
	go func() { g.Srv.GracefulStop(); close(done) }()
	select {
	case <-done:
		return nil
	case <-ctx.Done():
		g.Srv.Stop()
		return ctx.Err()
	}
}

// RPC serves a net/rpc server. net/rpc has no Shutdown, so this adapter
// closes the listener, waits for open connections to finish their
// calls, and closes them when ctx expires.
type RPC struct {
	N   string
	Srv *rpc.Server
	Lis net.Listener

	mu      sync.Mutex
	conns   map[net.Conn]struct{}
	wg      sync.WaitGroup
	closing bool
}

func (r *RPC) Name() string { return r.N }

func (r *RPC) Serve() error {
	for {
		c, err := r.Lis.Accept()
		if err != nil {
			r.mu.Lock()
			closing := r.closing
			r.mu.Unlock()
			if closing {
				return nil
			}
			return err
		}
		r.mu.Lock()
		if r.conns == nil {
			r.conns = map[net.Conn]struct{}{}
		}
		r.conns[c] = struct{}{}
		r.wg.Add(1)
		r.mu.Unlock()
		go func() {
			defer r.wg.Done()
			r.Srv.ServeConn(c) // returns when the client hangs up
			r.mu.Lock()
			delete(r.conns, c)
			r.mu.Unlock()
		}()
	}
}

func (r *RPC) Shutdown(ctx context.Context) error {
	r.mu.Lock()
	r.closing = true
	r.mu.Unlock()
	_ = r.Lis.Close()
	done := make(chan struct{})
	go func() { r.wg.Wait(); close(done) }()
	select {
	case <-done:
		return nil
	case <-ctx.Done():
		r.mu.Lock()
		for c := range r.conns {
			_ = c.Close()
		}
		r.mu.Unlock()
		<-done
		return nil
	}
}

// Func adapts a run function that blocks until its ctx is canceled,
// such as a Watermill router or a consumer loop.
type Func struct {
	N      string
	Start  func(ctx context.Context) error
	cancel context.CancelFunc
	done   chan struct{}
	ready  chan struct{}
	once   sync.Once
}

// NewFunc builds a Func adapter.
func NewFunc(name string, start func(ctx context.Context) error) *Func {
	return &Func{N: name, Start: start, done: make(chan struct{}), ready: make(chan struct{})}
}

func (f *Func) Name() string { return f.N }

func (f *Func) Serve() error {
	ctx, cancel := context.WithCancel(context.Background())
	f.cancel = cancel
	close(f.ready)
	defer close(f.done)
	err := f.Start(ctx)
	if errors.Is(err, context.Canceled) {
		return nil
	}
	return err
}

func (f *Func) Shutdown(ctx context.Context) error {
	<-f.ready
	f.once.Do(f.cancel)
	select {
	case <-f.done:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
go
package lifecycle

import (
	"context"
	"errors"
	"io"
	"net"
	"net/http"
	"net/rpc"
	"testing"
	"time"

	"google.golang.org/grpc"
)

type Echo struct{}

func (Echo) Say(in string, out *string) error { *out = in; return nil }

func TestRunStopsAllServersAndFinishesInFlightRequest(t *testing.T) {
	ctx, cancel := context.WithCancel(t.Context())

	httpLis, _ := net.Listen("tcp", "127.0.0.1:0")
	grpcLis, _ := net.Listen("tcp", "127.0.0.1:0")
	rpcLis, _ := net.Listen("tcp", "127.0.0.1:0")

	started := make(chan struct{})
	mux := http.NewServeMux()
	mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
		close(started)
		time.Sleep(150 * time.Millisecond) // in-flight while shutdown begins
		io.WriteString(w, "done")
	})
	rs := rpc.NewServer()
	if err := rs.Register(Echo{}); err != nil {
		t.Fatal(err)
	}
	consumerStopped := make(chan struct{})

	runErr := make(chan error, 1)
	go func() {
		runErr <- Run(ctx, 2*time.Second,
			HTTP{N: "http", Srv: &http.Server{Handler: mux, ReadHeaderTimeout: time.Second}, Lis: httpLis},
			GRPC{N: "grpc", Srv: grpc.NewServer(), Lis: grpcLis},
			&RPC{N: "rpc", Srv: rs, Lis: rpcLis},
			NewFunc("consumer", func(ctx context.Context) error {
				<-ctx.Done()
				close(consumerStopped)
				return ctx.Err()
			}),
		)
	}()

	body := make(chan string, 1)
	go func() {
		resp, err := http.Get("http://" + httpLis.Addr().String() + "/slow")
		if err != nil {
			body <- err.Error()
			return
		}
		b, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		body <- string(b)
	}()
	<-started
	cancel() // SIGTERM in production: signal.NotifyContext cancels ctx

	select {
	case err := <-runErr:
		if err != nil {
			t.Fatalf("Run: %v", err)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("Run did not return")
	}
	if got := <-body; got != "done" {
		t.Fatalf("in-flight request got %q, want done", got)
	}
	<-consumerStopped
	if _, err := net.DialTimeout("tcp", httpLis.Addr().String(), 200*time.Millisecond); err == nil {
		t.Fatal("http listener still accepting")
	}
}

func TestOneFailingServerStopsTheOthers(t *testing.T) {
	httpLis, _ := net.Listen("tcp", "127.0.0.1:0")
	boom := errors.New("broker connection lost")
	err := Run(t.Context(), time.Second,
		HTTP{N: "http", Srv: &http.Server{ReadHeaderTimeout: time.Second}, Lis: httpLis},
		NewFunc("listener", func(ctx context.Context) error { return boom }),
	)
	if !errors.Is(err, boom) {
		t.Fatalf("got %v, want %v", err, boom)
	}
}

The logger's main, which runs the three servers under one lifecycle.Run:

go
// Command logger runs logger-service: REST on :80, net/rpc on :5001,
// gRPC on :50001, all in one process, entries in MongoDB.
package main

import (
	"context"
	"net/http"
	"net/rpc"
	"os"
	"os/signal"
	"syscall"
	"time"

	"go.opentelemetry.io/otel"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"

	logsv1 "academy/microservices-project/gen/logs/v1"
	"academy/microservices-project/logger"
	"academy/microservices-project/platform/config"
	"academy/microservices-project/platform/lifecycle"
	"academy/microservices-project/platform/web"
	"academy/microservices-project/tracing"
)

func main() {
	log := web.NewLogger(os.Stdout, "logger-service")
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	tp := otel.GetTracerProvider()

	store, err := logger.OpenMongo(config.Env("MONGO_URL", "mongodb://admin:secret@mongo:27017"))
	if err != nil {
		log.Error("mongo", "err", err)
		os.Exit(1)
	}
	defer store.Client.Disconnect(context.Background())
	svc := &logger.Service{Store: store, Log: log}

	httpLis, err := config.Listen(config.Env("PORT", "80"))
	if err != nil {
		log.Error("listen", "err", err)
		os.Exit(1)
	}
	rpcLis, err := config.Listen(config.Env("RPC_PORT", "5001"))
	if err != nil {
		log.Error("listen", "err", err)
		os.Exit(1)
	}
	grpcLis, err := config.Listen(config.Env("GRPC_PORT", "50001"))
	if err != nil {
		log.Error("listen", "err", err)
		os.Exit(1)
	}

	rs := rpc.NewServer()
	if err := rs.Register(&logger.RPCServer{Svc: svc, Tracer: tp.Tracer("logger-rpc")}); err != nil {
		log.Error("rpc register", "err", err)
		os.Exit(1)
	}
	gs := grpc.NewServer(tracing.GRPCServerOption(tp))
	logsv1.RegisterLogServiceServer(gs, &logger.GRPCServer{Svc: svc})
	hs := health.NewServer() // grpc.health.v1.Health for grpc-health-probe
	healthpb.RegisterHealthServer(gs, hs)

	srv := &http.Server{Handler: tracing.HTTPHandler(svc.Routes(), "logger-service", tp), ReadHeaderTimeout: 5 * time.Second}
	err = lifecycle.Run(ctx, 10*time.Second,
		lifecycle.HTTP{N: "http", Srv: srv, Lis: httpLis},
		&lifecycle.RPC{N: "rpc", Srv: rs, Lis: rpcLis},
		lifecycle.GRPC{N: "grpc", Srv: gs, Lis: grpcLis},
	)
	if err != nil {
		log.Error("exit", "err", err)
		os.Exit(1)
	}
}

Structured logging with request IDs across services, and propagation Must-know ​

In plain words: The broker gives every request an ID (or keeps the one the edge proxy sent), puts it in the context, sends it to every downstream as X-Request-ID (or inside the payload or message headers where there are no HTTP headers), and every service's logger writes it as request_id on every JSON log line. One search for request_id=r-1 then shows the request in all five services.

Common misunderstanding: "The trace ID makes request IDs unnecessary." They overlap but answer different needs: the request ID is cheap, always present, human-readable, safe to show to a user in an error ("quote r-1 to support") and works even when tracing is sampled away. Many teams log both. A second one: "Put the logger in the context." The logger is a dependency; only the ID travels in ctx, and a slog handler reads it (see context values).

Definition: web.RequestIDMiddleware reuses an inbound X-Request-ID of at most 64 characters or creates 16 hex characters from crypto/rand, stores it with web.WithRequestID and echoes it in the response. web.PropagatingTransport copies it into outgoing requests. web.ContextHandler wraps a slog.JSONHandler and adds service and request_id on every ...Context call. Propagation per transport: HTTP header; net/rpc field RPCPayload.RequestID; gRPC field LogEntry.request_id (gRPC metadata would also work); AMQP message header X-Request-ID plus LogEvent.RequestID. Logging itself is in CLI Flags, Env & log/slog.

1  front end   POST /handle                              (no id)
2  broker      RequestIDMiddleware -> r-7f3a...; ctx carries it; response X-Request-ID: r-7f3a...
3  broker      {"level":"ERROR","msg":"mail failed","service":"broker-service","request_id":"r-7f3a...","status":504}
4  broker -> auth   X-Request-ID: r-7f3a...      auth log line has the same request_id
5  broker -> RabbitMQ   header X-Request-ID + event.request_id
6  listener -> logger   X-Request-ID: r-7f3a...  MongoDB document request_id: r-7f3a...

Success is logged too: the broker writes one INFO line per accepted action (event published with routing_key and event_id, log written, authenticated, mail accepted), so a 202 is findable by its request ID (TestSuccessIsLoggedWithRequestID).

Real scenario: a user reports "error r-7f3a"; support finds the broker's 504 and the mailer's "smtp server too slow" lines; a log pipeline (Loki, Elasticsearch) groups by request_id; a MongoDB audit entry is traced back to the HTTP request that caused it hours earlier through the queue.

HopCarrierSet byRead by
Front end → brokerX-Request-ID (optional)Edge proxy or nobodyRequestIDMiddleware
Broker → auth, mailer, logger RESTX-Request-ID headerPropagatingTransportRequestIDMiddleware
Broker → logger net/rpcRPCPayload.RequestIDclients.LogRPCRPCServer.LogInfo
Broker → logger gRPCLogEntry.request_idclients.LogGRPCGRPCServer.WriteLog
Broker → RabbitMQ → listenerAMQP header + LogEvent.RequestIDclients.Eventslistener handler
Any service → stdoutrequest_id JSON fieldweb.ContextHandlerlog pipeline
go
// Package web holds the HTTP plumbing every service shares: JSON
// helpers with a body limit, the request-ID middleware, a slog handler
// that stamps request_id on every record, and a client transport that
// forwards the ID to the next hop.
package web

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"

	"academy/microservices-project/contracts"
)

// MaxBody is the largest JSON body any service accepts (1 MiB).
const MaxBody = 1 << 20

// ReadJSON decodes exactly one JSON value from the body into dst.
func ReadJSON(w http.ResponseWriter, r *http.Request, dst any) error {
	r.Body = http.MaxBytesReader(w, r.Body, MaxBody)
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	if err := dec.Decode(dst); err != nil {
		return fmt.Errorf("bad JSON: %w", err)
	}
	if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
		return errors.New("body must contain a single JSON value")
	}
	return nil
}

// WriteJSON writes v with the given status.
func WriteJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

// ErrorJSON writes the shared error envelope.
func ErrorJSON(w http.ResponseWriter, status int, err error) {
	WriteJSON(w, status, contracts.JSONResponse{Error: true, Message: err.Error()})
}

type requestIDKey struct{}

// WithRequestID stores id in ctx.
func WithRequestID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, requestIDKey{}, id)
}

// RequestID returns the id stored in ctx, or "".
func RequestID(ctx context.Context) string {
	id, _ := ctx.Value(requestIDKey{}).(string)
	return id
}

// NewID returns 16 random hex characters.
func NewID() string {
	var b [8]byte
	_, _ = rand.Read(b[:])
	return hex.EncodeToString(b[:])
}

// RequestIDMiddleware reuses an inbound X-Request-ID (set by the
// broker or the edge proxy) or creates one, puts it in ctx and echoes
// it in the response.
func RequestIDMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get(contracts.HeaderRequestID)
		if id == "" || len(id) > 64 {
			id = NewID()
		}
		w.Header().Set(contracts.HeaderRequestID, id)
		next.ServeHTTP(w, r.WithContext(WithRequestID(r.Context(), id)))
	})
}

// PropagatingTransport copies the request ID from the outgoing
// request's ctx into the X-Request-ID header.
type PropagatingTransport struct {
	Base http.RoundTripper
}

// RoundTrip implements http.RoundTripper.
func (t PropagatingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	base := t.Base
	if base == nil {
		base = http.DefaultTransport
	}
	if id := RequestID(r.Context()); id != "" && r.Header.Get(contracts.HeaderRequestID) == "" {
		r = r.Clone(r.Context())
		r.Header.Set(contracts.HeaderRequestID, id)
	}
	return base.RoundTrip(r)
}

// ContextHandler adds request_id and service to every record logged
// with a ...Context call.
type ContextHandler struct {
	slog.Handler
	Service string
}

// Handle implements slog.Handler.
func (h ContextHandler) Handle(ctx context.Context, r slog.Record) error {
	r.AddAttrs(slog.String("service", h.Service))
	if id := RequestID(ctx); id != "" {
		r.AddAttrs(slog.String("request_id", id))
	}
	return h.Handler.Handle(ctx, r)
}

// WithAttrs keeps the wrapper in the chain.
func (h ContextHandler) WithAttrs(as []slog.Attr) slog.Handler {
	return ContextHandler{Handler: h.Handler.WithAttrs(as), Service: h.Service}
}

// WithGroup keeps the wrapper in the chain.
func (h ContextHandler) WithGroup(name string) slog.Handler {
	return ContextHandler{Handler: h.Handler.WithGroup(name), Service: h.Service}
}

// NewLogger returns a JSON logger for one service.
func NewLogger(w io.Writer, service string) *slog.Logger {
	return slog.New(ContextHandler{Handler: slog.NewJSONHandler(w, nil), Service: service})
}
go
package web

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"academy/microservices-project/contracts"
)

func TestRequestIDTravelsAcrossTwoServices(t *testing.T) {
	var seenDownstream string
	logs := &bytes.Buffer{}
	log := NewLogger(logs, "logger")
	downstream := httptest.NewServer(RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		seenDownstream = RequestID(r.Context())
		log.InfoContext(r.Context(), "entry stored")
	})))
	defer downstream.Close()

	client := &http.Client{Transport: PropagatingTransport{}}
	upstream := RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, downstream.URL, nil)
		resp, err := client.Do(req)
		if err != nil {
			t.Error(err)
			return
		}
		resp.Body.Close()
	}))

	req := httptest.NewRequest(http.MethodPost, "/handle", nil)
	req.Header.Set(contracts.HeaderRequestID, "r-42")
	rec := httptest.NewRecorder()
	upstream.ServeHTTP(rec, req)

	if seenDownstream != "r-42" {
		t.Fatalf("downstream saw %q, want r-42", seenDownstream)
	}
	if rec.Header().Get(contracts.HeaderRequestID) != "r-42" {
		t.Fatal("request id not echoed")
	}
	var rec2 map[string]any
	if err := json.Unmarshal(logs.Bytes(), &rec2); err != nil {
		t.Fatal(err)
	}
	if rec2["request_id"] != "r-42" || rec2["service"] != "logger" {
		t.Fatalf("log line %s", logs.String())
	}
}

func TestReadJSONRejectsTrailingAndUnknown(t *testing.T) {
	for _, body := range []string{`{"name":"a"}{"name":"b"}`, `{"nme":"a"}`} {
		var dst contracts.LogPayload
		r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body))
		if err := ReadJSON(httptest.NewRecorder(), r, &dst); err == nil {
			t.Fatalf("%s: want error", body)
		}
	}
}

Timeouts and retries per hop, and idempotency Must-know ​

In plain words: Each downstream gets its own small budget per attempt, inside the request's overall budget. Only failures that another attempt can fix are retried (a timeout of one attempt, a refused connection, 502/503/504, gRPC Unavailable), with random backoff, and never after the overall budget is gone. Because a retried write may already have happened, every attempt carries the same idempotency key, and the receiving service ignores a key it has seen.

Common misunderstanding: "Retries make a call reliable." Retries without idempotency turn one email into three; retries at every layer (front end x broker x listener) multiply load during an outage; and a retry after the caller gave up is wasted work. A timeout is also not a failure of the downstream: the write may have committed just after your deadline, which is exactly why the key is needed (Stripe's API docs describe the same mechanism for payments). See Timeouts, Retries & Jitter and API Idempotency for the system-level policy.

Definition: resilience.Hop{Name, Timeout, Attempts, Backoff} and resilience.Do(ctx, hop, fn): for each attempt, context.WithTimeout(ctx, hop.Timeout) (skipped when Timeout is 0, as in the monolith), call fn, stop on success, stop if the caller's ctx.Err() != nil, stop if !Retryable(err), otherwise sleep a full-jitter backoff rand.Int64N(Backoff << n) in a select with ctx.Done(). Retryable is true for context.DeadlineExceeded (an attempt timed out), rpc.ErrShutdown, any net.Error, UpstreamError with 502/503/504 and gRPC Unavailable/DeadlineExceeded; false for 4xx, an open breaker and everything else. The broker's key is the client's Idempotency-Key or the request ID; the logger uses it as _id (upsert), the mailer keeps seen keys, the listener passes the event ID.

     broker (LogHop: 1s per attempt, 3 attempts, 50ms backoff; request budget from the client)
1    attempt 1  WriteLog(key r-1)  -> 503 "starting"               retryable, sleep rand(0..50ms)
2    attempt 2  WriteLog(key r-1)  -> context deadline exceeded    the write may have happened! retryable
3    attempt 3  WriteLog(key r-1)  -> 202 id r-1                   logger: _id r-1 exists -> duplicate, no second row
   TestRetriesReuseOneIdempotencyKey: 3 calls, all with key "r-1"
   TestPerAttemptTimeoutInsideCallerBudget: 25 ms attempts inside a 60 ms budget -> at most 3 calls, < 200 ms

Real scenario: a logger pod restarting during a deploy (503 for a second); a mailer that accepted the message and then timed out on the response; a gRPC connection reset by a load balancer; a front end that retries a POST after a network blip with the same Idempotency-Key.

HopPer-attempt timeoutAttemptsIdempotent howRetry on
broker → auth2 s2Read-only (SELECT + compare)Timeout, conn errors, 502/503/504
broker → logger (REST, RPC, gRPC)1 s3Idempotency-Key → Mongo _id upsertSame, plus rpc.ErrShutdown, codes.Unavailable
broker → RabbitMQ1 s3Message UUID = event IDnet.Error and attempt timeouts only; other publish errors answer 503 at once
broker → mailer5 s2Mailer claims the key before sending (per process)Timeout, conn errors, 5xx; never when the breaker is open
listener → logger2 sWatermill Retry 5, then nackEvent ID as keyAny error except unknown version
go
// Package resilience is the per-hop policy the broker applies to every
// downstream call: a timeout per attempt, bounded retries with jitter
// for retryable errors only, a circuit breaker per dependency, and one
// function that maps any downstream error to the HTTP status the
// broker returns.
package resilience

import (
	"context"
	"errors"
	"fmt"
	"io"
	"math/rand/v2"
	"net"
	"net/http"
	"net/rpc"
	"time"

	"github.com/sony/gobreaker/v2"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// UpstreamError is a non-2xx answer from a downstream HTTP service.
type UpstreamError struct {
	Service string
	Status  int
	Message string
}

func (e *UpstreamError) Error() string {
	return fmt.Sprintf("%s answered %d: %s", e.Service, e.Status, e.Message)
}

// Hop is the policy for one downstream dependency.
type Hop struct {
	Name     string
	Timeout  time.Duration // per attempt
	Attempts int           // 1 = no retry
	Backoff  time.Duration // base; full jitter up to Backoff*2^n
}

// Do runs fn under the hop's policy. fn receives a ctx bounded by the
// per-attempt timeout and, inside that, by the caller's own deadline.
func Do(ctx context.Context, h Hop, fn func(ctx context.Context) error) error {
	attempts := max(h.Attempts, 1)
	var err error
	for n := range attempts {
		actx, cancel := ctx, context.CancelFunc(func() {})
		if h.Timeout > 0 { // 0 = no per-attempt limit (in-process calls)
			actx, cancel = context.WithTimeout(ctx, h.Timeout)
		}
		err = fn(actx)
		cancel()
		if err == nil {
			return nil
		}
		if ctx.Err() != nil { // the caller's budget is gone: never retry
			return err
		}
		if !Retryable(err) || n == attempts-1 {
			return err
		}
		wait := time.Duration(rand.Int64N(int64(h.Backoff<<n) + 1))
		t := time.NewTimer(wait)
		select {
		case <-ctx.Done():
			t.Stop()
			return err
		case <-t.C:
		}
	}
	return err
}

// Retryable reports whether another attempt can succeed: timeouts of a
// single attempt, connection failures, 502/503/504, gRPC Unavailable.
// Client errors (4xx) and an open breaker are never retried.
func Retryable(err error) bool {
	var ue *UpstreamError
	var ne net.Error
	switch {
	case errors.Is(err, gobreaker.ErrOpenState), errors.Is(err, gobreaker.ErrTooManyRequests):
		return false
	case errors.Is(err, context.DeadlineExceeded):
		return true
	case errors.Is(err, rpc.ErrShutdown), errors.Is(err, io.ErrUnexpectedEOF):
		return true // a broken net/rpc connection; the client redials
	case errors.As(err, &ue):
		return ue.Status == http.StatusBadGateway || ue.Status == http.StatusServiceUnavailable || ue.Status == http.StatusGatewayTimeout
	case errors.As(err, &ne):
		return true
	}
	if s, ok := status.FromError(err); ok {
		return s.Code() == codes.Unavailable || s.Code() == codes.DeadlineExceeded
	}
	return false
}

// NewBreaker returns a circuit breaker that opens after `failures`
// consecutive failures and probes again after `open`. 4xx answers are
// the caller's fault, so they count as successes for the breaker.
func NewBreaker(name string, failures uint32, open time.Duration, onChange func(name string, from, to gobreaker.State)) *gobreaker.CircuitBreaker[struct{}] {
	return gobreaker.NewCircuitBreaker[struct{}](gobreaker.Settings{
		Name:        name,
		MaxRequests: 1,
		Timeout:     open,
		ReadyToTrip: func(c gobreaker.Counts) bool { return c.ConsecutiveFailures >= failures },
		IsSuccessful: func(err error) bool {
			var ue *UpstreamError
			if errors.As(err, &ue) && ue.Status < 500 {
				return true
			}
			if s, ok := status.FromError(err); ok && err != nil {
				switch s.Code() {
				case codes.InvalidArgument, codes.NotFound, codes.AlreadyExists, codes.Unauthenticated, codes.PermissionDenied:
					return true
				}
			}
			return err == nil
		},
		IsExcluded:    func(err error) bool { return errors.Is(err, context.Canceled) },
		OnStateChange: onChange,
	})
}

// Guard runs fn through the breaker.
func Guard(cb *gobreaker.CircuitBreaker[struct{}], fn func() error) error {
	_, err := cb.Execute(func() (struct{}, error) { return struct{}{}, fn() })
	return err
}

// HTTPStatus maps a downstream error to the status the broker answers.
func HTTPStatus(err error) int {
	var ue *UpstreamError
	var ne net.Error
	switch {
	case err == nil:
		return http.StatusOK
	case errors.Is(err, gobreaker.ErrOpenState), errors.Is(err, gobreaker.ErrTooManyRequests):
		return http.StatusServiceUnavailable
	case errors.Is(err, context.DeadlineExceeded):
		return http.StatusGatewayTimeout
	case errors.As(err, &ue):
		if ue.Status >= 400 && ue.Status < 500 {
			return ue.Status // the caller's mistake travels back unchanged
		}
		return http.StatusBadGateway
	case errors.Is(err, rpc.ErrShutdown), errors.Is(err, io.ErrUnexpectedEOF), errors.As(err, &ne):
		return http.StatusBadGateway
	}
	if s, ok := status.FromError(err); ok {
		switch s.Code() {
		case codes.InvalidArgument:
			return http.StatusBadRequest
		case codes.NotFound:
			return http.StatusNotFound
		case codes.AlreadyExists:
			return http.StatusConflict
		case codes.Unauthenticated:
			return http.StatusUnauthorized
		case codes.PermissionDenied:
			return http.StatusForbidden
		case codes.ResourceExhausted:
			return http.StatusTooManyRequests
		case codes.Unavailable:
			return http.StatusServiceUnavailable
		case codes.DeadlineExceeded:
			return http.StatusGatewayTimeout
		}
	}
	return http.StatusInternalServerError
}
go
package resilience

import (
	"context"
	"errors"
	"net/http"
	"testing"
	"time"

	"github.com/sony/gobreaker/v2"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func TestDoRetriesOnlyRetryableErrors(t *testing.T) {
	calls := 0
	err := Do(t.Context(), Hop{Timeout: 20 * time.Millisecond, Attempts: 3, Backoff: time.Millisecond}, func(ctx context.Context) error {
		calls++
		if calls < 3 {
			return &UpstreamError{Service: "logger", Status: 503, Message: "starting"}
		}
		return nil
	})
	if err != nil || calls != 3 {
		t.Fatalf("err=%v calls=%d, want nil after 3", err, calls)
	}

	calls = 0
	err = Do(t.Context(), Hop{Timeout: 20 * time.Millisecond, Attempts: 3, Backoff: time.Millisecond}, func(ctx context.Context) error {
		calls++
		return &UpstreamError{Service: "auth", Status: 401, Message: "invalid credentials"}
	})
	if calls != 1 || HTTPStatus(err) != http.StatusUnauthorized {
		t.Fatalf("4xx must not be retried: calls=%d status=%d", calls, HTTPStatus(err))
	}
}

func TestPerAttemptTimeoutInsideCallerBudget(t *testing.T) {
	ctx, cancel := context.WithTimeout(t.Context(), 60*time.Millisecond)
	defer cancel()
	calls := 0
	start := time.Now()
	err := Do(ctx, Hop{Timeout: 25 * time.Millisecond, Attempts: 10, Backoff: time.Millisecond}, func(ctx context.Context) error {
		calls++
		<-ctx.Done() // a hung mailer
		return ctx.Err()
	})
	if !errors.Is(err, context.DeadlineExceeded) || HTTPStatus(err) != http.StatusGatewayTimeout {
		t.Fatalf("err=%v", err)
	}
	if calls > 3 || time.Since(start) > 200*time.Millisecond {
		t.Fatalf("retries outlived the caller: calls=%d elapsed=%v", calls, time.Since(start))
	}
}

func TestBreakerOpensAndFailsFast(t *testing.T) {
	cb := NewBreaker("mailer", 3, time.Hour, nil)
	down := errors.New("dial tcp mailer-service:80: connect: connection refused")
	for range 3 {
		_ = Guard(cb, func() error { return down })
	}
	if cb.State() != gobreaker.StateOpen {
		t.Fatalf("state %v, want open", cb.State())
	}
	called := false
	err := Guard(cb, func() error { called = true; return nil })
	if called || !errors.Is(err, gobreaker.ErrOpenState) || HTTPStatus(err) != http.StatusServiceUnavailable {
		t.Fatalf("open breaker must fail fast: called=%v err=%v", called, err)
	}
}

func TestClientErrorsDoNotTripTheBreaker(t *testing.T) {
	cb := NewBreaker("auth", 2, time.Hour, nil)
	for range 5 {
		_ = Guard(cb, func() error { return &UpstreamError{Service: "auth", Status: 401} })
	}
	if cb.State() != gobreaker.StateClosed {
		t.Fatalf("401s tripped the breaker")
	}
}

func TestStatusMapping(t *testing.T) {
	cases := map[error]int{
		status.Error(codes.InvalidArgument, "name required"): 400,
		status.Error(codes.Unavailable, "logger down"):       503,
		status.Error(codes.DeadlineExceeded, "slow"):         504,
		&UpstreamError{Status: 500}:                          502,
		&UpstreamError{Status: 422}:                          422,
		context.DeadlineExceeded:                             504,
		gobreaker.ErrTooManyRequests:                         503,
		errors.New("something else"):                         500,
	}
	for err, want := range cases {
		if got := HTTPStatus(err); got != want {
			t.Errorf("%v: got %d want %d", err, got, want)
		}
	}
}
One downstream call: budget, attempt, breaker, retry, statusrequest ctxr.Context()client budgetattempt nWithTimeout(per hop)circuit breakerclosed: callopen: fail fastdownstreamauth / loggermailerclassify errorRetryable(err)?errbackofffull jitterselect on ctxyesnext attempt, same keyHTTPStatus(err)401/422 pass through, 502, 503, 504no / budget gone202 + JSONokIdempotency-Key: one per client request, reused by every attemptErrOpenState and 4xx are never retried; ctx.Err() != nil stops the loop

Circuit breaker with sony/gobreaker Must-know ​

In plain words: If the mailer has failed five times in a row, the broker stops calling it for 30 seconds and answers 503 at once. After 30 seconds it lets one request through; if that works, calls resume, otherwise it waits again.

Common misunderstanding: "A breaker is a retry policy." It is the opposite: it prevents calls. It protects the caller's goroutines and connections and gives the struggling service room to recover. Fowler's description: "You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips". A second one: "Every error should count." A 401 or 422 means the callee is healthy and the caller is wrong; counting those would let one bad client open the breaker for everyone. IsSuccessful here counts 4xx as success (TestClientErrorsDoNotTripTheBreaker) and IsExcluded ignores context.Canceled (the client left; says nothing about the mailer).

Definition: github.com/sony/gobreaker/v2 v2.4.0 is generic: gobreaker.NewCircuitBreaker[T](gobreaker.Settings{...}) and cb.Execute(func() (T, error)). Settings: MaxRequests ("the maximum number of requests allowed to pass through when the CircuitBreaker is half-open. If MaxRequests is 0, CircuitBreaker allows only 1 request"), Interval (closed-state count reset; "If Interval is 0, CircuitBreaker does not clear the internal Counts during the closed state"), BucketPeriod (rolling window), Timeout (open → half-open; 0 means 60 s), ReadyToTrip ("The default ReadyToTrip returns true when the number of consecutive failures is more than 5"), OnStateChange, IsSuccessful, IsExcluded. Errors: gobreaker.ErrOpenState (circuit breaker is open) and ErrTooManyRequests (too many requests, half-open and over MaxRequests). resilience.NewBreaker(name, failures, open, onChange) sets MaxRequests: 1, ReadyToTrip: ConsecutiveFailures >= failures; the broker uses 5 failures and 30 s in production, and Guard(cb, fn) adapts it to func() error. Patterns: Circuit Breaker.

state       event                                   broker answers           mailer sees
closed      fail, fail, fail, fail, fail (5 in a row) 504/502 each           5 calls
open        next request                            503 at once (ErrOpenState)  nothing
open        ... 30 s pass (Timeout)
half-open   1 request allowed (MaxRequests 1)       call goes through        1 call
closed      it succeeds                             202                      normal traffic
(half-open  it fails -> open again for 30 s)

Real scenario: an SMTP provider outage during a campaign; a mailer stuck on a full disk; a dependency rate-limiting you with 503s; protecting a broker whose goroutines would otherwise pile up waiting on a dead host.

Settinggobreaker defaultThis projectWhy
ReadyToTripconsecutive failures > 5consecutive failures ≥ 5 (3 in tests)Explicit threshold
Timeout (open)60 s30 s production, 1 h in testsProbe sooner
MaxRequests (half-open)0 → 11One probe
Interval0 (never reset while closed)0Consecutive count resets on success anyway
IsSuccessfulerr == nilalso 4xx and gRPC client codesCaller errors are not outages
IsExcludednonecontext.CanceledA client leaving is not a mailer failure
Status when open—503"Try later", no call made

Error propagation and status mapping Must-know ​

In plain words: Every downstream failure, from any transport, is turned into exactly one HTTP status for the front end. The caller's own mistakes (400, 401, 404, 409, 422) pass through with their message; the system's problems become 502, 503 or 504 with a generic message, and the details stay in the broker's log under the request ID.

Common misunderstanding: "Pass the downstream's status through unchanged." A 500 from the logger passed through says "the broker crashed"; a 503 passed through may make a front end retry a call that already committed; and passing a 5xx body through can leak internal hostnames ("dial tcp postgres:5432..."). The other extreme, "always 500" (the Before broker), hides the wrong password behind an outage.

Definition: resilience.HTTPStatus(err): nil → 200; ErrOpenState/ErrTooManyRequests → 503; context.DeadlineExceeded → 504; UpstreamError 4xx → same status, other → 502; rpc.ErrShutdown or net.Error → 502; gRPC InvalidArgument → 400, NotFound → 404, AlreadyExists → 409, Unauthenticated → 401, PermissionDenied → 403, ResourceExhausted → 429, Unavailable → 503, DeadlineExceeded → 504; anything else → 500. Broker.fail writes the upstream message only for 4xx and logs everything else with the status. RabbitMQ publish failures are answered 503 explicitly.

1  auth says 401 {"message":"invalid credentials"}        -> broker 401 "invalid credentials"
2  auth says 503 {"message":"user store unavailable"}     -> broker retries once -> 502 "authentication failed: Bad Gateway"
3  logger gRPC codes.InvalidArgument                      -> broker 400
4  mailer: two attempts hit the 5 s per-attempt timeout   -> broker 504 "mail failed: Gateway Timeout"
5  breaker open                                           -> broker 503 "mail failed: Service Unavailable"

Real scenario: a front end showing "wrong password" vs "try again later"; an SLO dashboard counting 5xx by downstream; a client library deciding which statuses to retry; a security review checking that no internal addresses leak.

Downstream signalTransportBroker statusMessage to clientRetried by broker
400/401/404/409/422RESTSameDownstream's messageNo
500REST502GenericNo
502/503/504REST502GenericYes
rpc.ServerError "log entry needs a name"net/rpc422Downstream's stringNo
rpc.ServerError "log store unavailable"net/rpc502GenericYes
rpc.ErrShutdown, io.ErrUnexpectedEOFnet/rpc502GenericYes (redial)
codes.InvalidArgumentgRPC400Generic text from the brokerNo
codes.UnavailablegRPC503GenericYes
Attempt deadlineany504GenericYes, while the budget lasts
Breaker openany503GenericNo
Publish failedAMQP503"event bus unavailable, retry later"Only network errors

Testing strategy: unit per service, contract tests, httptest/bufconn/GoChannel fakes Must-know ​

In plain words: Nothing in the test suite needs Docker, Postgres, MongoDB, RabbitMQ or an SMTP server. Each service is tested alone through its HTTP handler with fakes behind its interfaces (unit per service); each client is tested against the real handler of the service it calls (contract tests); and the whole system runs in one process with real HTTP, net/rpc and gRPC on loopback and GoChannel instead of RabbitMQ (end to end).

Common misunderstanding: "Fakes prove nothing; only a real stack does." Fakes prove the logic and the contracts, fast and deterministically; what they do not prove is the adapters' behaviour against real servers (the Postgres SQL, the MongoDB upsert, RabbitMQ topology, a real SMTP provider), and the page says so. That part belongs to a small integration suite with testcontainers or the Compose stack, run less often. Another one: "GoChannel behaves like RabbitMQ." It matches topic names exactly (no log.* wildcard), has no durability and no redelivery after a crash; the listener tests subscribe to exact topics for that reason.

Definition: the pyramid used here:

LevelWhat runsToolsExample test
Unit per serviceOne handler + fakeshttptest.NewRecorder, httptest.NewRequestWithContext, in-memory storesauth.TestAuthenticate, broker.TestSlowMailerIsCutAt504
TransportOne service over its real protocolhttptest.NewServer, net.Listen("tcp", "127.0.0.1:0") + rpc.Dial, bufconn.Listen + grpc.NewClient("passthrough:///bufnet")logger.TestGRPCOverBufconn, TestNetRPCRegisterDialCall
ConsumerRouter + GoChannelgochannel.NewGoChannel, flaky fakeslistener.TestLoggerDownIsRetried
ContractClient vs the provider's real handlerGolden JSON files, httptest.NewServer(svc.Routes())clients.TestLogContractAllThreeTransports, contracts.TestGoldenRoundTrip
SMTP protocolgo-mail vs a 60-line fake SMTP servernet.Listen, bufiomailer.TestGoMailAgainstFakeSMTP
End to endAll services, one processallinone.Start, tracetest.NewInMemoryExporterallinone.TestEndToEndTracesAndShutdown
Integration with real storesCompose stack or testcontainersNot in this moduleDescribed in Lab, not run
1  go test ./auth        httptest recorder, MemoryStore, bcrypt.MinCost          ~ms
2  go test ./logger      httptest server, 127.0.0.1:0 net/rpc, bufconn gRPC       ~ms
3  go test ./listener    GoChannel pub/sub, flaky logger fake                     ~ms
4  go test ./clients     each client against the provider's real handler          ~ms
5  go test ./allinone    8 lifecycle servers on loopback, GoChannel, in-memory OTel  ~0.6 s
   whole module with -race: 14 packages with tests, all ok, no network beyond loopback

Real scenario: a CI job that must finish in a minute; a refactor of contracts that should fail fast; a new transport added to the logger; a flaky integration environment you do not want on every pull request. Testing tools in depth: Testing & Benchmarking, Mocking with Interfaces.

Fix / how to use it: the contract tests, one file:

go
package clients

// Contract tests: each client (the consumer side) runs against the
// real handler of the service it calls (the provider side), in
// process. A field renamed on one side fails here, not in staging.

import (
	"context"
	"errors"
	"io"
	"log/slog"
	"net"
	"net/http"
	"net/http/httptest"
	"net/rpc"
	"strings"
	"testing"
	"time"

	"github.com/ThreeDotsLabs/watermill/message"
	"golang.org/x/crypto/bcrypt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/test/bufconn"

	"academy/microservices-project/auth"
	"academy/microservices-project/contracts"
	logsv1 "academy/microservices-project/gen/logs/v1"
	"academy/microservices-project/logger"
	"academy/microservices-project/mailer"
	"academy/microservices-project/platform/resilience"
	"academy/microservices-project/platform/web"
)

var quiet = slog.New(slog.DiscardHandler)

func TestAuthContract(t *testing.T) {
	hash, _ := bcrypt.GenerateFromPassword([]byte("verysecret"), bcrypt.MinCost)
	svc := auth.New(&auth.MemoryStore{Users: map[string]auth.User{
		"admin@example.test": {ID: 1, Email: "admin@example.test", FirstName: "Ada", PasswordHash: hash, Active: true},
	}}, nil, quiet)
	srv := httptest.NewServer(svc.Routes())
	defer srv.Close()
	c := AuthREST{BaseURL: srv.URL, HTTP: HTTPClient(nil)}

	u, err := c.Authenticate(t.Context(), contracts.AuthPayload{Email: "admin@example.test", Password: "verysecret"})
	if err != nil || u.ID != 1 || u.FirstName != "Ada" {
		t.Fatalf("u=%+v err=%v", u, err)
	}
	_, err = c.Authenticate(t.Context(), contracts.AuthPayload{Email: "admin@example.test", Password: "bad"})
	var ue *resilience.UpstreamError
	if !errors.As(err, &ue) || ue.Status != 401 || ue.Message != auth.ErrInvalidCredentials.Error() {
		t.Fatalf("got %v", err)
	}
}

func TestLogContractAllThreeTransports(t *testing.T) {
	store := &logger.MemoryStore{}
	svc := &logger.Service{Store: store, Log: quiet}

	// REST
	srv := httptest.NewServer(svc.Routes())
	defer srv.Close()
	rest := LogREST{BaseURL: srv.URL, HTTP: HTTPClient(nil)}

	// net/rpc
	rs := rpc.NewServer()
	if err := rs.Register(&logger.RPCServer{Svc: svc}); err != nil {
		t.Fatal(err)
	}
	lis, _ := net.Listen("tcp", "127.0.0.1:0")
	defer lis.Close()
	go rs.Accept(lis)
	rpcc := &LogRPC{Addr: lis.Addr().String()}

	// gRPC over bufconn
	bl := bufconn.Listen(1 << 20)
	gs := grpc.NewServer()
	logsv1.RegisterLogServiceServer(gs, &logger.GRPCServer{Svc: svc})
	go gs.Serve(bl)
	defer gs.Stop()
	conn, err := grpc.NewClient("passthrough:///bufnet",
		grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return bl.DialContext(ctx) }),
		grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		t.Fatal(err)
	}
	defer conn.Close()
	grpcc := LogGRPC{Client: logsv1.NewLogServiceClient(conn)}

	ctx := web.WithRequestID(t.Context(), "r-contract")
	writers := map[string]interface {
		WriteLog(context.Context, string, contracts.LogPayload) (string, error)
	}{"rest": rest, "rpc": rpcc, "grpc": grpcc}
	for name, w := range writers {
		ctx, cancel := context.WithTimeout(ctx, time.Second)
		id, err := w.WriteLog(ctx, "", contracts.LogPayload{Name: "event", Data: name})
		if err != nil || id == "" {
			cancel()
			t.Fatalf("%s: id=%q err=%v", name, id, err)
		}
		// Every transport maps "no name" to a 4xx-class error.
		_, err = w.WriteLog(ctx, "", contracts.LogPayload{})
		cancel()
		if code := resilience.HTTPStatus(err); code < 400 || code >= 500 {
			t.Fatalf("%s: invalid entry mapped to %d (%v)", name, code, err)
		}
	}
	for _, e := range store.All() {
		if e.RequestID != "r-contract" {
			t.Fatalf("request id lost on a transport: %+v", e)
		}
	}
	if len(store.All()) != 3 {
		t.Fatalf("stored %d", len(store.All()))
	}

	// The same idempotency key, retried on each transport: one entry each.
	for name, w := range writers {
		for range 2 {
			if _, err := w.WriteLog(ctx, "key-"+name, contracts.LogPayload{Name: "retry"}); err != nil {
				t.Fatalf("%s: %v", name, err)
			}
		}
	}
	if len(store.All()) != 6 {
		t.Fatalf("stored %d, want 6: a retried key was stored twice", len(store.All()))
	}

	// Store down: every transport gives a retryable 5xx-class error and
	// no internal error text.
	store.Err = errors.New("mongo: dial tcp mongo:27017: connection refused")
	for name, w := range writers {
		_, err := w.WriteLog(ctx, "", contracts.LogPayload{Name: "event"})
		code := resilience.HTTPStatus(err)
		if code < 500 || !resilience.Retryable(err) || strings.Contains(err.Error(), "mongo:27017") {
			t.Fatalf("%s: store down mapped to %d, retryable=%v, err=%v", name, code, resilience.Retryable(err), err)
		}
	}
}

func TestRPCClientRedialsAfterLoggerRestart(t *testing.T) {
	svc := &logger.Service{Store: &logger.MemoryStore{}, Log: quiet}
	rs := rpc.NewServer()
	_ = rs.Register(&logger.RPCServer{Svc: svc})
	lis, _ := net.Listen("tcp", "127.0.0.1:0")
	addr := lis.Addr().String()
	accepted := make(chan net.Conn, 1)
	go func() {
		c, err := lis.Accept()
		if err != nil {
			return
		}
		accepted <- c
		rs.ServeConn(c)
	}()
	c := &LogRPC{Addr: addr}
	if _, err := c.WriteLog(t.Context(), "", contracts.LogPayload{Name: "a"}); err != nil {
		t.Fatal(err)
	}
	(<-accepted).Close() // logger restarts: connection gone
	lis.Close()
	lis2, err := net.Listen("tcp", addr)
	if err != nil {
		t.Skip("port reuse not available:", err)
	}
	defer lis2.Close()
	go rs.Accept(lis2)

	err = resilience.Do(t.Context(), resilience.Hop{Timeout: time.Second, Attempts: 3, Backoff: time.Millisecond}, func(ctx context.Context) error {
		_, err := c.WriteLog(ctx, "", contracts.LogPayload{Name: "b"})
		return err
	})
	if err != nil {
		t.Fatalf("no recovery after ErrShutdown: %v", err)
	}
}

func TestMailContract(t *testing.T) {
	ms, _ := mailer.New(senderFunc(func(ctx context.Context, m mailer.Rendered) error { return nil }), "noreply@example.test", quiet)
	srv := httptest.NewServer(ms.Routes())
	defer srv.Close()
	c := MailREST{BaseURL: srv.URL, HTTP: HTTPClient(nil)}
	if err := c.Send(t.Context(), "k", contracts.MailPayload{To: "a@example.test", Subject: "s", Message: "m"}); err != nil {
		t.Fatal(err)
	}
	err := c.Send(t.Context(), "k2", contracts.MailPayload{To: "a@example.test"})
	if resilience.HTTPStatus(err) != http.StatusUnprocessableEntity {
		t.Fatalf("got %v", err)
	}
}

type senderFunc func(ctx context.Context, m mailer.Rendered) error

func (f senderFunc) Send(ctx context.Context, m mailer.Rendered) error { return f(ctx, m) }

// blockingPub never returns, like a publish waiting for a confirm that
// never comes.
type blockingPub struct{ release chan struct{} }

func (b blockingPub) Publish(topic string, msgs ...*message.Message) error { <-b.release; return nil }
func (b blockingPub) Close() error                                         { return nil }

func TestEventsPublishIsBoundedByCtx(t *testing.T) {
	pub := blockingPub{release: make(chan struct{})}
	defer close(pub.release)
	ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
	defer cancel()
	start := time.Now()
	err := Events{Pub: pub}.PublishLog(ctx, "k", "info", contracts.LogPayload{Name: "event"})
	if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 500*time.Millisecond {
		t.Fatalf("err=%v after %v", err, time.Since(start))
	}
}

// A peer that accepts and never reads: a large request blocks in the
// write inside rpc.Client.Go. The hop's ctx must still bound it.
func TestRPCSendIsBoundedByCtx(t *testing.T) {
	lis, _ := net.Listen("tcp", "127.0.0.1:0")
	defer lis.Close()
	go func() {
		c, err := lis.Accept()
		if err == nil {
			defer c.Close()
			time.Sleep(10 * time.Second) // never reads
		}
	}()
	c := &LogRPC{Addr: lis.Addr().String()}
	defer c.Close()
	ctx, cancel := context.WithTimeout(t.Context(), 200*time.Millisecond)
	defer cancel()
	done := make(chan error, 1)
	go func() {
		_, err := c.WriteLog(ctx, "k", contracts.LogPayload{Name: "big", Data: strings.Repeat("x", 32<<20)})
		done <- err
	}()
	select {
	case err := <-done:
		if !errors.Is(err, context.DeadlineExceeded) {
			t.Fatalf("got %v", err)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("net/rpc send ignored the ctx deadline")
	}
}

// A blackholed address: SYNs are dropped, connect hangs.
func TestRPCDialIsBoundedByCtx(t *testing.T) {
	c := &LogRPC{Addr: "10.255.255.1:5001"}
	ctx, cancel := context.WithTimeout(t.Context(), 200*time.Millisecond)
	defer cancel()
	done := make(chan error, 1)
	start := time.Now()
	go func() { _, err := c.WriteLog(ctx, "k", contracts.LogPayload{Name: "a"}); done <- err }()
	select {
	case err := <-done:
		if time.Since(start) < 50*time.Millisecond && !errors.Is(err, context.DeadlineExceeded) {
			t.Skipf("no blackhole on this network (dial failed fast: %v)", err)
		}
		if !errors.Is(err, context.DeadlineExceeded) {
			t.Fatalf("got %v", err)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("net/rpc dial ignored the ctx deadline")
	}
}

// The logger closes the connection while a call is pending: net/rpc
// fails that call with io.ErrUnexpectedEOF, not rpc.ErrShutdown. It must
// be dropped and retried like ErrShutdown.
func TestRPCUnexpectedEOFIsRedialedAndRetried(t *testing.T) {
	svc := &logger.Service{Store: &logger.MemoryStore{}, Log: quiet}
	rs := rpc.NewServer()
	_ = rs.Register(&logger.RPCServer{Svc: svc})
	lis, _ := net.Listen("tcp", "127.0.0.1:0")
	defer lis.Close()
	go func() {
		first, err := lis.Accept()
		if err != nil {
			return
		}
		// Read the whole request (so the close is a clean FIN, not a
		// reset): the call is now pending on the client.
		buf := make([]byte, 64<<10)
		_, _ = first.Read(buf)
		_ = first.SetReadDeadline(time.Now().Add(50 * time.Millisecond))
		for {
			if _, err := first.Read(buf); err != nil {
				break
			}
		}
		first.Close() // logger crashes mid-call
		for {
			c, err := lis.Accept()
			if err != nil {
				return
			}
			go rs.ServeConn(c)
		}
	}()
	c := &LogRPC{Addr: lis.Addr().String()}
	defer c.Close()
	attempts := 0
	var firstErr error
	err := resilience.Do(t.Context(), resilience.Hop{Timeout: time.Second, Attempts: 2, Backoff: time.Millisecond}, func(ctx context.Context) error {
		attempts++
		_, err := c.WriteLog(ctx, "k-eof", contracts.LogPayload{Name: "a"})
		if attempts == 1 {
			firstErr = err
		}
		return err
	})
	if !errors.Is(firstErr, io.ErrUnexpectedEOF) {
		t.Fatalf("first attempt got %v, want io.ErrUnexpectedEOF", firstErr)
	}
	if err != nil || attempts != 2 {
		t.Fatalf("err=%v attempts=%d, want success on the 2nd attempt", err, attempts)
	}
}

The clients they exercise:

go
// Package clients holds the broker's (and listener's) typed clients for
// each downstream service and transport. Each one returns errors the
// resilience package can classify: *resilience.UpstreamError for HTTP,
// gRPC status errors, context errors, net errors.
package clients

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/rpc"
	"sync"
	"time"

	"github.com/ThreeDotsLabs/watermill/message"
	"go.opentelemetry.io/otel/trace"

	"academy/microservices-project/contracts"
	logsv1 "academy/microservices-project/gen/logs/v1"
	"academy/microservices-project/logger"
	"academy/microservices-project/platform/resilience"
	"academy/microservices-project/platform/web"
	"academy/microservices-project/tracing"
)

func postJSON(ctx context.Context, hc *http.Client, service, url, key string, in, out any) error {
	body, err := json.Marshal(in)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	if key != "" {
		req.Header.Set(contracts.HeaderIdempotencyKey, key)
	}
	resp, err := hc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	raw, err := io.ReadAll(io.LimitReader(resp.Body, web.MaxBody))
	if err != nil {
		return err
	}
	var env contracts.JSONResponse
	env.Data = out
	if err := json.Unmarshal(raw, &env); err != nil {
		return &resilience.UpstreamError{Service: service, Status: resp.StatusCode, Message: "non-JSON answer"}
	}
	if resp.StatusCode >= 300 || env.Error {
		return &resilience.UpstreamError{Service: service, Status: resp.StatusCode, Message: env.Message}
	}
	return nil
}

// HTTPClient returns the client every service uses for its hops: no
// global timeout (the ctx carries it), request-ID propagation on top
// of the given transport (which may add tracing).
func HTTPClient(base http.RoundTripper) *http.Client {
	return &http.Client{Transport: web.PropagatingTransport{Base: base}}
}

// AuthREST calls POST {BaseURL}/authenticate.
type AuthREST struct {
	BaseURL string // "http://authentication-service" in Compose
	HTTP    *http.Client
}

func (a AuthREST) Authenticate(ctx context.Context, p contracts.AuthPayload) (contracts.AuthUser, error) {
	var u contracts.AuthUser
	err := postJSON(ctx, a.HTTP, "authentication-service", a.BaseURL+"/authenticate", "", p, &u)
	return u, err
}

// LogREST calls POST {BaseURL}/log.
type LogREST struct {
	BaseURL string
	HTTP    *http.Client
}

func (l LogREST) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	var out map[string]string
	if err := postJSON(ctx, l.HTTP, "logger-service", l.BaseURL+"/log", key, p, &out); err != nil {
		return "", err
	}
	return out["id"], nil
}

// Log satisfies auth.Logger.
func (l LogREST) Log(ctx context.Context, p contracts.LogPayload) error {
	_, err := l.WriteLog(ctx, "", p)
	return err
}

// LogRPC calls RPCServer.LogInfo over net/rpc (gob over TCP). net/rpc
// has no context anywhere, so this client adds one around every step:
//   - connect: net.Dialer.DialContext + rpc.NewClient instead of the
//     context-free rpc.Dial;
//   - send: Client.Go writes the request synchronously, so it runs in a
//     goroutine; if ctx ends before the write finished, the connection
//     is closed (that unblocks the write) and dropped;
//   - wait: select on call.Done and ctx.Done.
//
// A broken connection shows up as rpc.ErrShutdown (we or a previous
// call closed it) or io.ErrUnexpectedEOF (the server hung up while the
// call was pending); both drop the client so the next attempt redials.
type LogRPC struct {
	Addr string // "logger-service:5001"

	mu     sync.Mutex
	client *rpc.Client
}

func (l *LogRPC) conn(ctx context.Context) (*rpc.Client, error) {
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.client != nil {
		return l.client, nil
	}
	nc, err := (&net.Dialer{}).DialContext(ctx, "tcp", l.Addr)
	if err != nil {
		if ctx.Err() != nil { // "i/o timeout" from the dialer: say why
			return nil, fmt.Errorf("dial %s: %w", l.Addr, ctx.Err())
		}
		return nil, err
	}
	l.client = rpc.NewClient(nc)
	return l.client, nil
}

func (l *LogRPC) drop(c *rpc.Client) {
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.client == c {
		_ = c.Close()
		l.client = nil
	}
}

// Close hangs up. net/rpc servers cannot tell an idle connection from
// a busy one, so a client that never closes holds up their shutdown.
func (l *LogRPC) Close() error {
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.client == nil {
		return nil
	}
	err := l.client.Close()
	l.client = nil
	return err
}

// brokenConn reports errors after which the connection is unusable:
// rpc.ErrShutdown, io.ErrUnexpectedEOF (server closed while the call was
// pending) and any other transport error (a reset). Only a
// rpc.ServerError means the connection itself is fine.
func brokenConn(err error) bool {
	var se rpc.ServerError
	return err != nil && !errors.As(err, &se)
}

func (l *LogRPC) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	c, err := l.conn(ctx)
	if err != nil {
		return "", err
	}
	var reply string
	args := logger.RPCPayload{Name: p.Name, Data: p.Data, RequestID: web.RequestID(ctx), Key: key, Trace: tracing.Inject(ctx)}
	done := make(chan *rpc.Call, 1)
	sent := make(chan struct{})
	go func() {
		c.Go("RPCServer.LogInfo", args, &reply, done) // blocks while writing
		close(sent)
	}()
	select {
	case call := <-done:
		<-sent
		if brokenConn(call.Error) {
			l.drop(c)
			return "", fmt.Errorf("logger-service (rpc): %w", call.Error)
		}
		var se rpc.ServerError
		if errors.As(call.Error, &se) {
			// The only thing net/rpc gives back is a string, so the
			// contract is the exact text of the two errors it may send.
			status := http.StatusServiceUnavailable // retryable
			if string(se) == logger.ErrInvalid.Error() {
				status = http.StatusUnprocessableEntity
			}
			return "", &resilience.UpstreamError{Service: "logger-service (rpc)", Status: status, Message: string(se)}
		}
		return reply, call.Error
	case <-ctx.Done():
		select {
		case <-sent:
			// Sent; the call keeps running on the server, we only stop
			// waiting. The connection is fine for other calls.
		default:
			// Still writing: the peer is not reading. Kill the conn.
			l.drop(c)
		}
		return "", ctx.Err()
	}
}

// LogGRPC calls logs.v1.LogService/WriteLog.
type LogGRPC struct {
	Client logsv1.LogServiceClient
}

func (l LogGRPC) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	resp, err := l.Client.WriteLog(ctx, &logsv1.WriteLogRequest{Entry: &logsv1.LogEntry{
		Name: p.Name, Data: p.Data, RequestId: web.RequestID(ctx), IdempotencyKey: key,
	}})
	if err != nil {
		return "", err
	}
	return resp.GetId(), nil
}

// MailREST calls POST {BaseURL}/send.
type MailREST struct {
	BaseURL string
	HTTP    *http.Client
}

func (m MailREST) Send(ctx context.Context, key string, p contracts.MailPayload) error {
	return postJSON(ctx, m.HTTP, "mailer-service", m.BaseURL+"/send", key, p, nil)
}

// Events publishes LogEvents. With watermill-amqp the topic is the
// routing key on the logs_topic exchange; with GoChannel it is just a
// topic name.
type Events struct {
	Pub    message.Publisher
	Tracer trace.Tracer // optional producer span
	Now    func() time.Time
}

func (e Events) PublishLog(ctx context.Context, key, severity string, p contracts.LogPayload) error {
	now := time.Now
	if e.Now != nil {
		now = e.Now
	}
	if e.Tracer != nil {
		var span trace.Span
		ctx, span = e.Tracer.Start(ctx, contracts.RoutingKey(severity)+" publish", trace.WithSpanKind(trace.SpanKindProducer))
		defer span.End()
	}
	ev := contracts.LogEvent{ID: key, Version: 1, Name: p.Name, Data: p.Data, Severity: severity, OccurredAt: now().UTC(), RequestID: web.RequestID(ctx)}
	body, err := json.Marshal(ev)
	if err != nil {
		return err
	}
	msg := message.NewMessage(key, body) // message UUID = event ID = idempotency key
	msg.Metadata.Set(contracts.HeaderRequestID, ev.RequestID)
	tracing.InjectMessage(ctx, msg)
	msg.SetContext(ctx)
	// watermill-amqp checks msg.Context() only before publishing; the
	// wait for the publisher confirm ignores it. Bound the whole call
	// here; on timeout the outcome is unknown, and a retry reuses the
	// same message UUID, which consumers deduplicate.
	done := make(chan error, 1)
	go func() { done <- e.Pub.Publish(contracts.RoutingKey(severity), msg) }()
	select {
	case err := <-done:
		if err != nil {
			return fmt.Errorf("publish %s: %w", contracts.RoutingKey(severity), err)
		}
		return nil
	case <-ctx.Done():
		return fmt.Errorf("publish %s: waiting for confirm: %w", contracts.RoutingKey(severity), ctx.Err())
	}
}

Makefile multi-binary build, Dockerfiles, Compose topology (describe) Important ​

In plain words: One module, six main packages under cmd/ (five services plus a health-check helper), one Makefile that builds them all, one Dockerfile that builds any of them by a build argument, and one Compose file that wires them with Postgres, MongoDB, RabbitMQ and Mailpit.

Common misunderstanding: "Each microservice needs its own repository and Dockerfile." Independent deployment is about images and release pipelines, not repositories. One module keeps contracts compiled with every service; the Dockerfile's ARG SERVICE produces five different images. A second one: "docker compose up is the test." It is a smoke test of wiring; the logic is proven by go test before any image is built.

Definition: the Makefile's SERVICES := broker authentication logger mailer listener; build runs CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o bin/$@ ./cmd/$@ per service plus bin/healthcheck; vet, test (-race -count=1), proto (buf lint, buf generate), docker, up, down. The Dockerfile is multi-stage: FROM golang:1.24 AS build, go mod download (cached layer), build /out/app and /out/healthcheck, then FROM gcr.io/distroless/static-debian12:nonroot with only the two binaries. The Compose file defines a shared x-go-service block (restart policy, stop_grace_period: 15s, healthcheck) and the five services, postgres:18 (with pg_isready and the schema mounted into docker-entrypoint-initdb.d), mongo:8, rabbitmq:4-management, axllent/mailpit:v1.34; only 8080 (broker), 15672 (RabbitMQ UI) and 8025 (Mailpit UI) are published. Layout and Docker practice are in Project Layout, Linting & Builds. The Compose file was validated with docker compose config (static parsing only) and is described here; the stack was not started.

# Multi-binary build: one module, six commands, one Dockerfile.
# `make build` puts every binary in bin/; `make docker` builds one image
# per service from deploy/Dockerfile with SERVICE as a build arg.
SERVICES := broker authentication logger mailer listener
GOFLAGS  := -trimpath
LDFLAGS  := -s -w

.PHONY: all build test vet proto docker up down clean $(SERVICES)

all: vet test build

build: $(SERVICES) bin/healthcheck

$(SERVICES):
	CGO_ENABLED=0 go build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o bin/$@ ./cmd/$@

bin/healthcheck:
	CGO_ENABLED=0 go build $(GOFLAGS) -ldflags "$(LDFLAGS)" -o $@ ./cmd/healthcheck

vet:
	test -z "$$(gofmt -l .)"
	go vet ./...

test:
	go test -race -count=1 ./...

proto:
	buf lint
	buf generate

docker:
	for s in $(SERVICES); do \
	  docker build -f deploy/Dockerfile --build-arg SERVICE=$$s -t academy/$$s-service:dev . || exit 1; \
	done

up:
	docker compose -f deploy/docker-compose.yml up -d --build

down:
	docker compose -f deploy/docker-compose.yml down

clean:
	$(RM) -r bin

The broker's main: configuration from the environment with Compose names as defaults, clients, hop policies, server timeouts:

go
// Command broker runs broker-service: HTTP on :80 inside its container.
package main

import (
	"context"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/sony/gobreaker/v2"
	"go.opentelemetry.io/otel"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"academy/microservices-project/amqpbus"
	"academy/microservices-project/broker"
	"academy/microservices-project/clients"
	"academy/microservices-project/contracts"
	logsv1 "academy/microservices-project/gen/logs/v1"
	"academy/microservices-project/platform/config"
	"academy/microservices-project/platform/lifecycle"
	"academy/microservices-project/platform/resilience"
	"academy/microservices-project/platform/web"
	"academy/microservices-project/tracing"
)

func main() {
	log := web.NewLogger(os.Stdout, "broker-service")
	if err := run(log); err != nil {
		log.Error("exit", "err", err)
		os.Exit(1)
	}
}

func run(log *slog.Logger) error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	tp := otel.GetTracerProvider() // an OTLP exporter would be installed here

	hc := clients.HTTPClient(tracing.HTTPTransport(http.DefaultTransport, tp))
	conn, err := grpc.NewClient(config.Env("LOGGER_GRPC", "dns:///logger-service:50001"),
		grpc.WithTransportCredentials(insecure.NewCredentials()), tracing.GRPCDialOption(tp))
	if err != nil {
		return err
	}
	defer conn.Close()
	amqpConn, ch, err := amqpbus.Dial(config.Env("AMQP_URL", "amqp://guest:guest@rabbitmq:5672/"))
	if err != nil {
		return err // RabbitMQ down at start: exit and let Compose restart us
	}
	defer amqpConn.Close()
	// The broker declares only the exchange; the listener owns its
	// queues. Until they are bound, mandatory publishes come back as
	// ErrUnroutable and the broker answers 503 instead of losing events.
	if err := amqpbus.DeclareExchange(ch); err != nil {
		return err
	}
	pub, err := amqpbus.NewPublisher(ch)
	if err != nil {
		return err
	}
	logURL := config.Env("LOGGER_URL", "http://logger-service")

	b := &broker.Broker{
		Auth: clients.AuthREST{BaseURL: config.Env("AUTH_URL", "http://authentication-service"), HTTP: hc},
		Logs: map[string]broker.LogWriter{
			contracts.ViaREST: clients.LogREST{BaseURL: logURL, HTTP: hc},
			contracts.ViaRPC:  &clients.LogRPC{Addr: config.Env("LOGGER_RPC", "logger-service:5001")},
			contracts.ViaGRPC: clients.LogGRPC{Client: logsv1.NewLogServiceClient(conn)},
		},
		Events:   clients.Events{Pub: pub, Tracer: tp.Tracer("broker-events")},
		Mail:     clients.MailREST{BaseURL: config.Env("MAILER_URL", "http://mailer-service"), HTTP: hc},
		Log:      log,
		AuthHop:  resilience.Hop{Name: "auth", Timeout: 2 * time.Second, Attempts: 2, Backoff: 50 * time.Millisecond},
		LogHop:   resilience.Hop{Name: "log", Timeout: time.Second, Attempts: 3, Backoff: 50 * time.Millisecond},
		MailHop:  resilience.Hop{Name: "mail", Timeout: 5 * time.Second, Attempts: 2, Backoff: 200 * time.Millisecond},
		EventHop: resilience.Hop{Name: "event", Timeout: time.Second, Attempts: 3, Backoff: 50 * time.Millisecond},
		MailBreaker: resilience.NewBreaker("mailer-service", 5, 30*time.Second, func(name string, from, to gobreaker.State) {
			log.Warn("circuit breaker state change", "breaker", name, "from", from.String(), "to", to.String())
		}),
	}

	lis, err := config.Listen(config.Env("PORT", "80"))
	if err != nil {
		return err
	}
	srv := &http.Server{
		Handler:           tracing.HTTPHandler(b.Routes(), "broker-service", tp),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      15 * time.Second,
		IdleTimeout:       60 * time.Second,
	}
	log.Info("listening", "addr", lis.Addr().String())
	return lifecycle.Run(ctx, 10*time.Second, lifecycle.HTTP{N: "http", Srv: srv, Lis: lis})
}
# One Dockerfile for every service: docker build --build-arg SERVICE=broker .
# Build context is the module root (the directory with go.mod).
FROM golang:1.24 AS build
ARG SERVICE
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o /out/app ./cmd/${SERVICE} \
 && CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o /out/healthcheck ./cmd/healthcheck

FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
COPY --from=build /out/healthcheck /healthcheck
USER nonroot:nonroot
ENTRYPOINT ["/app"]
yml
# Compose topology for the project (written and described; not run in
# this chapter). Every service joins the default network and is
# reachable by its service name: http://logger-service, postgres:5432,
# amqp://rabbitmq:5672. Only the broker and the dev UIs are published.
name: academy-microservices

x-go-service: &go-service
  restart: unless-stopped
  stop_grace_period: 15s # SIGTERM, then SIGKILL after 15 s
  healthcheck:
    test: ["CMD", "/healthcheck", "http://127.0.0.1/readyz"]
    interval: 10s
    timeout: 3s
    retries: 3
    start_period: 10s

services:
  broker-service:
    <<: *go-service
    build: { context: .., dockerfile: deploy/Dockerfile, args: { SERVICE: broker } }
    ports: ["8080:80"]
    environment:
      AUTH_URL: http://authentication-service
      LOGGER_URL: http://logger-service
      LOGGER_RPC: logger-service:5001
      LOGGER_GRPC: dns:///logger-service:50001
      MAILER_URL: http://mailer-service
      AMQP_URL: amqp://guest:guest@rabbitmq:5672/
    depends_on:
      rabbitmq: { condition: service_healthy }
      authentication-service: { condition: service_healthy }
      logger-service: { condition: service_healthy }
      mailer-service: { condition: service_healthy }
      # the listener declares listener.logs/listener.poison at startup;
      # until then the broker's mandatory publishes return 503, not 202
      listener-service: { condition: service_started }

  authentication-service:
    <<: *go-service
    build: { context: .., dockerfile: deploy/Dockerfile, args: { SERVICE: authentication } }
    environment:
      DSN: postgres://auth:secret@postgres:5432/users?sslmode=disable
      LOGGER_URL: http://logger-service
    depends_on:
      postgres: { condition: service_healthy }

  logger-service:
    <<: *go-service
    build: { context: .., dockerfile: deploy/Dockerfile, args: { SERVICE: logger } }
    environment:
      MONGO_URL: mongodb://admin:secret@mongo:27017
    depends_on:
      mongo: { condition: service_healthy }

  mailer-service:
    <<: *go-service
    build: { context: .., dockerfile: deploy/Dockerfile, args: { SERVICE: mailer } }
    environment:
      MAIL_HOST: mailpit
      MAIL_PORT: "1025"
      MAIL_FROM: noreply@example.test
    depends_on:
      mailpit: { condition: service_started }

  listener-service:
    <<: *go-service
    build: { context: .., dockerfile: deploy/Dockerfile, args: { SERVICE: listener } }
    healthcheck: { disable: true } # no HTTP port; the restart policy covers it
    environment:
      AMQP_URL: amqp://guest:guest@rabbitmq:5672/
      LOGGER_URL: http://logger-service
    depends_on:
      rabbitmq: { condition: service_healthy }
      logger-service: { condition: service_healthy }

  postgres:
    image: postgres:18
    environment:
      POSTGRES_USER: auth
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: users
    volumes:
      - pg-data:/var/lib/postgresql
      - ../auth/schema.sql:/docker-entrypoint-initdb.d/001-schema.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 5s
      retries: 10

  mongo:
    image: mongo:8
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: secret
    volumes: [mongo-data:/data/db]
    healthcheck:
      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
      interval: 5s
      retries: 10

  rabbitmq:
    image: rabbitmq:4-management
    ports: ["15672:15672"] # management UI, development only
    healthcheck:
      test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
      interval: 5s
      retries: 10

  mailpit:
    image: axllent/mailpit:v1.34
    ports: ["8025:8025"] # web UI showing every mail the mailer "sent"

volumes:
  pg-data:
  mongo-data:
Compose topology (default network academy-microservices_default)
1  host:8080 ─▶ broker-service:80 ─┬─▶ authentication-service:80 ─▶ postgres:5432
2                                  ├─▶ logger-service:80 / :5001 / :50001 ─▶ mongo:27017
3                                  ├─▶ mailer-service:80 ─▶ mailpit:1025   (host:8025 UI)
4                                  └─▶ rabbitmq:5672 ─▶ listener-service ─▶ logger-service:80
5  start order: postgres, mongo, rabbitmq healthy -> auth, logger -> mailer -> broker, listener

Real scenario: a developer running the full stack on a laptop; a CI smoke job; a single-VM staging; the same images moved to Kubernetes later, where Compose's depends_on disappears and readiness probes and retries do the job.

ArtifactBuilt fromSize / note
bin/broker./cmd/broker16.9 MB (measured, darwin/arm64, -s -w)
bin/authentication./cmd/authentication19.9 MB
bin/logger./cmd/logger18.1 MB
bin/mailer./cmd/mailer14.4 MB
bin/listener./cmd/listener16.0 MB
bin/healthcheck./cmd/healthcheck5.6 MB
Image per servicedeploy/Dockerfile, SERVICE=<name>distroless static, non-root (not built here)

Observability: OpenTelemetry traces across REST/gRPC/AMQP Important ​

In plain words: Every hop creates a span and passes the trace context to the next one: HTTP and gRPC do it automatically through instrumentation libraries, AMQP through message headers, net/rpc by hand inside the payload. In a trace viewer one login shows as one tree: broker → auth → logger.

Common misunderstanding: "Tracing an HTTP server is enough." The trace breaks at every hop that is not instrumented: an http.Client without the otelhttp transport, a gRPC client without the stats handler, a message published without injecting traceparent into its headers, or a net/rpc call (no metadata at all). The all-in-one test asserts that each flow (auth, gRPC, net/rpc, event) is one trace.

Definition: tracing.Propagator = propagation.TraceContext{} writes and reads the W3C traceparent header (example from the spec: traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01). HTTP: otelhttp.NewHandler(h, name, ...) on servers, otelhttp.NewTransport(base, ...) on clients. gRPC: grpc.StatsHandler(otelgrpc.NewServerHandler(...)) and grpc.WithStatsHandler(otelgrpc.NewClientHandler(...)). AMQP/Watermill: Propagator.Inject(ctx, propagation.MapCarrier(msg.Metadata)) before publish, Extract in the handler, then a consumer span. net/rpc: tracing.Inject(ctx) into RPCPayload.Trace and Extract in LogInfo. Tests use sdktrace.NewTracerProvider(sdktrace.WithSyncer(tracetest.NewInMemoryExporter())); in production an OTLP exporter to a collector would be installed in each main (left as otel.GetTracerProvider() here, which is a no-op until one is set). Messaging span conventions (producer/consumer kinds, publish/process names) are in the OpenTelemetry messaging semantic conventions; more in Event-Driven Go, observability.

real output of go test -v ./allinone (one run; trace ids shortened; span names sorted)
trace 2311888e…: HTTP POST | authentication-service | broker-service | logger-service    auth + audit
trace dae6604c…: HTTP POST | broker-service | logger-service                             log via REST
trace 8e6e744c…: RPCServer.LogInfo | broker-service                                      log via net/rpc
trace 7a9944bc…: broker-service | logs.v1.LogService/WriteLog                            log via gRPC
trace 754b102e…: HTTP POST | broker-service | log-event process | log.info publish | logger-service   via RabbitMQ

Real scenario: finding which hop added 2 s to a login; seeing that the mailer's p99 is the whole request's p99; following an event from the broker to the MongoDB write minutes later; correlating a log line with a span through request_id and trace_id.

HopInstrumentationPropagation carrierSpan kinds
Front end → brokerotelhttp.NewHandlertraceparent header (if the client sends one)server
Broker → auth/mailer/logger RESTotelhttp.NewTransport + NewHandlertraceparent headerclient, server
Broker → logger gRPCotelgrpc client/server stats handlersgRPC metadata traceparentclient, server
Broker → logger net/rpcManual: tracing.Inject / Extract, Tracer.StartRPCPayload.Trace mapserver (manual)
Broker → RabbitMQ → listenerManual: InjectMessage / ExtractMessageAMQP headers via Watermill metadataproducer, consumer
go
// Package tracing wires OpenTelemetry across the three transports the
// project uses: HTTP (otelhttp), gRPC (otelgrpc stats handlers) and
// AMQP/Watermill messages (W3C traceparent in message metadata). The
// same carrier helpers are used by hand for net/rpc, which has no
// metadata of its own.
package tracing

import (
	"context"
	"net/http"

	"github.com/ThreeDotsLabs/watermill/message"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/grpc"
)

// Propagator writes and reads the W3C traceparent/tracestate headers.
var Propagator propagation.TextMapPropagator = propagation.TraceContext{}

// NewProvider returns a provider that exports every span synchronously
// to exp (an in-memory exporter in tests, OTLP in production).
func NewProvider(exp sdktrace.SpanExporter) *sdktrace.TracerProvider {
	return sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp), sdktrace.WithSampler(sdktrace.AlwaysSample()))
}

// HTTPHandler wraps a service's handler so each request starts (or
// continues) a server span.
func HTTPHandler(h http.Handler, service string, tp trace.TracerProvider) http.Handler {
	return otelhttp.NewHandler(h, service, otelhttp.WithTracerProvider(tp), otelhttp.WithPropagators(Propagator))
}

// HTTPTransport makes client spans and injects traceparent.
func HTTPTransport(base http.RoundTripper, tp trace.TracerProvider) http.RoundTripper {
	return otelhttp.NewTransport(base, otelhttp.WithTracerProvider(tp), otelhttp.WithPropagators(Propagator))
}

// GRPCServerOption and GRPCDialOption install the stats handlers.
func GRPCServerOption(tp trace.TracerProvider) grpc.ServerOption {
	return grpc.StatsHandler(otelgrpc.NewServerHandler(otelgrpc.WithTracerProvider(tp), otelgrpc.WithPropagators(Propagator)))
}

func GRPCDialOption(tp trace.TracerProvider) grpc.DialOption {
	return grpc.WithStatsHandler(otelgrpc.NewClientHandler(otelgrpc.WithTracerProvider(tp), otelgrpc.WithPropagators(Propagator)))
}

// InjectMessage copies the span context from ctx into msg.Metadata.
func InjectMessage(ctx context.Context, msg *message.Message) {
	Propagator.Inject(ctx, propagation.MapCarrier(msg.Metadata))
}

// ExtractMessage returns ctx carrying the producer's span context.
func ExtractMessage(ctx context.Context, msg *message.Message) context.Context {
	return Propagator.Extract(ctx, propagation.MapCarrier(msg.Metadata))
}

// Inject and Extract work on a plain map, for net/rpc payloads.
func Inject(ctx context.Context) map[string]string {
	m := map[string]string{}
	Propagator.Inject(ctx, propagation.MapCarrier(m))
	return m
}

func Extract(ctx context.Context, m map[string]string) context.Context {
	return Propagator.Extract(ctx, propagation.MapCarrier(m))
}
go
// Package allinone wires all five services in one process, each on its
// own loopback listener with its real transport (HTTP, net/rpc, gRPC),
// GoChannel standing in for RabbitMQ, and OpenTelemetry on every hop.
// lifecycle.Run starts them together and shuts them down together.
// Tests use it as the end-to-end system; cmd/* run one service each.
package allinone

import (
	"context"
	"log/slog"
	"net"
	"net/http"
	"net/rpc"
	"time"

	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"academy/microservices-project/auth"
	"academy/microservices-project/broker"
	"academy/microservices-project/clients"
	"academy/microservices-project/contracts"
	logsv1 "academy/microservices-project/gen/logs/v1"
	"academy/microservices-project/listener"
	"academy/microservices-project/logger"
	"academy/microservices-project/mailer"
	"academy/microservices-project/platform/lifecycle"
	"academy/microservices-project/platform/resilience"
	"academy/microservices-project/tracing"
)

// System is the running project.
type System struct {
	BrokerURL string
	Logs      *logger.MemoryStore
	servers   []lifecycle.Server
	closers   []func() error
}

// Options configures Start.
type Options struct {
	Users  map[string]auth.User
	Sender mailer.Sender
	Tracer trace.TracerProvider
	Log    *slog.Logger
}

func listen() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }

// Start binds every listener and builds every service. Call Run next.
func Start(o Options) (*System, error) {
	tp, log := o.Tracer, o.Log
	hc := clients.HTTPClient(tracing.HTTPTransport(http.DefaultTransport, tp))
	httpSrv := func(name string, h http.Handler) (lifecycle.Server, string, error) {
		l, err := listen()
		if err != nil {
			return nil, "", err
		}
		srv := &http.Server{Handler: tracing.HTTPHandler(h, name, tp), ReadHeaderTimeout: 2 * time.Second}
		return lifecycle.HTTP{N: name, Srv: srv, Lis: l}, "http://" + l.Addr().String(), nil
	}
	s := &System{Logs: &logger.MemoryStore{}}

	// logger-service: REST + net/rpc + gRPC on three listeners.
	logSvc := &logger.Service{Store: s.Logs, Log: log}
	logHTTP, logURL, err := httpSrv("logger-service", logSvc.Routes())
	if err != nil {
		return nil, err
	}
	rpcLis, err := listen()
	if err != nil {
		return nil, err
	}
	rs := rpc.NewServer()
	if err := rs.Register(&logger.RPCServer{Svc: logSvc, Tracer: tp.Tracer("logger-rpc")}); err != nil {
		return nil, err
	}
	grpcLis, err := listen()
	if err != nil {
		return nil, err
	}
	gs := grpc.NewServer(tracing.GRPCServerOption(tp))
	logsv1.RegisterLogServiceServer(gs, &logger.GRPCServer{Svc: logSvc})

	// authentication-service: audits through logger REST.
	authSvc := auth.New(&auth.MemoryStore{Users: o.Users}, clients.LogREST{BaseURL: logURL, HTTP: hc}, log)
	authHTTP, authURL, err := httpSrv("authentication-service", authSvc.Routes())
	if err != nil {
		return nil, err
	}

	// mailer-service.
	mailSvc, err := mailer.New(o.Sender, "noreply@example.test", log)
	if err != nil {
		return nil, err
	}
	mailHTTP, mailURL, err := httpSrv("mailer-service", mailSvc.Routes())
	if err != nil {
		return nil, err
	}

	// "RabbitMQ": GoChannel, exact topic names.
	bus := gochannel.NewGoChannel(gochannel.Config{}, watermill.NopLogger{})
	router, err := listener.NewRouter(listener.Config{
		Sub: bus, Pub: bus, Topics: []string{contracts.RoutingKey("info")}, Poison: contracts.LogPoisonKey,
		Logs: clients.LogREST{BaseURL: logURL, HTTP: hc}, Log: log, Tracer: tp,
		MaxRetries: 3, InitialInterval: 10 * time.Millisecond,
	})
	if err != nil {
		return nil, err
	}

	// broker-service: the front door.
	conn, err := grpc.NewClient("passthrough:///"+grpcLis.Addr().String(),
		grpc.WithTransportCredentials(insecure.NewCredentials()), tracing.GRPCDialOption(tp))
	if err != nil {
		return nil, err
	}
	rpcClient := &clients.LogRPC{Addr: rpcLis.Addr().String()}
	b := &broker.Broker{
		Auth: clients.AuthREST{BaseURL: authURL, HTTP: hc},
		Logs: map[string]broker.LogWriter{
			contracts.ViaREST: clients.LogREST{BaseURL: logURL, HTTP: hc},
			contracts.ViaRPC:  rpcClient,
			contracts.ViaGRPC: clients.LogGRPC{Client: logsv1.NewLogServiceClient(conn)},
		},
		Events:      clients.Events{Pub: bus, Tracer: tp.Tracer("broker-events")},
		Mail:        clients.MailREST{BaseURL: mailURL, HTTP: hc},
		Log:         log,
		AuthHop:     resilience.Hop{Name: "auth", Timeout: 2 * time.Second, Attempts: 2, Backoff: 50 * time.Millisecond},
		LogHop:      resilience.Hop{Name: "log", Timeout: time.Second, Attempts: 3, Backoff: 50 * time.Millisecond},
		MailHop:     resilience.Hop{Name: "mail", Timeout: 3 * time.Second, Attempts: 2, Backoff: 100 * time.Millisecond},
		EventHop:    resilience.Hop{Name: "event", Timeout: time.Second, Attempts: 3, Backoff: 50 * time.Millisecond},
		MailBreaker: resilience.NewBreaker("mailer-service", 5, 10*time.Second, nil),
	}
	brokerHTTP, brokerURL, err := httpSrv("broker-service", b.Routes())
	if err != nil {
		return nil, err
	}
	s.BrokerURL = brokerURL
	s.servers = []lifecycle.Server{
		brokerHTTP, authHTTP, logHTTP, mailHTTP,
		&lifecycle.RPC{N: "logger-rpc", Srv: rs, Lis: rpcLis},
		lifecycle.GRPC{N: "logger-grpc", Srv: gs, Lis: grpcLis},
		lifecycle.NewFunc("listener-service", router.Run),
		// The broker's net/rpc client hangs up on shutdown; otherwise the
		// rpc server waits the full grace period for an idle connection.
		lifecycle.NewFunc("broker-rpc-client", func(ctx context.Context) error {
			<-ctx.Done()
			_ = rpcClient.Close()
			return ctx.Err()
		}),
	}
	s.closers = []func() error{conn.Close, bus.Close}
	return s, nil
}

// Run blocks until ctx ends, then stops every server within grace.
func (s *System) Run(ctx context.Context, grace time.Duration) error {
	defer func() {
		for _, c := range s.closers {
			_ = c()
		}
	}()
	return lifecycle.Run(ctx, grace, s.servers...)
}
go
package allinone

import (
	"context"
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
	"sort"
	"strings"
	"sync"
	"testing"
	"time"

	"go.opentelemetry.io/otel/sdk/trace/tracetest"
	"golang.org/x/crypto/bcrypt"

	"academy/microservices-project/auth"
	"academy/microservices-project/contracts"
	"academy/microservices-project/mailer"
	"academy/microservices-project/tracing"
)

type outbox struct {
	mu   sync.Mutex
	mail []mailer.Rendered
}

func (o *outbox) Send(ctx context.Context, m mailer.Rendered) error {
	o.mu.Lock()
	defer o.mu.Unlock()
	o.mail = append(o.mail, m)
	return nil
}

func post(t *testing.T, url, body, reqID string) (int, contracts.JSONResponse) {
	t.Helper()
	req, _ := http.NewRequestWithContext(t.Context(), http.MethodPost, url+"/handle", strings.NewReader(body))
	req.Header.Set(contracts.HeaderRequestID, reqID)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	var out contracts.JSONResponse
	_ = json.Unmarshal(raw, &out)
	return resp.StatusCode, out
}

func TestEndToEndTracesAndShutdown(t *testing.T) {
	exp := tracetest.NewInMemoryExporter()
	tp := tracing.NewProvider(exp)
	hash, _ := bcrypt.GenerateFromPassword([]byte("verysecret"), bcrypt.MinCost)
	box := &outbox{}
	sys, err := Start(Options{
		Users:  map[string]auth.User{"admin@example.test": {ID: 1, Email: "admin@example.test", PasswordHash: hash, Active: true}},
		Sender: box, Tracer: tp, Log: slog.New(slog.DiscardHandler),
	})
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(t.Context())
	runErr := make(chan error, 1)
	go func() { runErr <- sys.Run(ctx, 2*time.Second) }()

	cases := []struct{ id, body string }{
		{"r-auth", `{"action":"auth","auth":{"email":"admin@example.test","password":"verysecret"}}`},
		{"r-rest", `{"action":"log","log":{"name":"event","data":"rest","via":"rest"}}`},
		{"r-rpc", `{"action":"log","log":{"name":"event","data":"rpc","via":"rpc"}}`},
		{"r-grpc", `{"action":"log","log":{"name":"event","data":"grpc","via":"grpc"}}`},
		{"r-event", `{"action":"log","log":{"name":"event","data":"amqp"}}`},
		{"r-mail", `{"action":"mail","mail":{"to":"a@example.test","subject":"Hi","message":"hello"}}`},
	}
	for _, c := range cases {
		if code, resp := post(t, sys.BrokerURL, c.body, c.id); code != http.StatusAccepted {
			t.Fatalf("%s: %d %s", c.id, code, resp.Message)
		}
	}
	code, _ := post(t, sys.BrokerURL, `{"action":"auth","auth":{"email":"admin@example.test","password":"wrong"}}`, "r-bad")
	if code != http.StatusUnauthorized {
		t.Fatalf("wrong password through the broker: %d", code)
	}

	// The event is asynchronous: wait for the listener to deliver it.
	deadline := time.Now().Add(2 * time.Second)
	byReq := map[string]bool{}
	for time.Now().Before(deadline) {
		byReq = map[string]bool{}
		for _, e := range sys.Logs.All() {
			byReq[e.RequestID] = true
		}
		if byReq["r-event"] {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	for _, id := range []string{"r-auth", "r-rest", "r-rpc", "r-grpc", "r-event"} {
		if !byReq[id] {
			t.Errorf("no log entry carries request id %s (have %v)", id, byReq)
		}
	}
	if len(box.mail) != 1 {
		t.Fatalf("mails %d", len(box.mail))
	}

	// Every span of the event flow shares one trace: broker HTTP server
	// span -> producer (inject) -> listener consumer span -> logger REST.
	spans := exp.GetSpans()
	traces := map[string]map[string]bool{} // trace id -> span names
	for _, s := range spans {
		id := s.SpanContext.TraceID().String()
		if traces[id] == nil {
			traces[id] = map[string]bool{}
		}
		traces[id][s.Name] = true
	}
	want := map[string][]string{
		"event": {"broker-service", "log.info publish", "log-event process", "logger-service"},
		"grpc":  {"broker-service", "logs.v1.LogService/WriteLog"},
		"rpc":   {"broker-service", "RPCServer.LogInfo"},
		"auth":  {"broker-service", "authentication-service", "logger-service"},
	}
	for id, set := range traces {
		names := make([]string, 0, len(set))
		for n := range set {
			names = append(names, n)
		}
		sort.Strings(names)
		t.Logf("trace %s…: %s", id[:8], strings.Join(names, " | "))
	}
	for flow, names := range want {
		found := false
		for _, set := range traces {
			ok := true
			for _, n := range names {
				ok = ok && set[n]
			}
			found = found || ok
		}
		if !found {
			t.Errorf("%s: no single trace contains %v", flow, names)
		}
	}

	cancel() // SIGTERM
	select {
	case err := <-runErr:
		if err != nil {
			t.Fatalf("Run: %v", err)
		}
	case <-time.After(3 * time.Second):
		t.Fatal("system did not shut down")
	}
	if _, err := http.Post(sys.BrokerURL+"/handle", "application/json", strings.NewReader("{}")); err == nil {
		t.Fatal("broker still accepting after shutdown")
	}
}

Mechanics ​

One request through every layer Important ​

A login, from the browser to Postgres and back, with everything each layer adds. Times are illustrative.

t=0ms    browser      POST http://localhost:8080/handle  {"action":"auth","auth":{...}}
t=0      broker       otelhttp server span "broker-service" (new trace 2311...)
t=0      broker       RequestIDMiddleware: X-Request-ID r-7f3a; ctx = WithRequestID(...)
t=0      broker       ReadJSON: MaxBytesReader 1 MiB, DisallowUnknownFields, single value
t=0      broker       action "auth" -> resilience.Do(AuthHop{2s, 2 attempts})
t=0      broker       attempt 1: ctx 2s; NewRequestWithContext POST http://authentication-service/authenticate
t=0      broker       PropagatingTransport: X-Request-ID; otelhttp transport: client span "HTTP POST", traceparent
t=1      DNS          authentication-service -> 172.20.0.4 (Compose embedded DNS)
t=2      auth         otelhttp server span "authentication-service" (child of the client span)
t=2      auth         ByEmail(ctx 500ms): SELECT ... FROM users WHERE email = $1  (pgx, pool)
t=5      auth         bcrypt.CompareHashAndPassword (cost 10: tens of ms)
t=60     auth         Audit.Log -> POST http://logger-service/log (span "logger-service", same trace)
t=63     auth         202 {"error":false,"message":"Authenticated ...","data":{...}}
t=63     broker       postJSON decodes envelope into AuthUser; 2xx -> nil error
t=63     broker       202 {"error":false,"message":"Authenticated","data":{...}}  X-Request-ID: r-7f3a
         logs: 3 services x JSON lines with "request_id":"r-7f3a"; trace: 5 spans under one trace id

Ports, names and knobs Important ​

KnobValueWhere
Broker published port8080:80Compose ports
Logger ports80 REST, 5001 net/rpc, 50001 gRPCcmd/logger env PORT, RPC_PORT, GRPC_PORT
Max JSON body1 MiB (web.MaxBody)Every service
Request ID length accepted≤ 64 characters, else regeneratedRequestIDMiddleware
Server timeouts (broker)ReadHeaderTimeout 5 s, ReadTimeout 10 s, WriteTimeout 15 s, IdleTimeout 60 scmd/broker
Shutdown grace10 s (mailer 12 s, a slow SMTP send) in lifecycle.Run; Compose stop_grace_period: 15s, always longermains, Compose
Readiness timeout1 s for all checks togetherhealth.Handler
Postgres query budget500 msPostgresStore.ByEmail
Postgres poolSetMaxOpenConns(10), SetMaxIdleConns(10), SetConnMaxIdleTime(5m)auth.OpenPostgres
MongoDB server selection2 slogger.OpenMongo
net/rpc server budget2 s (RPCServer.Timeout default)logger.RPCServer
bcrypt costDefaultCost (10) in production, MinCost (4) in testsauth
RabbitMQ prefetch10listener.AMQPConfig
Watermill retry (listener)5 retries from 200 ms, ×2cmd/listener
Watermill router close timeout5 slistener.NewRouter
Breaker5 consecutive failures, 30 s open, 1 probecmd/broker

Exact error texts Must-know ​

TextWhere it comes from
connection is shut downrpc.ErrShutdown: the net/rpc connection is gone; redial
unexpected EOFio.ErrUnexpectedEOF: the server closed the connection while the call was pending
amqp: message unroutable (no queue bound for routing key)amqpbus.ErrUnroutable: a mandatory publish came back as basic.return (reply 312 NO_ROUTE)
log entry needs a name (as rpc.ServerError)A server method's error, flattened to a string by net/rpc
rpc error: code = DeadlineExceeded desc = context deadline exceededgrpc-go client when the ctx deadline passed
rpc error: code = InvalidArgument desc = log entry needs a namestatus.Error(codes.InvalidArgument, ...) in GRPCServer.WriteLog
circuit breaker is opengobreaker.ErrOpenState
too many requestsgobreaker.ErrTooManyRequests (half-open, over MaxRequests)
dial tcp: lookup logger-service: no such hostGo resolver: the Compose name does not resolve (service not started, wrong network)
dial tcp 172.20.0.5:80: connect: connection refusedContainer up, process not listening (starting, crashed)
Exception (504) Reason: "channel/connection is not open"amqp091-go ErrClosed: the AMQP channel or connection was closed
server selection error: context deadline exceeded, current topology: { ... }MongoDB driver v2: no reachable server within the selection timeout
http: request body too largehttp.MaxBytesReader after 1 MiB
json: unknown field "nme"Decoder.DisallowUnknownFields
reason_poisoned metadataWatermill PoisonQueue adds the handler's error text here
invalid credentialsauth.ErrInvalidCredentials, the only login failure a caller sees
event bus unavailable, retry laterBroker's answer when publishing to RabbitMQ fails
delivery not confirmed for message [<uuid>]watermill-amqp: the broker nacked the publish (confirms on)
log store unavailableThe logger's fixed error over REST (JSON message) and net/rpc (string) when MongoDB fails

Solving the classic problems ​

The failure scenarios a five-service system meets in its first month, and what this project does about each.

ProblemSolutionHowAdvantageCost / limitation
A downstream hangsPer-attempt timeout inside the request budgetresilience.Do + ctxBounded latency, no goroutine pile-upMust pick numbers per hop
A downstream flapsRetry retryable errors with jitterRetryable + full jitterAbsorbs restarts and blipsLoad amplification if every layer retries
A retry duplicates a writeIdempotency key per client requestIdempotency-Key, _id upsert, seen-key setSafe retriesKey storage; per-process for the mailer
A downstream is down for minutesCircuit breakergobreaker, 5 failures, 30 sFast 503, gives it roomA healthy instance behind a bad one is also skipped
The user should not wait for slow workEvent + 202RabbitMQ, listenerDecoupled in timeAt-least-once, eventual consistency
Messages that can never succeedPoison topicPoisonQueueWithFilterQueue keeps flowingSomeone must read the parking queue
Logs cannot be joinedRequest ID + trace context on every hopMiddleware, transport, payload fields, AMQP headersOne search shows the whole requestEvery new transport must carry them
Errors meaningless to the front endOne status mappingresilience.HTTPStatusConsistent client behaviourMapping must be kept complete
Deploys drop requestsGraceful shutdown of all serverslifecycle.RunZero dropped in-flight requestsGrace period lengthens deploys

Broker down (RabbitMQ unavailable) ​

cmd/broker and cmd/listener fail fast at start if RabbitMQ is unreachable (amqpbus.Dial returns the error, main exits 1) and Compose's restart: unless-stopped plus depends_on: rabbitmq: condition: service_healthy brings them back. If the broker starts before the listener has declared its queues, its mandatory publishes come back as ErrUnroutable and it answers 503 rather than 202 for an event nobody will receive. At run time, a failed publish makes only the event path answer 503 "event bus unavailable, retry later" (TestRabbitMQDownOnlyBreaksTheEventPath): login, mail and the REST, net/rpc and gRPC logging paths keep working. If losing a log action is unacceptable, write the event to an outbox table in the same transaction as the business change and publish from a relay (Event-Driven Go, outbox); this project has no business table in the broker, so it answers 503 and lets the client retry with the same Idempotency-Key.

DB down (Postgres or MongoDB unavailable) ​

Postgres down: auth's /readyz turns 503 (Compose marks it unhealthy but does not restart it), Authenticate returns the store error, the handler answers 503 "user store unavailable" without the internal address (TestAuthenticate), the broker retries once and answers 502. Users see "try again later", never "wrong password". MongoDB down: the logger answers 503 on REST, codes.Unavailable on gRPC, an error string on net/rpc; the broker retries (same key) and then answers 502 or 503; on the event path nothing fails for the user, because the listener keeps retrying and nacking, and the queue holds the events until MongoDB is back (TestLoggerDownIsRetried).

Slow mailer ​

The broker's mail hop gives each attempt its own budget and the whole call the request's budget; a mailer that hangs costs at most two attempts, then 504 (TestSlowMailerIsCutAt504: about 80 ms with a 40 ms attempt budget, against 300 ms or forever in the Before broker). Inside the mailer, the real SMTP adapter closes its connection when the broker's ctx ends (go-mail itself bounds only the dial with ctx, see Mailer service): TestSMTPStallIsBoundedByCtx runs go-mail against a fake server that accepts and then never answers after DATA, and the send returns context.DeadlineExceeded at 150 ms instead of after go-mail's 15 s step timeout; the handler maps the deadline to 504 (TestSlowSMTPIsCutByTheCallerDeadline, with a fake sender). Five consecutive failures open the breaker, after which the broker answers 503 without calling (TestMailerDownOpensBreaker). If the business can accept "the email will arrive", the better design is to make mail an event like log: the broker answers 202 and a mail consumer works through a queue at its own pace.

Retry and failure handling ​

ErrorMeaningRetry?
context.DeadlineExceeded from one attemptThat attempt was too slow; outcome unknownYes, with the same key, if the request budget remains
context.CanceledThe client leftNo; excluded from the breaker
net.Error (refused, reset, DNS)Network or process not upYes
rpc.ErrShutdown / io.ErrUnexpectedEOFnet/rpc connection closed (later calls / the pending call)Yes, after redial
502 / 503 / 504 from RESTUpstream overloaded or restartingYes
400 / 401 / 404 / 409 / 422The request is wrongNo
500 from RESTUpstream bugNo (it will fail again)
codes.Unavailable / codes.DeadlineExceededgRPC transientYes
codes.InvalidArgument etc.gRPC caller errorNo
ErrOpenState / ErrTooManyRequestsBreaker refusingNo: answer 503
ErrUnknownVersion in the listenerConsumer cannot handle this eventNo: poison topic

Choosing ​

SituationRecommendationExtra techniqueReason
One team, one product, earlyA monolith with module boundaries (see below)Interfaces between modulesFowler: most successful systems started that way
A part needs independent scaling or deploysExtract it as a service behind the same interfaceContract tests before the moveThe broker cannot tell an in-process adapter from a client
Front end needs one URL and one error formatA broker / API gatewayStatus mapping, request IDsOne place for cross-cutting policy
Answer needed now, internal, typedgRPCDeadlines, status codesContract + speed
Answer needed now, public or polyglotREST/JSONGolden-file contractsUniversal
Only Go, legacynet/rpcWrap with ctx select, redialIt works, but it is frozen
Work the user does not wait forRabbitMQ eventIdempotent consumer, poison topic, publisher confirmsDecoupled in time
Event must never be lost after a DB writeOutbox + relayInbox on the consumerAtomic with the business change
Shared wire typesOne contracts package (one module) or tagged module + go.workGolden JSON, additive changesDrift caught at compile or test time
Local discoveryCompose service namesEnv vars with defaults, dns:/// for gRPCNo registry to run
Health/healthz liveness, /readyz readinessgRPC health for gRPC serversRestarts only when restarting helps
A flaky dependencyBreaker + bounded retriesCount only server-side failuresFail fast, recover automatically
TestsFakes, httptest, bufconn, GoChannel, contract testsA small real-stack suite elsewhereFast, deterministic

In architecture: from a single process to a distributed system ​

Monolith: what a monolith version would look like ​

The monolith version is one binary and one http.Handler: the same broker router in front of the same auth.Service, logger.Service and mailer.Service, wired with in-process adapters (monolith.AuthDirect, LogDirect, MailDirect) that implement the broker's interfaces with plain function calls. There are no JSON hops between services, no per-hop timeouts (the Hop timeouts are 0), no retries, no breaker except around the SMTP server (still remote), no RabbitMQ (an event becomes a call, or a goroutine with WithoutCancel, or an outbox row), one log stream and one deploy. In a monolith with one database, auth and logs could even share a transaction. TestSameRouterNoNetwork runs the same broker router against it: login, wrong password, log and mail all behave the same, validation errors keep the network version's status (an empty log name or an incomplete mail is 422, because the direct adapters map logger.ErrInvalid and mailer.ErrInvalid to the same UpstreamError{Status: 422} the HTTP clients produce), and the audit entry lands in the store. This is also the migration path: start here, keep the interfaces, and replace an adapter with a network client when a service really needs to leave.

go
// Package monolith is what the project looks like as one deployable:
// the same auth, logger and mailer packages, called in-process through
// the same interfaces the broker uses for its network clients. No
// JSON between services, no timeouts per hop, no breaker, no broker
// to lose: an event becomes a function call (or a goroutine/outbox).
package monolith

import (
	"context"
	"errors"
	"log/slog"
	"net/http"

	"academy/microservices-project/auth"
	"academy/microservices-project/broker"
	"academy/microservices-project/contracts"
	"academy/microservices-project/logger"
	"academy/microservices-project/mailer"
	"academy/microservices-project/platform/resilience"
)

// AuthDirect calls the auth service's business method.
type AuthDirect struct{ Svc *auth.Service }

func (a AuthDirect) Authenticate(ctx context.Context, p contracts.AuthPayload) (contracts.AuthUser, error) {
	u, err := a.Svc.Authenticate(ctx, p)
	if errors.Is(err, auth.ErrInvalidCredentials) {
		// Same status mapping as over HTTP, without the HTTP.
		return u, &resilience.UpstreamError{Service: "auth", Status: http.StatusUnauthorized, Message: err.Error()}
	}
	return u, err
}

// LogDirect writes through logger.Service; it also stands in for the
// event path, because in one process "publish" is just "call".
type LogDirect struct{ Svc *logger.Service }

func (l LogDirect) WriteLog(ctx context.Context, key string, p contracts.LogPayload) (string, error) {
	id, err := l.Svc.Write(ctx, key, p)
	return id, invalid(err, logger.ErrInvalid, "logger")
}

func (l LogDirect) PublishLog(ctx context.Context, key, severity string, p contracts.LogPayload) error {
	_, err := l.Svc.Write(ctx, key, p)
	return invalid(err, logger.ErrInvalid, "logger")
}

// invalid keeps the network version's contract: a validation error is
// a 422 from the callee, whatever the transport (here: none).
func invalid(err, sentinel error, service string) error {
	if errors.Is(err, sentinel) {
		return &resilience.UpstreamError{Service: service, Status: http.StatusUnprocessableEntity, Message: err.Error()}
	}
	return err
}

// MailDirect sends through mailer.Service.
type MailDirect struct{ Svc *mailer.Service }

func (m MailDirect) Send(ctx context.Context, key string, p contracts.MailPayload) error {
	_, err := m.Svc.Send(ctx, key, p)
	return invalid(err, mailer.ErrInvalid, "mailer")
}

// New builds the monolith: one http.Handler, one process, the broker's
// router in front of direct calls.
func New(users auth.Store, logs logger.Store, sender mailer.Sender, log *slog.Logger) (http.Handler, error) {
	logSvc := &logger.Service{Store: logs, Log: log}
	authSvc := auth.New(users, LogDirect{Svc: logSvc}.asAudit(), log)
	mailSvc, err := mailer.New(sender, "noreply@example.test", log)
	if err != nil {
		return nil, err
	}
	direct := LogDirect{Svc: logSvc}
	b := &broker.Broker{
		Auth:        AuthDirect{Svc: authSvc},
		Logs:        map[string]broker.LogWriter{contracts.ViaREST: direct, contracts.ViaRPC: direct, contracts.ViaGRPC: direct},
		Events:      direct,
		Mail:        MailDirect{Svc: mailSvc},
		Log:         log,
		AuthHop:     resilience.Hop{Attempts: 1},
		LogHop:      resilience.Hop{Attempts: 1},
		MailHop:     resilience.Hop{Attempts: 1},
		EventHop:    resilience.Hop{Attempts: 1},
		MailBreaker: resilience.NewBreaker("smtp", 5, 0, nil), // the SMTP server is still remote
	}
	return b.Routes(), nil
}

type auditFunc func(ctx context.Context, p contracts.LogPayload) error

func (f auditFunc) Log(ctx context.Context, p contracts.LogPayload) error { return f(ctx, p) }

func (l LogDirect) asAudit() auth.Logger {
	return auditFunc(func(ctx context.Context, p contracts.LogPayload) error {
		_, err := l.Svc.Write(ctx, "", p)
		return err
	})
}
go
package monolith

import (
	"context"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"golang.org/x/crypto/bcrypt"

	"academy/microservices-project/auth"
	"academy/microservices-project/logger"
	"academy/microservices-project/mailer"
)

type nopSender struct{}

func (nopSender) Send(ctx context.Context, m mailer.Rendered) error { return nil }

func TestSameRouterNoNetwork(t *testing.T) {
	hash, _ := bcrypt.GenerateFromPassword([]byte("verysecret"), bcrypt.MinCost)
	logs := &logger.MemoryStore{}
	h, err := New(&auth.MemoryStore{Users: map[string]auth.User{
		"admin@example.test": {ID: 1, Email: "admin@example.test", PasswordHash: hash, Active: true},
	}}, logs, nopSender{}, slog.New(slog.DiscardHandler))
	if err != nil {
		t.Fatal(err)
	}
	for body, want := range map[string]int{
		`{"action":"auth","auth":{"email":"admin@example.test","password":"verysecret"}}`: 202,
		`{"action":"auth","auth":{"email":"admin@example.test","password":"nope"}}`:       401,
		`{"action":"log","log":{"name":"event","data":"d"}}`:                              202,
		`{"action":"mail","mail":{"to":"a@example.test","subject":"s","message":"m"}}`:    202,
		// validation errors keep the network version's status: 422
		`{"action":"log","log":{"name":"","data":"d"}}`:              422,
		`{"action":"mail","mail":{"to":"a@example.test"}}`:           422,
		`{"action":"log","log":{"name":"","data":"d","via":"grpc"}}`: 422,
	} {
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/handle", strings.NewReader(body)))
		if rec.Code != want {
			t.Errorf("%s: %d want %d", body, rec.Code, want)
		}
	}
	// audit entry from the login + the explicit log entry
	if n := len(logs.All()); n != 2 {
		t.Fatalf("entries %d, want 2", n)
	}
}

Modular monolith and multiple databases ​

Between the two: one deployable, but each module owns its own store and talks to the others only through its interface. Auth owns Postgres users, logger owns MongoDB logs; no module reads another's tables. This is the point where the database-per-service rule ("accessible only via its API") is adopted before the network is. Transactions no longer span modules, so the audit log becomes an in-process event (a channel, or a GoChannel Watermill bus with the same listener code) and idempotency keys start to matter. Extracting the logger later is then a deployment change: swap LogDirect for clients.LogREST, add a hop policy, done. Microservices Architecture covers the boundary choices.

Microservices ​

The full project: five deployables, four transports, three stores, one broker. What crosses the boundaries: JSON envelopes and events defined in contracts, the request ID, the trace context, the idempotency key and, for gRPC, the deadline. What does not: transactions (login and audit are separate writes; the audit is best-effort by design), Go error values (each transport flattens them to a status, a code or a string), and the caller's deadline over REST and net/rpc. A multi-service flow with the actual messages: front end POST /handle {"action":"log"} → broker publishes log.info (event r-1, headers X-Request-ID, traceparent) to logs_topic → confirm → 202 → listener receives from listener.logs → POST http://logger-service/log with Idempotency-Key: r-1 → MongoDB upsert _id: r-1 → ack. If the logger is down, nothing in that chain is lost; if the listener crashes after the upsert and before the ack, the redelivery is absorbed by the key. Communication styles in general: Service Communication.

Distributed data: replicas, caches, sharded databases, multi-region ​

Each store scales on its own terms. Postgres for auth can add read replicas, but a login right after a password change must read from the primary or it may accept the old password for the replica lag (read-your-writes). MongoDB for logs is append-mostly and shards well by time or by request ID; the _id upsert stays idempotent on any shard because _id is the shard key or included in it. RabbitMQ becomes a cluster with quorum queues for listener.logs; publisher confirms then mean "a quorum stored it". A cache in front of auth (users by email) must be invalidated on password change, or a breaker-open fallback to the cache would accept stale credentials, which is why this project has no fallback for auth. Across regions, the broker should call services in its own region; events can be replicated (shovel, federation) and the idempotency key makes replays safe. Consensus and replication details: RabbitMQ, Replication & Failover.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesPractice
1× (a few requests per second, one host)Compose on one machine is enough; the monolith would be tooTests, health checks, request IDs, graceful shutdown from day one
10× (several instances behind a load balancer)Broker and logger scale horizontally; DNS returns several IPs; gRPC needs client-side balancing (round_robin) or a proxyBreaker per downstream, retry budgets, readiness probes, prefetch tuned, Postgres pool sized against max_connections
100× (many teams, many services)Compose gives way to Kubernetes; a real gateway (Envoy, Kong) replaces parts of the broker; a service mesh may take over mTLS, retries and some breakingDeadline propagation everywhere (gRPC), tracing sampled at the collector, an outbox for every event that matters, schema registry or buf breaking for contracts, load shedding at the edge (API Gateway, BFF & Service Mesh)

Lab ​

1. Run every test (real) ​

cd docs/snippets/go/microservices-project/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok   academy/microservices-project/allinone            1.965s
# ok   academy/microservices-project/auth                2.863s
# ok   academy/microservices-project/before              1.616s
# ok   academy/microservices-project/broker              1.391s
# ok   academy/microservices-project/clients             1.984s
# ok   academy/microservices-project/contracts           1.493s
# ok   academy/microservices-project/listener            1.355s
# ok   academy/microservices-project/logger              1.600s
# ok   academy/microservices-project/mailer              1.503s
# ok   academy/microservices-project/monolith            1.971s
# ok   academy/microservices-project/platform/health     1.386s
# ok   academy/microservices-project/platform/lifecycle  1.687s
# ok   academy/microservices-project/platform/resilience 1.519s
# ok   academy/microservices-project/platform/web        1.438s
# ?    .../cmd/* , gen/logs/v1, platform/config, tracing  [no test files]

2. Watch one trace per flow (real) ​

go test -race -count=1 -v -run TestEndToEndTracesAndShutdown ./allinone
# (map order: the order of lines varies between runs)
# trace 8e6e744c…: RPCServer.LogInfo | broker-service
# trace 7a9944bc…: broker-service | logs.v1.LogService/WriteLog
# trace 754b102e…: HTTP POST | broker-service | log-event process | log.info publish | logger-service
# trace c0be6e1a…: HTTP POST | broker-service | mailer-service
# trace cf1ecb89…: HTTP POST | authentication-service | broker-service      (wrong password: no audit)
# trace 2311888e…: HTTP POST | authentication-service | broker-service | logger-service
# trace dae6604c…: HTTP POST | broker-service | logger-service
# --- PASS: TestEndToEndTracesAndShutdown (0.53s)

While building, before the broker's net/rpc client was closed during shutdown, this test took 2.59 s instead of about 0.6 s (observed in that session, not kept as a file): the net/rpc server waited the whole 2 s grace for an idle client connection. That is the "no graceful shutdown API" limit of net/rpc, measured.

3. See the net/rpc limits (real) ​

go test -race -count=1 -v -run 'TestNetRPCRegisterDialCall|TestRPCClientRedialsAfterLoggerRestart' ./logger ./clients
# --- PASS: TestNetRPCRegisterDialCall          errors arrive as rpc.ServerError strings;
#                                               the server finishes work after the client's deadline
# --- PASS: TestRPCClientRedialsAfterLoggerRestart   rpc.ErrShutdown -> redial on the next attempt

4. Build all binaries (real) ​

CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o ./bin/ ./cmd/...
# 19912802 authentication
# 16936450 broker
#  5595922 healthcheck
# 15955250 listener
# 18092722 logger
# 14430946 mailer
make -n build      # prints the six go build commands the Makefile runs
buf lint           # (no output: STANDARD rules pass)

5. Validate the Compose file (real, static only) ​

docker compose -f deploy/docker-compose.yml config --services
# rabbitmq
# mailpit
# mailer-service
# postgres
# authentication-service
# mongo
# logger-service
# broker-service
# listener-service

6. The whole stack in Docker Compose (expected, not run) ​

make up                                   # docker compose -f deploy/docker-compose.yml up -d --build
docker compose -f deploy/docker-compose.yml ps
# NAME ...                   STATUS
# broker-service             Up (healthy)   0.0.0.0:8080->80/tcp
# authentication-service     Up (healthy)
# logger-service             Up (healthy)
# ...
curl -s -X POST localhost:8080/handle -H 'X-Request-ID: lab-1' \
  -d '{"action":"log","log":{"name":"event","data":"hello"}}'
# {"error":false,"message":"queued via RabbitMQ"}
docker compose -f deploy/docker-compose.yml stop mailer-service
for i in 1 2 3 4 5 6; do curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8080/handle \
  -d '{"action":"mail","mail":{"to":"a@example.test","subject":"s","message":"m"}}'; done
# 502 502 503 503 503 503      (each request makes up to 2 attempts; the 5th failed attempt,
#                               in request 3, opens the breaker; later ones are refused at once)
docker compose -f deploy/docker-compose.yml logs broker-service | grep lab-1
# expected: the broker's success line for that publish, the same shape as this REAL line
# from `go test -v -run TestSuccessIsLoggedWithRequestID ./broker` (request id r-1 there):
# {"time":"2026-11-29T01:09:36.666576+03:30","level":"INFO","msg":"event published","routing_key":"log.info","event_id":"r-1","service":"broker-service","request_id":"r-1"}
# Mailpit UI: http://localhost:8025 shows mails sent while the mailer was up

For PHP/Laravel developers ​

A Laravel team usually builds this system as one application, and that is the Laravel equivalent of the monolith version: controllers instead of the broker, Eloquent on Postgres for users, a log channel (or a logs table or MongoDB package) for the logger, Mail::to(...)->send(new Welcome) with Blade templates for the mailer, and queued jobs instead of RabbitMQ events. Laravel 13's docs: "Laravel queues provide a unified queueing API across a variety of different queue backends, such as Amazon SQS, Redis, or even a relational database", and the listener's role is played by php artisan queue:work. Horizon "provides a beautiful dashboard and code-driven configuration for your Laravel powered Redis queues", which is roughly what the RabbitMQ management UI plus your own metrics give the Go listener. Octane "supercharges your application's performance by serving your application using high-powered application servers, including FrankenPHP, Open Swoole, Swoole, and RoadRunner"; it boots the application once and keeps it in memory, like a Go service, so the same care about shared state and graceful restarts applies. When a Laravel application does call other services, the HTTP client covers timeouts and retries ("The retry method accepts the maximum number of times the request should be attempted and the number of milliseconds that Laravel should wait in between attempts"), but there is no shared deadline, no built-in breaker and no request-ID propagation; those are written by hand, exactly as in this project.

php
// Laravel: the broker's three actions in one controller (comparison only)
$ok = Auth::attempt($request->only('email', 'password'));              // auth, in-process
LogEntry::dispatch($request->input('log'))->onQueue('logs');           // event: a queued job, Redis/SQS/DB
$response = Http::timeout(3)->retry(2, 100)
    ->withHeaders(['Idempotency-Key' => $key, 'X-Request-ID' => $rid])
    ->post('http://mailer-service/send', $request->input('mail'));     // a real remote call: manual policy
LaravelThis Go project
Controller + routesBroker JSON action router
Auth::attempt, Hash::check (Bcrypt in the starter kits)auth service, bcrypt.CompareHashAndPassword
Log channel / logs tablelogger service, MongoDB
Mail + Mailable + Blademailer service, html/template + go-mail
Queued job + queue:workRabbitMQ event + listener service
Horizon dashboard, failed jobs tableRabbitMQ UI, poison topic, traces
Octane (long-lived workers)Every Go service is long-lived by default
Http::timeout()->retry()resilience.Do with a Hop
ShouldBeUnique, idempotent jobsIdempotency keys, _id upsert
Laravel Context (request data into logs and jobs)Request ID in ctx, slog handler, message headers

Common misconceptions ​

BeliefReality
Microservices are more reliable by defaultEach hop is a new failure mode; reliability comes from timeouts, retries with keys, breakers and queues
The broker is just a proxyIt owns the action contract, the per-hop policy and the status mapping
http.Client{} has a sensible timeoutZero value: none. Use a ctx deadline per attempt
net/rpc is a small gRPCFrozen, Go-only (gob), no context, errors as strings, no shutdown API
gRPC sets a default deadline"By default, gRPC does not set a deadline"; the client must
Publish returned, so the event is storedOnly with confirms and mandatory: RabbitMQ confirms unroutable messages too; and still not processed
RabbitMQ delivers exactly onceAt least once; idempotent consumers make duplicates harmless
depends_on waits for readinessOnly with condition: service_healthy, and services must still retry
Liveness should check the databaseThat restarts healthy processes in a loop; readiness checks dependencies
Server.Shutdown stops gRPC and net/rpc tooEach server type needs its own graceful stop, driven by one root ctx
Retrying makes a call safeOnly if the call is idempotent or carries an idempotency key
Every error should trip the breaker4xx and client cancellations say nothing about the callee's health
Pass downstream statuses through4xx yes; 5xx become 502/503/504 without internal details
A shared contracts package couples servicesIt makes the existing wire coupling visible and compiler-checked
Fakes cannot catch real bugsThey catch logic and contract bugs; adapters against real servers need a separate suite
GoChannel is an in-memory RabbitMQNo wildcard routing, no durability, no redelivery after a crash

Cheat sheet ​

TopicRemember
Front doorBroker = one URL, one envelope {action, ...}, one error format
Transport choiceNeed the answer now: REST or gRPC. Do not need it now: event + 202
REST between servicesNewRequestWithContext, typed UpstreamError, 1 MiB limit, shared envelope
net/rpcRegister, Dial, Call/Go; gob; frozen; no ctx; errors are strings; ErrShutdown → redial
gRPC.proto → buf generate; NewClient("dns:///host:port"); always set a deadline; codes.*
RabbitMQTopic exchange logs_topic, key log.<sev>, binding log.*; confirms + mandatory + NotifyReturn; owner declares queues at startup; poison queue bound to a key outside log.*
ContractsOne contracts package or tagged module + go.work; golden JSON; additive only; version events
DiscoveryCompose service names are DNS names; env vars with those defaults
Health/healthz = alive, /readyz = dependencies; distroless needs a healthcheck binary
Shutdownsignal.NotifyContext → lifecycle.Run → Shutdown/GracefulStop/close in parallel within grace
Request IDsMiddleware → ctx → header/field/AMQP header → slog handler request_id
Per hopAttempt timeout inside the request budget; retry only retryable errors; jitter; same key
Breakergobreaker v2: NewCircuitBreaker[T], Execute; count only server-side failures; open → 503
Status mapping4xx pass through; 5xx → 502; timeout → 504; open breaker or bus down → 503
Testshttptest, bufconn, GoChannel, contract tests, one in-process end-to-end; no Docker
Tracingotelhttp, otelgrpc, traceparent in AMQP headers, manual for net/rpc

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does the front end talk only to the broker, and what does the broker own besides routing? Must-know ​

Answer

Answer: One public URL and one error format keep internal hostnames and transports private and let them change. The broker owns the action contract and its validation, the per-hop policy (timeout, retries, breaker), the idempotency key per client request, request-ID creation, and the mapping of every downstream failure to one HTTP status. See Broker service.

2 — A user types the wrong password while Postgres is also down for another user. What does each see, and why must the two differ? Must-know ​

Answer

Answer: Wrong password: auth answers 401 "invalid credentials" and the broker passes it through. Postgres down: auth answers 503 without internal details, the broker retries once and answers 502. If both were the same status, users would be told their password is wrong during an outage, or retry a login that will never succeed.

3 — Name four limits of net/rpc that this project works around, and how. Must-know ​

Answer

Answer: No context on Call (the client selects on call.Done and ctx.Done(), the server sets its own 2 s); errors arrive as strings (the server sends only two fixed texts, which the client maps to 422 or a retryable 503); no metadata (request ID and trace context travel as fields of RPCPayload); no shutdown API (lifecycle.RPC closes the listener and tracked connections, and clients hang up). Also: it is frozen and Go-only because of gob.

4 — What happens if the broker calls the gRPC logger without a deadline and the logger hangs? Must-know ​

Answer

Answer: gRPC sets no default deadline, so the call waits forever and the broker's goroutine, connection and request are stuck with it. With a ctx deadline the client sends grpc-timeout, the server's ctx expires too, and the client gets codes.DeadlineExceeded, which the broker may retry within its budget and finally maps to 504.

5 — The listener writes a log entry, then crashes before acking. What happens next, and why is the result still one entry? Must-know ​

Answer

Answer: RabbitMQ redelivers the unacked message to the next consumer (at-least-once). The listener calls the logger with the event ID as Idempotency-Key; the logger uses it as _id with an upsert ($setOnInsert), so the second write matches the existing document and stores nothing.

6 — Why is the poison routing key poison.log and not log.poison in this topology? Important ​

Answer

Answer: The listener's queue is bound to logs_topic with log.*, and * matches exactly one word, so log.poison would be routed back into the listener's own queue and loop. poison.log does not match log.*; the listener declares listener.poison bound to it at startup, and publishes poison with mandatory so a missing binding is an error rather than a confirmed, dropped message.

7 — In what order are the Watermill Retry and PoisonQueueWithFilter middlewares added, and what goes wrong with the other order? Important ​

Answer

Answer: Retry first, then the filtered poison middleware. Watermill runs the middleware added first outermost, so the poison filter sees the handler's error first: an unknown version is parked at once and Retry sees success. In the other order an unknown version would be retried MaxRetries times with backoff before being parked; the listener test with a 200 ms backoff catches that.

8 — Why do 401 and 422 count as successes for the mailer's circuit breaker, and why is context.Canceled excluded? Important ​

Answer

Answer: A breaker measures the callee's health. A 4xx means the callee worked and the caller was wrong; counting it would let one bad client open the breaker for everyone. context.Canceled means the client gave up, which says nothing about the mailer, so IsExcluded drops it from the counts.

9 — How does one request ID reach a MongoDB document written by the listener minutes later? Important ​

Answer

Answer: The broker's middleware puts it in ctx; clients.Events copies it into the event (request_id) and the AMQP header X-Request-ID; the listener puts it back into ctx; PropagatingTransport sends it as X-Request-ID to the logger; the logger's middleware puts it in ctx and Service.Write stores it in the document. Every service's slog handler logs it as request_id.

10 — The logger runs HTTP, net/rpc and gRPC in one process. What does a correct SIGTERM look like? Important ​

Answer

Answer: signal.NotifyContext cancels the root ctx; lifecycle.Run calls in parallel http.Server.Shutdown (stop accepting, wait for active requests), grpc.Server.GracefulStop (falling back to Stop at the grace limit) and the net/rpc adapter's close-listener-then-wait; all within a grace shorter than Compose's stop_grace_period. If any server fails on its own, the others are stopped too.

11 — One contracts package, a tagged module with go.work, or duplicated structs: how do you choose? Good to know ​

Answer

Answer: One team and one repo: a package in one module, checked by the compiler and golden JSON tests. Several teams in one repo with separate releases: contracts as its own module, go.work for local development, tagged versions in CI. Strict autonomy or polyglot services: duplication or generated types, with contract tests against the provider. In every case: additive changes only and versioned events.

12 — What does the all-in-one test prove that unit tests per service cannot, and what does it still not prove? Good to know ​

Answer

Answer: It proves the real transports work together on loopback (HTTP, net/rpc, gRPC), that request IDs and trace context cross every hop including the event path, and that all servers shut down together. It does not prove the Postgres SQL, the MongoDB upsert, the RabbitMQ topology or a real SMTP provider, which need a suite against real servers (Compose or testcontainers).

13 — Sketch the monolith version of this project. What disappears and what stays? Good to know ​

Answer

Answer: One binary: the same broker router in front of the same service cores, wired with in-process adapters. Gone: JSON hops, per-hop timeouts and retries, breakers between services, RabbitMQ (an event becomes a call or a background job), five deploys. Stays: the interfaces, validation, the status mapping, request IDs and the remote SMTP call with its own breaker. TestSameRouterNoNetwork runs it.

Glossary ​

TermMeaning
Broker serviceThe project's front door: one HTTP endpoint that routes JSON actions to the other services
Front doorThe single public entry point of a system; here the broker, in general an API gateway
JSON action routerDispatch on the action field of one JSON envelope (auth, log, mail)
API gatewayPattern: "the single entry point for all clients" (microservices.io)
Authentication serviceService that owns users and checks passwords
PostgresPostgreSQL, the relational store owned by the authentication service
bcryptAdaptive password hash; golang.org/x/crypto/bcrypt, cost 10 by default
Logger serviceService that stores log entries; reachable over REST, net/rpc and gRPC
MongoDBDocument store owned by the logger service
Mailer serviceService that renders templates and sends mail over SMTP
SMTPMail transfer protocol; Mailpit in development, a provider in production
go-mail / gomailgithub.com/wneessen/go-mail (maintained, ctx-aware) / gopkg.in/gomail.v2 (older)
Templateshtml/template (escaped HTML part) and text/template (plain part)
Listener serviceRabbitMQ consumer that turns events into logger calls
RabbitMQ consumerProcess that receives messages from a queue and acks or nacks them
Communication stylesREST/JSON, RPC (net/rpc), gRPC, and asynchronous events
REST/JSON between servicesHTTP requests with JSON bodies between internal services
net/rpcFrozen standard-library RPC package: Register, Dial, Call, gob encoding
gobGo's own binary encoding, used by net/rpc by default
Registerrpc.Server.Register: exposes an object's eligible methods as Type.Method
Dialrpc.Dial: connect to an RPC server and return a *rpc.Client
Callrpc.Client.Call: synchronous remote call, no context
rpc.ServerErrorString type a net/rpc client receives for a server method's error
rpc.ErrShutdownconnection is shut down: the client's connection is gone
gRPCRPC framework over HTTP/2 with protobuf contracts, deadlines and status codes
proto.proto file: the gRPC service and message contract
codegenGenerating Go types and client/server stubs from the proto (buf generate)
client/serverThe generated LogServiceClient and the LogServiceServer interface
DeadlinesAbsolute time a call must finish by; gRPC sends it as grpc-timeout
bufconnIn-memory listener from grpc-go for testing without a network
RabbitMQ eventsMessages that state something happened, published to an exchange
ExchangeRabbitMQ router; a topic exchange matches routing keys against binding patterns
Routing keysDot-separated words on a message (log.info); * one word, # zero or more in bindings
Publisher confirmsRabbitMQ extension: the broker acks each published message once it has taken care of it (unroutable ones too)
Mandatory flagPublish option: an unroutable message is sent back with basic.return before the ack
PrefetchMax unacked messages delivered to one consumer (basic.qos)
Poison queueDestination for messages that can never be processed
Sync vs asyncWhether the caller waits for the work to finish
Request/reply vs eventAsking a specific service for an answer vs announcing a fact to whoever listens
Service contractsThe wire formats services agree on: JSON shapes, events, headers, protos
Shared typesOne Go package of wire types imported by every service
go.workGo 1.18+ workspace file listing several modules developed together
DuplicationEach service keeps its own copy of the wire structs
Service discoveryHow a client finds a service's address; here Compose DNS names
DNS names in Docker ComposeEach service is "discoverable by its service name" on the default network
Health checks/healthz (liveness) and /readyz (readiness) endpoints, and Compose healthchecks
Graceful shutdownStop accepting, finish in-flight work, exit within a grace period
Structured loggingJSON log records with fields, via log/slog
Request IDsOne identifier per client request, carried on every hop and in every log line
PropagationCarrying request ID, trace context and deadline from one hop to the next
Timeouts and retries per hopA budget and retry policy chosen for each downstream separately
IdempotencyDoing a request twice has the effect of doing it once; via an idempotency key
Idempotency keyClient-chosen ID that lets a server recognise a repeated request
Circuit breakerStops calling a failing dependency for a while, then probes
sony/gobreakerGo circuit breaker library; v2 is generic (CircuitBreaker[T])
Error propagationHow a downstream error travels back: status, code, string
Status mappingTurning any downstream error into one HTTP status for the client
Testing strategyUnit per service, transport tests, contract tests, one in-process end-to-end test
Contract testsA client tested against the provider's real handler or golden files
httptest/bufconn/GoChannel fakesIn-process HTTP servers, gRPC listeners and Watermill pub/sub for tests
Makefile multi-binary buildOne Makefile building every cmd/<service> binary
DockerfilesMulti-stage build to a distroless image, one per service via ARG SERVICE
Compose topologyThe services, stores, networks and start order in docker-compose.yml
ObservabilityLogs, metrics and traces that explain the running system
OpenTelemetry tracesSpans linked by trace context across REST, gRPC and AMQP
traceparentW3C Trace Context header carrying trace ID, parent span ID and flags
Failure scenariosBroker down, DB down, slow mailer and the like, with the designed response
Monolith versionThe same cores and router in one process, wired with in-process adapters
DistrolessMinimal base image with no shell or package manager
Laravel equivalentOne Laravel app: controllers, Eloquent, Mail, queued jobs
QueuesLaravel's unified queueing API over Redis, SQS or a database
OctaneLaravel package serving the app from long-lived workers (FrankenPHP, Swoole, RoadRunner)
HorizonDashboard and code-driven configuration for Laravel's Redis queues

References ​

Built by Morteza Negahi