Security in Go from cryptography to the supply chain: using AES-GCM and Argon2id from the crypto packages correctly, signing, verifying, and rotating JWTs with golang-jwt/v5, OAuth2/OIDC flows with golang.org/x/oauth2 and go-oidc including PKCE, secrets management with Vault and SOPS beyond the env-var pitfalls — and the supply chain locked down with govulncheck, GOPRIVATE, and SBOMs.
After the restructuring from module 15, the Bookstore-API runs as a solid monolith — and that monolith is about to become a victim of its own success: the payments team wants to deploy independently, the catalog needs its own scaling for price search, and every release of the inventory system blocks the others. The plan: three services — catalog, orders, shipping — talking to each other internally. For that internal communication the teams choose gRPC: contracts in Protobuf, binary transport over HTTP/2, codegen for Go — no JSON negotiation, no hand-written client.
The core is the contract: a .proto file defines messages (data structures with numbered fields) and services (RPC methods). From it, protoc with the official plugins protoc-gen-go (google.golang.org/protobuf) and protoc-gen-go-grpc (google.golang.org/grpc) generates server interfaces and client stubs — both sides compile against the same types, and a contract break shows up at build time, not in production.
// api/proto/bookstore/v1/catalog.proto — the contract comes first, the code follows
syntax = "proto3";
package bookstore.v1;
option go_package = "bookstore/gen/catalog/v1;catalogv1";
message Book {
string isbn = 1; // field numbers ARE the wire contract — names are decoration
string title = 2;
string author = 3;
int32 price_cents = 4; // cents as int32, matching the database (module 12)
int32 stock = 5;
}
message GetBookRequest {
string isbn = 1;
}
service CatalogService {
rpc GetBook(GetBookRequest) returns (Book);
}
The codegen line is procedural, but it belongs in the build (Makefile or go:generate) — generated files are never committed and then "maintained" by hand:
# Codegen: protoc plus the two official Go plugins
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
protoc --proto_path=api/proto \
--go_out=gen --go_opt=module=bookstore \
--go-grpc_out=gen --go-grpc_opt=module=bookstore \
api/proto/bookstore/v1/catalog.proto
# → gen/catalog/v1/catalog.pb.go (messages: Book, GetBookRequest)
# → gen/catalog/v1/catalog_grpc.pb.go (server interface + client stub)
The catalog server implements the generated interface — embedding UnimplementedCatalogServiceServer is intentional and not a boilerplate curse: new RPCs in the contract do not break the build of old servers until someone actually implements the method.
// internal/catalog/grpc.go — server: fulfilling the generated contract
package catalog
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
catalogv1 "bookstore/gen/catalog/v1"
)
type Server struct {
catalogv1.UnimplementedCatalogServiceServer
store BookStore // domain interface from module 15 — the contract knows no SQL
}
func (s *Server) GetBook(ctx context.Context, req *catalogv1.GetBookRequest) (*catalogv1.Book, error) {
b, err := s.store.ByISBN(ctx, req.GetIsbn())
if err != nil {
return nil, status.Errorf(codes.NotFound, "isbn %q unknown", req.GetIsbn())
}
return &catalogv1.Book{
Isbn: b.Isbn,
Title: b.Title,
PriceCents: int32(b.PriceCents),
Stock: int32(b.Stock),
}, nil
}
// cmd/catalog/main.go — wiring: listener, registration, serve
func main() {
lis, err := net.Listen("tcp", ":9090")
if err != nil {
log.Fatal(err)
}
srv := grpc.NewServer()
catalogv1.RegisterCatalogServiceServer(srv, catalog.NewServer(queries))
log.Println("gRPC listening on", lis.Addr())
log.Fatal(srv.Serve(lis))
}
// Terminal: grpcurl -plaintext -d '{"isbn":"978-3-423-2089-8"}' localhost:9090 bookstore.v1.CatalogService/GetBook
// → {"author":"Paulo Coelho","isbn":"978-3-423-2089-8","priceCents":1295,"stock":3,"title":"Der Alchimist"}
The order side calls the catalog through the generated stub — since grpc-go v1.63, grpc.NewClient is the right constructor; grpc.Dial is deprecated:
// internal/orders/catalogclient.go — client: stub over a connection, deadline included
func NewCatalogClient(addr string) (catalogv1.CatalogServiceClient, func(), error) {
conn, err := grpc.NewClient(addr,
grpc.WithTransportCredentials(insecure.NewCredentials())) // only behind the network perimeter — lesson 78
if err != nil {
return nil, nil, err
}
return catalogv1.NewCatalogServiceClient(conn), func() { _ = conn.Close() }, nil
}
func (s *Service) PriceFor(ctx context.Context, isbn string) (int32, error) {
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer cancel()
b, err := s.catalog.GetBook(ctx, &catalogv1.GetBookRequest{Isbn: isbn})
if err != nil {
return 0, err // codes.DeadlineExceeded, codes.NotFound, codes.Unavailable — lesson 78
}
return b.PriceCents, nil
}
// Terminal: price query against a healthy catalog
// → err == nil, priceCents == 1295 — the RPC answers within a few milliseconds
//
// Terminal: catalog instance crashed
// → err: rpc error: code = Unavailable ... — grpc retries transparently without a connection (wait-for-ready is separate)
Field Numbers Are the Contract — Field Names Are Not
Protobuf does not serialize names, it serializes numbers: on the wire it says "field 4 has value 1295", not "price_cents". A rename is therefore harmless afterwards (all sides translate the same number into their own name), while reusing a number for a different type produces silent data corruption. That is why every well-kept .proto file ends with a comment: never reuse numbers, seal removed fields with reserved.
⚠ Common mistake: Removing a field from the Protobuf and later reusing its number for something new. Old clients still compiled against the old contract decode the new bytes silently into the old type:
stock int32 = 5suddenly becomesdiscount_percent int32 = 5— no error, no log — and the inventory service reserves goods using "discount 3" as the quantity. Removed fields belong inreserved 5; reserved "stock";so the compiler rejects any reuse at compile time.
Check: The team renames the field price_cents to price_minor_units in the Protobuf (same number 4, same type). What happens to clients compiled against the old contract?
Answer: Nothing — numbers travel on the wire, not names; the rename is fully compatible
The most common misconception is treating Protobuf like JSON with field names. In reality the wire codec serializes (tag, wire type, value) — names exist only inside each side's generated code. The dangerous move is the opposite: changing or reusing numbers, because the number is a field's identity on the wire. That is why contracts evolve additively: a new field gets a new number, an old field gets reserved.
Takeaways:
protoc with protoc-gen-go and protoc-gen-go-grpc generates types, server interface, and client stub — contract breaks surface at build time.UnimplementedCatalogServiceServer: new RPCs in the contract do not force-break running services.status with codes (codes.NotFound instead of generic errors) — the client distinguishes transient from permanent with status.Code(err).reserved.Single prices from the catalog are fine — but the stockroom of "Kant & Curves" is alive: inventory changes by the second, the frontend wants live updates, and importing 40,000 titles from the distributor CSV should not push through the wire as one 60-MB request. gRPC has streaming for exactly these three shapes: server streaming (one question, many answers), client streaming (many messages in, one summary out), and bidirectional (both sides send whenever they like). Under the hood it stays HTTP/2 — one call, one stream, frames in both directions.
Streaming Is Not a Channel Swap, It Is a Contract With an End Signal
Each streaming direction means a different interface in the generated code — and each side needs a defined end. Server streams end when the handler returns; clients recognize that by io.EOF from Recv. Client streams end with CloseSend plus one Recv for the single response. Handle the end signal and you have no hanging goroutines; treat it as an error and you build a retry loop around a perfectly normal ending.
First the contract — three methods, three directions:
// api/proto/bookstore/v1/inventory.proto — streaming in the contract
syntax = "proto3";
package bookstore.v1;
option go_package = "bookstore/gen/inventory/v1;inventoryv1";
import "google/protobuf/timestamp.proto";
message StockUpdate {
string isbn = 1;
int32 stock = 2;
google.protobuf.Timestamp as_of = 3;
}
message NewBook {
string isbn = 1;
string title = 2;
int32 price_cents = 3;
}
message ImportSummary {
int32 imported = 1;
int32 rejected = 2;
}
message GetBookRequest {
string isbn = 1;
}
service InventoryService {
rpc WatchStock(GetBookRequest) returns (stream StockUpdate); // server streaming
rpc BulkImport(stream NewBook) returns (ImportSummary); // client streaming
rpc LiveInventory(stream GetBookRequest) returns (stream Book); // bidirectional
}
Server streaming — the handler holds the call open and sends until the subscription ends or the client disappears:
// internal/inventory/grpc.go — server streaming: Send in a loop, end via return
func (s *Server) WatchStock(req *inventoryv1.GetBookRequest, stream inventoryv1.InventoryService_WatchStockServer) error {
events := s.stock.Subscribe(req.GetIsbn()) // channel from the stock pub/sub
defer s.stock.Unsubscribe(events)
for u := range events {
if err := stream.Send(&inventoryv1.StockUpdate{
Isbn: u.Isbn,
Stock: int32(u.Stock),
AsOf: timestamppb.New(u.At),
}); err != nil {
return err // client gone (context canceled) — Send reports that as an error
}
}
return nil // subscription closed: stream ends cleanly, the client sees io.EOF
}
// Terminal: stock changes twice, then the stockroom closes
// → {"isbn":"978-3-423-2089-8","stock":4,"asOf":"2026-11-07T14:02:11Z"}
// → {"isbn":"978-3-423-2089-8","stock":3,"asOf":"2026-11-07T14:02:44Z"}
// → (stream end)
On the client side the loop is the pattern — and the end signal is the trap:
// internal/dashboard/stockwatch.go — client: Recv loop with io.EOF as the normal ending
func WatchISBN(ctx context.Context, inv inventoryv1.InventoryServiceClient, isbn string) error {
stream, err := inv.WatchStock(ctx, &inventoryv1.GetBookRequest{Isbn: isbn})
if err != nil {
return err
}
for {
u, err := stream.Recv()
switch {
case errors.Is(err, io.EOF):
return nil // clean stream end — NOT an error, no retry
case err != nil:
return err // connection or server failure — retry/backoff belongs here
}
apply(u) // update UI or cache
}
}
// Terminal: 2 updates received, then the server ends the stream
// → stock updated: 4
// → stock updated: 3
// → WatchISBN returns nil — the loop never fell into the error handling
Bidirectional — sending and receiving run in parallel, each direction with its own end:
// internal/inventory/live.go — bidi: Send in a goroutine, CloseSend closes one direction
func (c *Client) LiveInventory(ctx context.Context, isbns []string) ([]*inventoryv1.Book, error) {
stream, err := c.stub.LiveInventory(ctx)
if err != nil {
return nil, err
}
go func() {
defer stream.CloseSend() // this half closes: the server knows no more ISBNs are coming
for _, isbn := range isbns {
if err := stream.Send(&inventoryv1.GetBookRequest{Isbn: isbn}); err != nil {
return
}
}
}()
var books []*inventoryv1.Book
for {
b, err := stream.Recv()
if errors.Is(err, io.EOF) {
return books, nil
}
if err != nil {
return nil, err
}
books = append(books, b)
}
}
// Terminal: pushing 40,000 import titles as client streaming
// → sent 40000 records, stream open — memory flat, because records go out in batches
// → summary: {"imported":39412,"rejected":588} — ONE answer at the end
⚠ Common mistake: Treating
io.EOFfromstream.Recv()as a real error — logging an alarm or returning a 500 to the user for it. EOF here is the agreed end signal: the server finished the stream properly (its handler returnednil). The typical consequence of the mix-up: a client that alarms after every clean stream end, or worse — a retry that restarts the same streaming call endlessly. Check EOF first (errors.Is(err, io.EOF)) and return normally; handle all remaining errors after that.
Check: A server-streaming call ends properly. What does stream.Recv() return last on the client side?
Answer: io.EOF as an error value — that is the agreed signal for a clean stream end
The common misconception: EOF must mean something broke, because it comes from the io package. In gRPC, io.EOF is the official code for 'the server ended the stream cleanly' — real connection or server failures arrive as status errors with codes.Unavailable and friends. The pattern is therefore always: check io.EOF first and exit normally, then handle the remaining errors. On bidirectional streams, CloseSend closes only the send half — Recv keeps running afterwards.
Takeaways:
returns (stream …)), client streaming (stream … as parameter), bidirectional (both) — all over one HTTP/2 call.return; clients recognize a clean end by io.EOF from Recv — EOF first, errors after.CloseSend ends only your own direction, Recv keeps going.Send error almost always means the client is gone (context canceled) — the handler cleans up and returns.Three services now speak Protobuf to each other. What worked in the demo raises the right questions in production: every internal call needs authentication (not every service may trigger payments), structured logging with metadata (which call took how long?), and above all an end: if the catalog hangs, the order service must not wait forever — and the catalog itself must not wait longer on its database than the client lent it time for. That is where interceptors, deadline propagation, and (m)TLS come in.
The deadline is not a Go detail, it is architecture: timeouts that travel from the client across every hop are the prerequisite for retry budgets and circuit breaking — the resilience module of the architecture course treats the chain of deadlines, retries with jitter, and bulkheads as a system. Here we build the Go side of it.
Interceptors Are the Middleware of RPC — the Onion Still Applies
An interceptor is exactly one function wrapped around every RPC handler: (ctx, req, info, handler) (any, error). Stacked with ChainUnaryInterceptor, you get the same onion as module 12: recovery outermost, then logging, then auth, then the handler. The difference to the HTTP middleware stack: the context automatically carries the caller's deadline — if the client reserved 2 seconds, the server handler sees the same context with the same remaining 300 milliseconds.
The logging interceptor — structure like slog from module 13, method and duration as fields:
// internal/interceptors/logging.go — one interceptor = one function around every RPC
package interceptors
import (
"context"
"log/slog"
"time"
"google.golang.org/grpc"
)
func Logging(logger *slog.Logger) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (any, error) {
start := time.Now()
resp, err := handler(ctx, req) // call the rest of the chain
logger.Info("rpc",
"method", info.FullMethod,
"err", err,
"dur_ms", time.Since(start).Milliseconds(),
)
return resp, err
}
}
Auth from metadata — gRPC headers are called metadata here and travel in the context:
// internal/interceptors/auth.go — validate the token from metadata, before the handler
func Auth(valid TokenValidator) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler) (any, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok || len(md.Get("authorization")) == 0 {
return nil, status.Error(codes.Unauthenticated, "Bearer token required")
}
token := strings.TrimPrefix(md.Get("authorization")[0], "Bearer ")
claims, err := valid.Parse(ctx, token) // e.g. github.com/golang-jwt/jwt/v5
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "invalid token: %v", err)
}
return handler(context.WithValue(ctx, claimsKey{}, claims), req)
}
}
// Client side: send metadata along
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+token)
// Terminal: call without a token
// → rpc error: code = Unauthenticated desc = Bearer token required
//
// Terminal: valid call
// → {"level":"INFO","msg":"rpc","method":"/bookstore.v1.CatalogService/GetBook","dur_ms":4}
Deadline propagation — the client lends a budget to the whole call path, and every server inherits the remaining time:
// internal/orders/service.go — client reserves 2 s for the entire path
ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
book, err := s.catalog.GetBook(ctx, req) // grpc sends the deadline as a grpc-timeout header
// internal/catalog/grpc.go — the server inherits the remaining time for its sub-calls
func (s *Server) GetBook(ctx context.Context, req *catalogv1.GetBookRequest) (*catalogv1.Book, error) {
ctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond) // sub-budget from the inherited context
defer cancel()
b, err := s.store.ByISBN(ctx, req.GetIsbn()) // the same deadline reaches the DB
...
}
// Terminal: catalog DB hangs, client waits with a 2 s budget
// → client: rpc error: code = DeadlineExceeded desc = context deadline exceeded (after 2.0 s)
// → server log: {"method":"/bookstore.v1.CatalogService/GetBook","err":"context deadline exceeded"}
On transport: TLS between internal services is standard, not garnish — and with client certificates (mTLS) both sides authenticate each other, which mesh-style operations demand anyway:
// internal/transport/mtls.go — mTLS: the server requires and verifies client certificates
func ServerCreds() (credentials.TransportCredentials, error) {
cert, err := tls.LoadX509KeyPair("certs/catalog.crt", "certs/catalog.key")
if err != nil {
return nil, err
}
caPEM, err := os.ReadFile("certs/internal-ca.crt")
if err != nil {
return nil, err
}
ca := x509.NewCertPool()
if !ca.AppendCertsFromPEM(caPEM) {
return nil, errors.New("CA pool unreadable")
}
return credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: ca,
ClientAuth: tls.RequireAndVerifyClientCert, // the M in mTLS
MinVersion: tls.VersionTLS13,
}), nil
}
// srv := grpc.NewServer(grpc.Creds(creds))
// Client: grpc.WithTransportCredentials(clientTLS) — with the order service's own certificate
// Terminal: grpcurl -insecure localhost:9090 list (without a client certificate)
// → rpc error: code = Unavailable ... TLS handshake failed: bad certificate
⚠ Common mistake: Firing internal gRPC calls with no deadline at all — because "internal networks are fast". In reality a call without a deadline waits forever: if the DB behind the catalog hangs, hanging handlers and their goroutines pile up in the order service, the connection pool fills, and one slow catalog becomes a full shop outage. A client context without a timeout also propagates no grpc-timeout to the server — the server cannot know how long it may take. Every outgoing call gets a budget (
context.WithTimeout), and server services slice that budget for their own sub-calls.
Check: The order service calls the catalog with a 2-second context; the catalog handler passes the same context to its DB query. The DB query takes 5 seconds. What happens?
Answer: The grpc-timeout header transports the deadline; the server context cancels after 2 s and the DB query is aborted
Deadline propagation is built into grpc-go: the client sets the deadline, gRPC transmits it as a grpc-timeout header, and the server restores it in the handler context. Because the context is the parent of all sub-calls, the DB query (via pgx) aborts with context deadline exceeded — 3 seconds before the client gives up. That chain is exactly the prerequisite for sensible retry strategies; how budgets, retries, and bulkheads interact is covered by the architecture course's resilience module.
Takeaways:
(ctx, req, info, handler) functions, stacked with ChainUnaryInterceptor — the same onion order as HTTP middleware: recovery outermost, logging, then auth.metadata.FromIncomingContext on the server, AppendToOutgoingContext on the client.context.WithTimeout on the client is transmitted as grpc-timeout and inherited by the server — sub-calls abort before the client gives up.credentials.NewTLS with RequireAndVerifyClientCert authenticates services to each other — insecure.NewCredentials() only behind the test perimeter.gRPC is synchronous: the order service asks, the catalog answers. But the shop also wants the world to learn about events as they happen: OrderPlaced, StockChanged, ShipmentDispatched. Several services should react — invoicing, analytics, shipping — without the buyer waiting on them. That is messaging. The two real Go options with their exact paths: NATS (github.com/nats-io/nats.go including the jetstream sub-package) and Kafka with franz-go (github.com/twmb/franz-go) or sarama (github.com/IBM/sarama).
The Delivery Guarantee Decides, Not the Broker's Reputation
NATS Core is at-most-once (fire and forget), NATS JetStream makes it at-least-once with persisted streams and explicit acks; Kafka is from the ground up a persistent, partitioned log with consumer groups and offsets. Both deliver at least once on failure — and that forces every consumer to be idempotent, because duplicates are normal, not exceptional. The broker purchase does not decide correctness; the consumer's ack and retry behavior does.
The comparison for "Kant & Curves":
| NATS (+ JetStream) | Kafka (franz-go / sarama) | |
|---|---|---|
| Model | Subjects (bookstore.orders.>), streams | Topics, partitioned logs |
| Persistence | Core: none; JetStream: file/memory | always a log on disk |
| Guarantee | Core: at-most-once; JetStream: at-least-once | at-least-once (consumer offsets) |
| Ordering | per subject per consumer | guaranteed per partition |
| Scaling | queue consumers, lightweight | consumer groups, partition bound |
| Operations | one small binary | broker cluster, ZooKeeper-free but heavyweight |
For events like OrderPlaced, JetStream is comfortably enough; whoever later needs event sourcing, long retention, and massive partition parallelism moves to Kafka — the consumer patterns stay the same.
NATS JetStream with the modern jetstream sub-package (since nats.go v1.34; the old js.Subscribe API keeps working):
// internal/bus/nats.go — create a stream and consume it as a work queue
package bus
import (
"context"
"log"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
func Connect(ctx context.Context) (jetstream.JetStream, func(), error) {
nc, err := nats.Connect("nats://nats.internal:4222")
if err != nil {
return nil, nil, err
}
js, err := jetstream.New(nc)
if err != nil {
nc.Close()
return nil, nil, err
}
return js, nc.Close, nil
}
func ConsumeOrders(ctx context.Context, js jetstream.JetStream, handle func([]byte) error) error {
if _, err := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
Name: "BOOKSTORE",
Subjects: []string{"bookstore.orders.>"},
}); err != nil {
return err
}
c, err := js.CreateOrUpdateConsumer(ctx, "BOOKSTORE", jetstream.ConsumerConfig{
Durable: "order-processor",
AckPolicy: jetstream.AckExplicitPolicy, // every message needs its own ack
})
if err != nil {
return err
}
cc, err := c.Consume(func(msg jetstream.Msg) {
if err := handle(msg.Data()); err != nil {
_ = msg.Nak() // back into the queue — again later, with delay
return
}
_ = msg.Ack() // ack only AFTER successful processing
})
if err != nil {
return err
}
defer cc.Stop()
<-ctx.Done()
return nil
}
// Terminal: broker restarts while 3 orders were being processed
// → the 3 unacked messages are redelivered — handle() runs again (idempotent!)
Kafka with franz-go — same contract, different mechanics: offsets instead of acks, commit after processing:
// internal/bus/kafka.go — franz-go: poll loop with manual commit
package bus
import (
"context"
"log"
"github.com/twmb/franz-go/pkg/kgo"
)
func ConsumeOrders(ctx context.Context, handle func([]byte) error) error {
cl, err := kgo.NewClient(
kgo.SeedBrokers("kafka-1.internal:9092", "kafka-2.internal:9092"),
kgo.ConsumerGroup("order-processor"),
kgo.ConsumeTopics("bookstore.orders"),
kgo.DisableAutoCommit(), // auto-commit would save offsets nobody processed
)
if err != nil {
return err
}
defer cl.Close()
for {
fetches := cl.PollRecords(ctx, 100)
if fetches.IsClientClosed() {
return nil
}
fetches.EachError(func(_ string, _ int32, err error) {
log.Printf("fetch error: %v", err) // partition trouble, broker restart — not fatal
})
fetches.EachRecord(func(r *kgo.Record) {
if err := handle(r.Value); err != nil {
log.Printf("processing failed, offset stays: %v", err)
return // no commit for this record — the group fetches it again later
}
})
cl.CommitRecords(ctx, fetches.Records()...) // persist only processed offsets
}
}
// Terminal: group: bookstore.orders, partition 2, 12 records
// → processing ok for 12 records, committed up to offset 4831
⚠ Common mistake: Acking the message immediately and processing afterwards —
msg.Ack()on the first line of the handler (or auto-commit enabled). Then the process dies in the middle of processing: the broker considers the message done, and the order is gone — at-least-once quietly became at-most-once through the ack order. The inverse trap is the reason duplicates are normal: acking after processing means a crash between work and ack redelivers the message. Together they yield the only correct combination: late ack plus an idempotent handler (order ID as key, upsert instead of insert).
Check: A JetStream consumer processes an order and crashes — between processing and msg.Ack(). What happens after restart?
Answer: The message is redelivered and the handler runs again — the handler must be idempotent
This is the core of at-least-once: something is done only once it got an ack. Without an ack — whether the crash came before or after the actual work — the message stays outstanding and comes back. The misconception 'the broker takes care of exactly-once' is widespread and expensive: brokers do not deliver exactly-once processing; only handlers that recognize repetitions do (order ID as a unique key, upsert, skipping already-processed IDs). Kafka with consumer groups behaves analogously: commit after processing, otherwise you lose messages; commit before, and you process duplicates.
Takeaways:
github.com/nats-io/nats.go/jetstream) adds streams with explicit acks — small, fast, one binary.github.com/twmb/franz-go (or github.com/IBM/sarama) means partitioned logs, consumer groups, and offsets instead of acks.msg.Nak() or a skipped commit for retries) — auto-commit and eager ack turn at-least-once into silent message loss.Now the final act of the restructuring: the order service writes the order to its PostgreSQL database and wants to tell the world about it — invoicing, shipping, and analytics should react to OrderPlaced. Right at that seam the classic distributed mistake happens: the order lands in the database, the publish to NATS/Kafka fails — and the order exists, but no other service knows about it. The reverse is just as bad: publish first, then persist, and the insert fails — the world reacts to an order that never existed. That is the dual-write problem, and its fix — the outbox pattern — is by no means a Go secret, it is architecture: the distributed sagas module of the architecture course treats both patterns and their compensation chains systematically. Here is the Go implementation.
Outbox: the Event Becomes Part of the Same Transaction
The idea is unspectacular and effective: instead of calling the broker directly, the service writes the event as a row into an outbox table — inside the same database transaction as the domain change. The commit creates both or neither. A separate relay process (or Debezium) reads the outbox, publishes to the broker, and marks the row. If the publish fails, the row stays and is sent again. The price: the relay produces at-least-once — and again, consumers must be idempotent.
The write path — order and event in one commit:
// internal/orders/outbox.go — order and event: one transaction, one commit
package orders
import (
"context"
"encoding/json"
"github.com/jackc/pgx/v5/pgxpool"
)
func (s *Store) PlaceOrder(ctx context.Context, o Order) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) // a no-op after commit — no longer an error path
if _, err := tx.Exec(ctx,
`INSERT INTO orders (id, isbn, qty, status) VALUES ($1, $2, $3, 'pending')`,
o.ID, o.ISBN, o.Qty); err != nil {
return err
}
payload, err := json.Marshal(OrderPlaced{ID: o.ID, ISBN: o.ISBN, Qty: o.Qty})
if err != nil {
return err
}
if _, err := tx.Exec(ctx,
`INSERT INTO outbox (topic, payload) VALUES ($1, $2)`,
"bookstore.orders.placed", payload); err != nil {
return err
}
return tx.Commit(ctx) // order + event row: both or nothing
}
// Terminal: commit ok
// → orders: 1 row (status pending), outbox: 1 row (sent_at NULL)
//
// Terminal: a broker outage does NOT disturb the commit — the outbox is just a table
// → order exists, event waits for the relay
The relay — a separate process that drains the outbox:
// internal/orders/relay.go — read the outbox, publish, mark; on failure the row stays
func (s *Relay) Run(ctx context.Context) error {
t := time.NewTicker(250 * time.Millisecond)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
rows, err := s.pool.Query(ctx,
`SELECT id, topic, payload FROM outbox WHERE sent_at IS NULL ORDER BY id LIMIT 50`)
if err != nil {
continue // DB briefly gone: the next tick tries again
}
for rows.Next() {
var id int64
var topic string
var payload []byte
if err := rows.Scan(&id, &topic, &payload); err != nil {
break
}
if err := s.bus.Publish(ctx, topic, payload); err != nil {
break // broker down: mark nothing, next tick tries again
}
if _, err := s.pool.Exec(ctx,
`UPDATE outbox SET sent_at = now() WHERE id = $1`, id); err != nil {
log.Printf("marking failed, message will duplicate: %v", err)
}
}
rows.Close()
}
}
}
// Terminal: relay tick after the broker returns
// → published bookstore.orders.placed (order bb-1042), sent_at set
The saga: several services take part in one business transaction without a shared transaction. Instead of rollback — which does not exist across service boundaries — every phase comes with a prepared compensation:
// internal/orders/saga.go — orchestration: steps forward, compensation backward
type step struct {
name string
do func(ctx context.Context, orderID string) error
undo func(ctx context.Context, orderID string) error
}
func (s *Saga) Run(ctx context.Context, orderID string) error {
steps := []step{
{"reserve", s.reserveStock, s.releaseStock},
{"charge", s.chargeCard, s.refund},
{"ship", s.createShipment, s.cancelShipment},
}
var done []step
for _, st := range steps {
if err := st.do(ctx, orderID); err != nil {
for i := len(done) - 1; i >= 0; i-- { // unwind backward
if uerr := done[i].undo(ctx, orderID); uerr != nil {
s.log.Error("compensation failed",
"step", done[i].name, "order", orderID, "err", uerr)
// do not abort: all remaining compensations must still run
}
}
return fmt.Errorf("step %q failed: %w", st.name, err)
}
done = append(done, st)
}
return nil
}
// Terminal: payment declined at step "charge"
// → compensation: releaseStock(bb-1042) ok — stock freed again
// → err: step "charge" failed: card declined (insufficient_funds)
// → orders: status 'failed', the customer sees "payment declined", no half-states
⚠ Common mistake: Trying to fix the dual write with "publish, then save" or "save, then publish" — both orders have a hole exactly in between, because database and broker share no transaction. No commit makes both atomic, and retry libraries do not change that. The only solvable variant is the outbox pattern: the event is written into the same local transaction as the domain row, and a relay bridges the gap to the broker with at-least-once plus idempotent consumers. Whoever only needs "mostly consistent" pays the bill later in the form of orders without invoices — or invoices without orders.
Check: Why is it not enough for PlaceOrder to first write the row into orders and then publish the message to NATS?
Answer: Because the process can crash between the successful commit and the publish — the order then exists, but the event never will
This is the dual-write problem in its purest form: the database commit and the broker publish are two independent systems with no shared transaction. Between the two steps anything can happen — crash, network outage, deployment. Save-without-event creates silently inconsistent state; publish-without-save creates phantom orders. The outbox pattern solves this by making the event an outbox row inside the same local transaction — the commit creates both or neither — and a relay bridges the last mile to the broker with a redelivery guarantee. The complete pattern family (including saga orchestration) lives in the architecture course's distributed-sagas module.
Takeaways:
Course navigation: ← Module 15 · All 20 modules · Module 17 →