Project: E-Commerce API — Services, Handlers, Cart, Orders, SMTP, Events, Swagger
"The easiest way to address inconsistencies in distributed state caused by failures is to implement server endpoints so that they're idempotent, which means that they can be called any number of times while guaranteeing that side effects only occur once." — Brandur Leach, "Designing robust and predictable APIs with idempotency", Stripe blog, 22 February 2017
Summary: One complete shop backend in Go: a catalogue with keyset pagination and search, a server-side cart that survives login, a checkout that in one PostgreSQL transaction reserves stock, creates the order and its items, records the payment intent and writes an OrderPlaced event to an outbox, an order state machine driven by signed payment webhooks, a relay that publishes events to an in-process bus or RabbitMQ, a worker that sends the confirmation mail over SMTP with retries, background jobs for the stock release timeout and abandoned carts, and an OpenAPI contract that a test keeps honest. Focus: the e-commerce domain (products, categories, users, carts, orders, order items, payments, inventory), the split between handlers, services and repositories, money in minor units and pure pricing rules, the schema and its constraints, transactions and row locks against overselling, idempotent order placement, the order state machine, the outbox, go-mail and templates, background workers, authentication and per-object authorization, validation and RFC 9457 errors, Swagger/OpenAPI, rate limiting and security headers, and how to test all of it without a database or a broker. Learning goal: Build and explain an order flow that never oversells, never charges or ships twice, never loses a confirmation mail, and never lets one customer read another's order; know which part of the code guarantees each of those, which test proves it, and what changes when the shop grows from one process to several services.
This chapter is an e-commerce API walkthrough: domain, catalogue/products, categories, cart, orders, order items, payments status, inventory/stock and users, built as one Go module you can run. It assembles techniques that other chapters teach in depth and links to them instead of re-teaching them: handlers, DTOs, the run function, ETag/If-Match and the generic Idempotency-Key middleware are in A REST API in Go; database/sql, pgx, pools and transactions in database/sql & pgx; password hashing, sessions and JWT in Authentication in Go; Watermill, RabbitMQ consumers and SQS in Event-Driven Go; middleware chaining in Middlewares; test techniques in Testing & Benchmarking. The money side of a shop (PSP integration, ledger, webhooks, refunds, PCI) is the subject of Payment Processing Architecture, and this project follows its rules: integer minor units, a derived idempotency key towards the PSP, a payment state machine that ignores late events, and an outbox for every money event. The general locking choice is in Optimistic & Pessimistic Locking, isolation in Isolation Levels, pagination in Pagination, the outbox in Outbox Pattern, idempotency as a system design topic in API Idempotency, and the order as an aggregate in Aggregates & Factories and Domain Events vs Integration Events.
Facts below were checked against the PostgreSQL current documentation (SELECT ... FOR UPDATE, transaction isolation, constraints, partial indexes, generated columns, text search, ILIKE, Appendix A error codes), Stripe's PaymentIntent lifecycle and idempotent-request pages, Brandur Leach's Stripe post, Shopify Engineering's "Building Resilient Payment Systems" (28 July 2022), RFC 9457, the IETF Idempotency-Key draft, OpenAPI 3.1.0, the READMEs of swaggo/swag, oapi-codegen, go-mail, pgx, amqp091-go, golang-migrate and goose, the RabbitMQ Go tutorials and publisher-confirms guide, Martin Fowler's Money pattern, the OWASP REST Security and API Security pages, the Go 1.22–1.25 release notes and net/http source, and the Laravel 13 documentation (Eloquent relationships, queries, database, queues, mail, Cashier, Scout). The module declares go 1.24 and pins github.com/jackc/pgx/v5 v5.8.0, github.com/wneessen/go-mail v0.7.2 (its go.mod says 1.24.0; v0.7.3 and v0.8.0 say 1.25.0 and v0.8.2 says 1.26.10, per the module proxy), github.com/rabbitmq/amqp091-go v1.17.0 and golang.org/x/time v0.14.0. The pgx pin is for the Go 1.24 line of this module only: pgx 5.12.0 (30 October 2026) fixed two high-severity issues, an SQL injection in simple-protocol batches and a require_auth/channel_binding bypass, per its CHANGELOG, so production code on Go 1.25+ should take the latest 5.x (see database/sql & pgx). It was compiled, vetted and tested with -race on Go 1.27.4 (macOS); no test needs PostgreSQL, RabbitMQ or an SMTP server.
Page map
| If you are looking for | Go to |
|---|---|
| The whole project on one screen | Everything in one minute |
| Why a shop is harder than CRUD | Why it exists |
| Where the patterns come from | Where it comes from |
| The fat handler and its replacement | Go |
| Products, categories, users, carts, orders, payments, stock | The domain |
| Packages, handlers vs services vs repositories | Project layout |
| Money as integers, currencies, rounding | Money |
| Tax and discounts | Pricing rules |
| Tables, constraints, indexes, migrations | Schema and migrations |
Store.InTx, retries on 40001 | Repository + transactions |
Overselling, FOR UPDATE, version columns | Stock: locks vs versions |
| The checkout transaction | Place order |
| Double clicks and retries | Idempotent order placement |
| created, paid, fulfilled, cancelled, refunded | Order state machine |
| Guest carts, cookies, login | Cart |
| Paging, filters, sort, search | Catalogue listing |
| Who may call what, and see which order | Authentication and authorization |
| 422, 409, problem+json | Validation and the error envelope |
OrderPlaced, PaymentCaptured, relay, RabbitMQ | Events through the outbox |
| Confirmation mail, go-mail, templates | SMTP mail |
| Retries, abandoned carts, unpaid orders | Background workers |
| PSP events into the order | Payment webhook |
| swag vs oapi-codegen, spec drift | Swagger/OpenAPI |
| 429, HSTS, nosniff | Rate limiting and security headers |
| Fake repos, httptest, real Postgres | Testing |
| Logs, metrics, traces | Observability |
| Shutdown, config, Docker | Deployment |
| Request pipeline, SQLSTATEs, exact responses | Mechanics |
| The bugs every shop meets | Solving the classic problems |
| What to use when | Choosing |
| One process to many services | In architecture |
| Run it yourself | Lab |
| Eloquent, Cashier, Scout, queues | For PHP/Laravel developers |
Everything in one minute
The packages. One module, academy/ecommerce-api-project; each row is a directory with its own tests.
| Package | Owns | Depends on | Proven by |
|---|---|---|---|
money | Money{Amount int64, Currency}, half-even rounding, allocation | stdlib | exact sums, rounding table, no lost cent |
pricing | Quote: subtotal, discount, tax, total as a pure function | money | table-driven cases |
domain | products, stock, cart, order, payment, events, state machine | money | transition table, merge rules |
store | the ports: Store.InTx, one interface per repository | domain | (interfaces only) |
memstore | in-memory adapter, the fake repos of every service test | store | rollback, keyset pages |
pgstore | PostgreSQL adapter (pgx v5), migrations, retry on 40001/40P01 | store, pgx | fake pgx.Tx, SQL builder; real Postgres behind a build tag |
service | use cases: catalogue, cart, checkout, orders, housekeeping | store, pricing | table-driven tests with fake repos, concurrency |
httpapi | routes, DTOs, auth, validation, RFC 9457, rate limit, headers, openapi.json | service | httptest API tests, spec-drift test |
outbox, bus, rabbit | relay, in-process bus, RabbitMQ publisher with confirms | store | order kept, failure retried |
mailer, worker | templates, go-mail SMTP sender, retries, jobs | domain, go-mail | one mail per event, permanent errors stop |
config, app, cmd/api | env config, wiring, graceful shutdown | everything | end-to-end flow, clean stop |
The endpoints.
| Method and path | Who | Does | Typical errors |
|---|---|---|---|
GET /v1/products | anyone | keyset page, filter, sort, search | 422 bad sort, limit, cursor |
GET /v1/products/{id} | anyone | one product, ETag = version | 404 |
POST /v1/admin/products | admin | create product and stock | 401, 403, 422 |
PUT /v1/admin/products/{id}/price | admin | change price with If-Match | 412 stale, 428 missing |
GET /v1/cart, PUT /v1/cart/items/{productID} | guest or customer | server-side cart, cart_id cookie for guests | 404, 422 |
POST /v1/cart/merge | customer | merge guest cart after login | 401 |
POST /v1/orders | customer | place order, Idempotency-Key required | 400, 409 stock, 422 cart or key reuse |
GET /v1/orders, GET /v1/orders/{id} | owner or admin | read orders | 404 for someone else's order |
POST /v1/orders/{id}/cancel | owner | cancel an unpaid order | 409 when paid |
POST /v1/admin/orders/{id}/fulfil | admin | ship a paid order | 409 when unpaid |
POST /v1/webhooks/psp | PSP (HMAC) | apply a payment event | 400 bad signature |
GET /healthz, /readyz, /openapi.json | ops | liveness, readiness, contract | 503 not ready |
The order lifecycle: created → paid → fulfilled → cancelled/refunded. Read it as "created, then paid, then fulfilled; an order ends either cancelled (before payment) or refunded (after)".
| From | To | Trigger | Side effects in the same transaction |
|---|---|---|---|
| (none) | created | POST /v1/orders | stock reserved, payment intent recorded, order.placed in the outbox |
created | paid | verified payment_intent.succeeded | payment succeeded, payment.captured in the outbox |
created | cancelled | customer cancel, or stock release timeout | stock released once, order.cancelled |
paid | fulfilled | admin ships | reservation becomes shipment (on_hand and reserved both drop) |
paid, fulfilled | refunded | refund recorded | refund handled in the payments system |
cancelled + late capture | cancelled | capture after the timeout | payment refund_pending, payment.refund_requested |
What protects what.
| Danger | First line | Last line (database) |
|---|---|---|
| Oversell | SELECT ... FOR UPDATE on stock rows, in product-id order | CHECK (reserved <= on_hand) |
| Double order on retry | Idempotency-Key + fingerprint, stored in the checkout transaction | PRIMARY KEY (scope, key) |
| Two payment intents | one intent per order in the service | payments.order_id UNIQUE, provider_key UNIQUE |
| Lost or phantom event | outbox row in the same transaction | outbox.event_id UNIQUE |
| Lost update on a price | If-Match + version compare-and-set | WHERE version = $n |
| Stale status from a late webhook | state machine: no edge, no change | CHECK (status IN (...)) |
| Reading someone else's order | per-object check in the service | (none: it is an application rule) |
Why it exists
A shop looks like CRUD with a checkout button. It is not, because three things happen at once that CRUD never meets: many people want the last unit of the same product at the same moment, the network between the customer, your API and the payment provider fails in the middle of a request, and some work (mail, warehouse, analytics) must happen exactly as often as the order happened, not as often as the request was retried. A first version that does everything in one handler works on a quiet day and fails on the first sale day: it oversells, it creates two orders for one double click, it answers 500 because the mail server was slow even though the order exists, and it trusts the price the browser sent.
| Naive shop | This project |
|---|---|
| Prices come from the request | Prices are read from the catalogue inside the checkout transaction |
float64 totals | int64 minor units, half-even rounding, allocation that never loses a cent |
| Check stock, then decrement, without a lock | Locked stock rows, all-or-nothing reservation, a CHECK as the net |
| Every retry is a new order | Idempotency-Key with fingerprint, replayed from the same transaction |
| Mail sent inside the request | order.placed written to an outbox, mailed by a worker with retries |
| Status is a free text column | A state machine with versioned transitions |
One isAdmin check per route | Route-level role plus per-object ownership in the service |
| Tests need a database | Services tested with fake repos, handlers with httptest, Postgres behind a build tag |
| Fewer files | More packages, and every rule has exactly one home |
An everyday picture. A bakery with a counter and a back room. The display is the catalogue; the customer's tray is the cart (it stays on the counter, not in the customer's pocket, so it survives "let me get my wallet"). When the customer says "I'll take these", the clerk moves the cakes from the shelf to a reservation shelf with a ticket (stock reserved, order created) and writes "call the customer when it is ready" on a slip in the outbox tray, all in one movement. The cashier rings up the payment; a late payment for a ticket that was already given up goes back as a refund, not as a resurrected order. A runner empties the outbox tray and makes the calls, and if the phone is busy, tries again later. If the same customer says "I'll take these" twice because the clerk did not answer fast enough, the clerk looks at the ticket number and says "already done".
Three common misunderstandings, up front
- "A transaction prevents overselling." A transaction at PostgreSQL's default
READ COMMITTEDlets two checkouts read the same stock number; only a row lock, an atomic conditionalUPDATE, a version check orSERIALIZABLEwith retry makes the second one see the first. - "Idempotency means a unique constraint on the order." A constraint turns the retry into an error the client cannot interpret; idempotency means the retry gets the first answer back, and a key reused with a different body is refused.
- "Publish the event after commit and it is reliable." A crash between commit and publish loses it; publishing before commit announces orders that roll back. The event belongs in the same transaction, as an outbox row.
Where it comes from
The building blocks are older than Go's place in web backends. Martin Fowler's Patterns of Enterprise Application Architecture (2002, with Dave Rice and others, per martinfowler.com) catalogues the Money pattern ("A large proportion of the computers in this world manipulate money, so it's always puzzled me that money isn't actually a first class data type in any mainstream programming language"), Optimistic Offline Lock (the version column) and Repository ("Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects"). Chris Richardson's microservices.io describes the transactional outbox for services that must update a database and send a message without a distributed transaction. Stripe's API popularised the Idempotency-Key header; Brandur Leach's February 2017 post explains it, and Stripe's docs today say that for API v1 it "saves the status code and body of the first request made with a given idempotency key". Shopify Engineering's July 2022 post on resilient payment systems adds a lesson about the key itself: switching from UUIDv4 to ULID gave "a 50 percent decrease in INSERT statement duration" in one high-throughput system. The IETF draft draft-ietf-httpapi-idempotency-key-header standardises the header and its 400/409/422 answers.
On the HTTP side, RFC 9457 (July 2023, obsoleting RFC 7807) defines Problem Details for error bodies, and OpenAPI 3.1.0 (15 February 2021) aligned the schema language with JSON Schema. Go 1.22 (February 2024) gave net/http.ServeMux method and wildcard patterns ("Routing Enhancements for Go 1.22", 13 February 2024), which is why this project needs no router library. swaggo/swag generates Swagger 2.0 from comments ("Swag converts Go annotations to Swagger Documentation 2.0"); oapi-codegen goes the other way, "to convert OpenAPI specifications to Go code". For mail, the standard library's net/smtp "is frozen and is not accepting new features", which is why projects use github.com/wneessen/go-mail. Laravel ships the same building blocks as framework features: Eloquent relationships, lockForUpdate, queued jobs with afterCommit, queued mailables, Cashier for Stripe and Scout for search (For PHP/Laravel developers).
Go
Before
The checkout most first versions look like. It compiles, it passes a happy-path test, and it is wrong in four ways the test below shows: the browser chooses the price, money is float64, every retry is a new order, and a slow mail server turns a successful order into a 500 that invites the customer to buy again.
// Package before is the checkout most first versions look like: one fat
// handler that trusts the client's prices, uses float64 for money, has no
// idempotency, and sends the confirmation mail inside the request. It
// works on a quiet day; the tests show what happens on a bad one.
package before
import (
"encoding/json"
"fmt"
"net/http"
"sync"
)
type Item struct {
ProductID int `json:"product_id"`
Price float64 `json:"price"` // sent by the browser
Qty int `json:"qty"`
}
type Order struct {
ID int `json:"id"`
Email string `json:"email"`
Items []Item `json:"items"`
Total float64 `json:"total"`
}
// Shop keeps everything in one struct, guarded by one mutex.
type Shop struct {
mu sync.Mutex
Stock map[int]int
Orders []Order
SendMail func(to, body string) error // net/smtp.SendMail in production
}
// PlaceOrder decodes the cart, totals it, decrements stock, stores the
// order and mails the customer, all before answering.
func (s *Shop) PlaceOrder(w http.ResponseWriter, r *http.Request) {
var in struct {
Email string `json:"email"`
Items []Item `json:"items"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
total := 0.0
for _, it := range in.Items {
total += it.Price * float64(it.Qty)
}
s.mu.Lock()
for _, it := range in.Items {
if s.Stock[it.ProductID] < it.Qty {
s.mu.Unlock()
http.Error(w, "out of stock", http.StatusConflict)
return
}
}
for _, it := range in.Items {
s.Stock[it.ProductID] -= it.Qty
}
o := Order{ID: len(s.Orders) + 1, Email: in.Email, Items: in.Items, Total: total}
s.Orders = append(s.Orders, o)
s.mu.Unlock()
if err := s.SendMail(in.Email, fmt.Sprintf("Order %d: total %v", o.ID, o.Total)); err != nil {
http.Error(w, "could not send confirmation", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(o)
}package before
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func post(s *Shop, body string) int {
rec := httptest.NewRecorder()
s.PlaceOrder(rec, httptest.NewRequest("POST", "/orders", strings.NewReader(body)))
return rec.Code
}
func TestWhatGoesWrong(t *testing.T) {
mailDown := true
s := &Shop{Stock: map[int]int{1: 10, 2: 10}, SendMail: func(string, string) error {
if mailDown {
return errors.New("dial tcp: i/o timeout")
}
return nil
}}
body := `{"email":"alice@example.com","items":[{"product_id":1,"price":0.1,"qty":1},{"product_id":2,"price":0.2,"qty":1}]}`
// 1. SMTP is slow and fails: the customer sees 500, but the order exists.
if code := post(s, body); code != http.StatusInternalServerError || len(s.Orders) != 1 {
t.Fatalf("code %d orders %d", code, len(s.Orders))
}
// 2. The customer presses "Buy" again: a second order, stock taken twice.
mailDown = false
if code := post(s, body); code != http.StatusCreated || len(s.Orders) != 2 || s.Stock[1] != 8 {
t.Fatalf("code %d orders %d stock %d", code, len(s.Orders), s.Stock[1])
}
// 3. Float money: 0.1 + 0.2 is not 0.3.
if s.Orders[0].Total == 0.3 {
t.Fatal("float64 surprised us by being exact")
}
// 4. The browser chose the price.
post(s, `{"email":"mallory@example.com","items":[{"product_id":1,"price":0.01,"qty":5}]}`)
if s.Orders[2].Total != 0.05 {
t.Fatalf("total %v", s.Orders[2].Total)
}
}After
The same use case as a service method. Prices come from the catalogue, totals from a pure function, stock is reserved all-or-nothing, the order, its items, the payment intent, the outbox row and the idempotency record are written in one transaction, and nothing leaves the process until it commits.
package service
import (
"context"
"errors"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/store"
)
// Checkout places orders.
type Checkout struct{ Deps }
// PlaceOrderInput comes from POST /v1/orders. Fingerprint is a SHA-256 of
// the canonical request body, computed by the handler.
type PlaceOrderInput struct {
Who domain.Principal
IdempotencyKey string
Fingerprint string
DiscountCode string
}
// PlaceOrderResult says whether this call created the order or replayed it.
type PlaceOrderResult struct {
Order domain.Order
Payment domain.Payment
Replayed bool
}
// PlaceOrder is the heart of the project. In ONE transaction it:
// 1. replays the stored result if the Idempotency-Key was seen (422 if the
// body differs), otherwise claims the key at once, so a concurrent
// duplicate blocks on the key's primary key here and later replays,
// 2. reads the cart and prices it from the catalogue (never from the client),
// 3. reserves stock for every line, in product-id order, all or nothing,
// 4. creates the order and its items (status created),
// 5. records the payment intent with a derived PSP idempotency key,
// 6. writes OrderPlaced to the outbox,
// 7. empties the cart.
//
// Any failure rolls everything back, the key claim included. Nothing is
// published and no mail is sent here: the relay and the worker do that
// after commit, from the outbox.
func (c Checkout) PlaceOrder(ctx context.Context, in PlaceOrderInput) (PlaceOrderResult, error) {
if in.Who.UserID == 0 {
return PlaceOrderResult{}, domain.ErrForbidden
}
if l := len(in.IdempotencyKey); l < 8 || l > 255 {
return PlaceOrderResult{}, &ValidationError{Fields: []FieldError{{"Idempotency-Key", "8 to 255 characters"}}}
}
scope := "POST /v1/orders user:" + itoa(in.Who.UserID)
var res PlaceOrderResult
err := retryConflict(func() error {
return c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
res = PlaceOrderResult{}
// 1. idempotency: replay, refuse, or claim the key before any work
now := c.Now()
orderID := c.NewID("ord")
rec, err := tx.Idempotency().Get(ctx, scope, in.IdempotencyKey)
switch {
case err == nil && rec.Fingerprint != in.Fingerprint:
return ErrIdempotencyMismatch
case err == nil:
res.Replayed = true
if res.Order, err = tx.Orders().Get(ctx, string(rec.Body)); err != nil {
return err
}
res.Payment, err = tx.Payments().ForOrder(ctx, res.Order.ID)
return err
case !errors.Is(err, domain.ErrNotFound):
return err
}
if err := tx.Idempotency().Put(ctx, store.IdemRecord{Scope: scope, Key: in.IdempotencyKey,
Fingerprint: in.Fingerprint, Status: 201, Body: []byte(orderID), CreatedAt: now}); err != nil {
return err // ErrDuplicateKey: a concurrent duplicate committed; InTx re-runs and replays
}
// 2. cart and prices
cart, err := tx.Carts().ForUser(ctx, in.Who.UserID)
if errors.Is(err, domain.ErrNotFound) || (err == nil && len(cart.Items) == 0) {
return domain.ErrEmptyCart
}
if err != nil {
return err
}
lines := make([]pricing.Line, 0, len(cart.Items))
names := map[int64]string{}
for _, it := range cart.Items {
p, err := tx.Products().Get(ctx, it.ProductID)
if err != nil {
return err
}
if !p.Active {
return domain.ErrInactiveProduct
}
names[p.ID] = p.Name
lines = append(lines, pricing.Line{ProductID: p.ID, SKU: p.SKU, Unit: p.Price, Qty: it.Qty, TaxClass: p.TaxClass})
}
var discounts []pricing.Discount
if d, ok := c.discount(in.DiscountCode); ok {
discounts = append(discounts, d)
}
totals, err := pricing.Quote(c.Currency, lines, discounts, c.TaxRates)
if err != nil {
return err
}
// 3. stock, all lines or none, in a fixed lock order
rs := make([]domain.Reservation, len(lines))
for i, l := range lines {
rs[i] = domain.Reservation{ProductID: l.ProductID, Qty: l.Qty}
}
if err := tx.Inventory().Reserve(ctx, domain.SortReservations(rs)); err != nil {
return err
}
// 4. order + items
o := domain.Order{ID: orderID, UserID: in.Who.UserID, Email: in.Who.Email,
Status: domain.OrderCreated, Subtotal: totals.Subtotal, Discount: totals.Discount,
Tax: totals.Tax, Total: totals.Total, Version: 1, CreatedAt: now, UpdatedAt: now,
ExpiresAt: now.Add(c.hold())}
for _, l := range totals.Lines {
lt, _ := l.Net.Add(l.Tax)
o.Items = append(o.Items, domain.OrderItem{ProductID: l.ProductID, SKU: l.SKU, Name: names[l.ProductID],
Unit: l.Unit, Qty: l.Qty, Discount: l.Discount, Tax: l.Tax, LineTotal: lt})
}
if err := tx.Orders().Create(ctx, &o); err != nil {
return err
}
// 5. payment intent (the PSP call happens in the payments system,
// with this derived key, so a retried attempt never charges twice)
pay := domain.Payment{ID: c.NewID("pay"), OrderID: o.ID, Amount: o.Total,
Status: domain.PaymentRequiresMethod, ProviderKey: o.ID + ":attempt:1", UpdatedAt: now}
if err := tx.Payments().Create(ctx, pay); err != nil {
return err
}
// 6. event, same transaction
ev := domain.NewEvent(domain.EvOrderPlaced, o.ID, o.Version, now, domain.OrderPlaced{
OrderID: o.ID, UserID: o.UserID, Email: o.Email, Total: o.Total.Amount, Curr: string(o.Total.Currency)})
if err := tx.Outbox().Add(ctx, ev); err != nil {
return err
}
// 7. cart gone
res.Order, res.Payment = o, pay
return tx.Carts().Delete(ctx, cart.ID, cart.Version) // conflict: an item was added meanwhile; re-run
})
})
return res, err
}
func (c Checkout) discount(code string) (pricing.Discount, bool) {
if code == "" || c.Discounts == nil {
return pricing.Discount{}, false
}
return c.Discounts(code)
}
func (d Deps) hold() time.Duration {
if d.StockHold > 0 {
return d.StockHold
}
return 15 * time.Minute
}The handler is thin: it requires the header, fingerprints the body, calls the service and maps errors to RFC 9457 problems. The whole flow is proven end to end by app_test.go: HTTP checkout, outbox, relay, bus, mail worker (whose first SMTP attempt fails), and a graceful shutdown.
package app
import (
"context"
"log/slog"
"net"
"net/http"
"strings"
"testing"
"time"
"academy/ecommerce-api-project/config"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/httpapi"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/memstore"
)
// The whole flow in one process: HTTP checkout -> outbox -> relay -> bus ->
// mail worker -> SMTP (recorded), then a graceful shutdown.
func TestOrderPlacedReachesTheMailboxAndShutdownIsClean(t *testing.T) {
cfg, _ := config.Load(func(string) string { return "" })
cfg.ShutdownTimeout = 2 * time.Second
rec := &mailer.Recorder{Fail: 1} // first SMTP attempt fails with a 421
a := New(cfg, Deps{Store: memstore.New(), Inbox: memstore.NewInbox(), Sender: rec,
Log: slog.New(slog.DiscardHandler), RelayTick: 10 * time.Millisecond, JobTick: time.Hour,
Auth: httpapi.StaticTokens{
"admin": {UserID: 1, Role: domain.RoleAdmin},
"alice": {UserID: 7, Email: "alice@example.com", Role: domain.RoleCustomer},
}})
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- a.Serve(ctx, ln) }()
base := "http://" + ln.Addr().String()
client := &http.Client{Transport: &http.Transport{}}
send := func(method, path, token, body string, hdr ...string) *http.Response {
req, _ := http.NewRequest(method, base+path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
for i := 0; i+1 < len(hdr); i += 2 {
req.Header.Set(hdr[i], hdr[i+1])
}
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
return res
}
if res := send("POST", "/v1/admin/products", "admin", `{"sku":"BOOK","name":"Go book","price":3999,"tax_class":"reduced","stock":5}`); res.StatusCode != 201 {
t.Fatalf("product: %d", res.StatusCode)
}
send("PUT", "/v1/cart/items/1", "alice", `{"qty":1}`)
if res := send("POST", "/v1/orders", "alice", `{"discount_code":"WELCOME10"}`, "Idempotency-Key", "a9b8c7d6-0001"); res.StatusCode != 201 {
t.Fatalf("order: %d", res.StatusCode)
}
deadline := time.Now().Add(5 * time.Second)
for len(rec.Sent()) == 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
sent := rec.Sent()
if len(sent) != 1 || sent[0].To != "alice@example.com" || !strings.Contains(sent[0].Text, "Total: 38.51 EUR") {
t.Fatalf("mail: %+v", sent)
}
// Shutdown closes idle connections at once but treats a connection that
// never sent a request as busy for 5 s; close ours so the test is fast.
client.CloseIdleConnections()
cancel()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("no graceful shutdown")
}
}
// APP_ROLE=api: the replica serves HTTP but starts no relay and no jobs.
func TestAPIRoleRunsNoBackgroundJobs(t *testing.T) {
cfg, _ := config.Load(func(k string) string { return map[string]string{"APP_ROLE": "api"}[k] })
cfg.ShutdownTimeout = time.Second
st := memstore.New()
rec := &mailer.Recorder{}
a := New(cfg, Deps{Store: st, Inbox: memstore.NewInbox(), Sender: rec, Log: slog.New(slog.DiscardHandler),
RelayTick: 5 * time.Millisecond, JobTick: 5 * time.Millisecond,
Auth: httpapi.StaticTokens{"admin": {UserID: 1, Role: domain.RoleAdmin}, "alice": {UserID: 7, Email: "a@example.com", Role: domain.RoleCustomer}}})
ln, _ := net.Listen("tcp", "127.0.0.1:0")
ctx, cancel := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- a.Serve(ctx, ln) }()
client := &http.Client{Transport: &http.Transport{}}
do := func(method, path, tok, body string, hdr ...string) int {
req, _ := http.NewRequest(method, "http://"+ln.Addr().String()+path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+tok)
if len(hdr) == 2 {
req.Header.Set(hdr[0], hdr[1])
}
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
return res.StatusCode
}
do("POST", "/v1/admin/products", "admin", `{"sku":"A","name":"A","price":100,"tax_class":"zero","stock":1}`)
do("PUT", "/v1/cart/items/1", "alice", `{"qty":1}`)
if c := do("POST", "/v1/orders", "alice", `{}`, "Idempotency-Key", "api-role-0001"); c != 201 {
t.Fatalf("order %d", c)
}
time.Sleep(100 * time.Millisecond) // 20 relay ticks if a relay were running
if len(rec.Sent()) != 0 || len(st.Unpublished()) != 1 {
t.Fatalf("api replica ran background work: sent %d, unpublished %d", len(rec.Sent()), len(st.Unpublished()))
}
client.CloseIdleConnections()
cancel()
if err := <-done; err != nil {
t.Fatal(err)
}
}The Go angle
Go pushes this design rather than fighting it. Interfaces are satisfied implicitly, so the ports in store are declared by the consumer and implemented by memstore and pgstore without either knowing the other; tests swap adapters with one constructor argument. context.Context flows from r.Context() through the service into pgx and go-mail, so a client that disconnects stops its own query. net/http since Go 1.22 routes by method and wildcard ("POST /v1/orders/{id}/cancel", read with r.PathValue("id")). embed puts the SQL migrations, the mail templates and openapi.json inside the binary. html/template escapes product names in the HTML mail by default. log/slog gives structured logs, and -race turns the concurrency tests into proofs. What Go does not give you is a framework that decides these things for you, which is the point of building it once by hand.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a timeline, real scenarios, a comparison table, and the code that does it.
The domain: products, categories, users, carts, orders, payments, stock Must-know
In plain words: before any handler, write down the nouns and the rules between them. A product belongs to a category and has a price and stock; a customer (user) has one cart; checking out turns the cart into an order with order items that copy the price and name at that moment; each order has exactly one payment intent whose status tracks the payment provider.
Common misunderstanding: "The order can point at the product for its price." Then a price change next week rewrites last week's invoices. Order items are a snapshot: SKU, name, unit price, discount, tax and line total are copied when the order is placed. The second one: "Stock is a number on the product." Stock has two numbers, on_hand (physically there) and reserved (promised to unpaid orders); what you can sell is the difference.
Definition: the aggregates are Product (with its Stock row), Cart (with CartItems, no prices), Order (with OrderItems, the root of the purchase, versioned) and Payment (the local record of the payment intent). User carries a role, customer or admin, and is owned by the authentication part of the system. Each aggregate is changed only through its own methods (Cart.Set, Cart.Merge, Order.Transition) and saved through its own repository; see Aggregates & Factories.
Customer action Aggregate touched Rows written
1 browse catalogue Product (read) none
2 add 2 x MUG to cart Cart carts, cart_items
3 log in Cart (guest -> customer) cart_items merged, guest cart deleted
4 place order Stock, Order, Payment inventory, orders, order_items, payments, outbox
5 PSP says succeeded Order, Payment orders (paid, v2), payments, outbox
6 warehouse ships Order, Stock orders (fulfilled, v3), inventory, outboxReal scenario: a price rise during a sale must not change orders already placed; a product taken off sale must disappear from the catalogue but stay readable in old orders; a customer who changes their e-mail must still find old orders; an admin edits a product while a checkout reads it.
| Entity | Identity | Changes how | Owned by |
|---|---|---|---|
Product | BIGINT identity, sku UNIQUE | admin edits, optimistic version | catalogue |
Category | identity, slug UNIQUE, parent_id tree | admin | catalogue |
Stock (inventory) | product_id | reserve, release, ship | inventory |
Cart | opaque random id (cookie), one per user | Set, Merge | cart |
Order + OrderItem | ord_<128-bit hex> | Transition, version +1 | ordering |
Payment | pay_<hex>, order_id UNIQUE | PSP events | payments |
User | identity, email UNIQUE, role | registration, admin | identity (see Authentication in Go) |
Fix / how to use it: keep the domain package free of HTTP, SQL and JSON tags on the aggregates; the state machine and the events are plain Go.
package domain
import (
"fmt"
"slices"
"time"
"academy/ecommerce-api-project/money"
)
// OrderStatus is the order state machine:
// created -> paid -> fulfilled, created -> cancelled, paid|fulfilled -> refunded.
type OrderStatus string
const (
OrderCreated OrderStatus = "created"
OrderPaid OrderStatus = "paid"
OrderFulfilled OrderStatus = "fulfilled"
OrderCancelled OrderStatus = "cancelled"
OrderRefunded OrderStatus = "refunded"
)
var orderEdges = map[OrderStatus][]OrderStatus{
OrderCreated: {OrderPaid, OrderCancelled},
OrderPaid: {OrderFulfilled, OrderRefunded},
OrderFulfilled: {OrderRefunded},
}
// CanBecome reports whether s -> to is an edge of the state machine.
func (s OrderStatus) CanBecome(to OrderStatus) bool { return slices.Contains(orderEdges[s], to) }
// OrderItem is a snapshot of a product at the moment of purchase: later
// price or name changes in the catalogue do not change past orders.
type OrderItem struct {
ProductID int64
SKU string
Name string
Unit money.Money
Qty int64
Discount money.Money
Tax money.Money
LineTotal money.Money // net + tax
}
// Order is the aggregate root for one purchase.
type Order struct {
ID string
UserID int64
Email string
Status OrderStatus
Items []OrderItem
Subtotal money.Money
Discount money.Money
Tax money.Money
Total money.Money
Version int64 // starts at 1, +1 per transition
CreatedAt time.Time
UpdatedAt time.Time
ExpiresAt time.Time // unpaid orders are cancelled and their stock released after this
}
// Transition moves the order along one edge and bumps the version.
func (o *Order) Transition(to OrderStatus, now time.Time) error {
if !o.Status.CanBecome(to) {
return fmt.Errorf("%w: order %s %s -> %s", ErrInvalidTransition, o.ID, o.Status, to)
}
o.Status, o.UpdatedAt = to, now
o.Version++
return nil
}
// Reservations lists the stock this order holds.
func (o *Order) Reservations() []Reservation {
rs := make([]Reservation, 0, len(o.Items))
for _, it := range o.Items {
rs = append(rs, Reservation{ProductID: it.ProductID, Qty: it.Qty})
}
return SortReservations(rs)
}
// PaymentStatus is a separate, smaller machine (a subset of Stripe's
// PaymentIntent statuses plus our own refund bookkeeping).
type PaymentStatus string
const (
PaymentRequiresMethod PaymentStatus = "requires_payment_method"
PaymentSucceeded PaymentStatus = "succeeded"
PaymentCanceled PaymentStatus = "canceled"
PaymentRefundPending PaymentStatus = "refund_pending" // captured after the order was cancelled
PaymentRefunded PaymentStatus = "refunded"
)
// Payment is the local record of the payment intent for an order. The PSP
// call itself lives in the payments system; this service only records the
// intent and reacts to the PSP's verified events.
type Payment struct {
ID string
OrderID string
Amount money.Money
Status PaymentStatus
ProviderKey string // idempotency key sent to the PSP: <order>:attempt:<n>
ProviderRef string // PSP object id, e.g. pi_..., once known
UpdatedAt time.Time
}package domain
import (
"slices"
"time"
)
// MaxQtyPerLine caps a cart line; merging two carts cannot exceed it.
const MaxQtyPerLine = 10
// CartItem is a product and a quantity. Prices are NOT stored in the cart:
// they are read from the catalogue at checkout.
type CartItem struct {
ProductID int64
Qty int64
}
// Cart is a server-side cart. A guest cart has UserID 0 and is found by its
// ID (an opaque random token in a cookie); a customer has at most one cart.
type Cart struct {
ID string
UserID int64
Email string // customer carts only: abandoned-cart reminders
Items []CartItem
UpdatedAt time.Time
RemindedAt *time.Time // abandoned-cart mail already sent
Version int64 // 0 = not saved yet; every Save is a compare-and-set
}
// Set puts qty of product in the cart (qty 0 removes the line).
func (c *Cart) Set(productID, qty int64, now time.Time) {
qty = min(qty, MaxQtyPerLine)
i := slices.IndexFunc(c.Items, func(it CartItem) bool { return it.ProductID == productID })
switch {
case i < 0 && qty > 0:
c.Items = append(c.Items, CartItem{ProductID: productID, Qty: qty})
case i >= 0 && qty > 0:
c.Items[i].Qty = qty
case i >= 0:
c.Items = slices.Delete(c.Items, i, i+1)
}
c.UpdatedAt = now
c.RemindedAt = nil
}
// Merge adds the guest cart's lines to c (the customer's cart) on login.
// Quantities of the same product are summed and capped at MaxQtyPerLine.
func (c *Cart) Merge(guest Cart, now time.Time) {
for _, g := range guest.Items {
cur := int64(0)
if i := slices.IndexFunc(c.Items, func(it CartItem) bool { return it.ProductID == g.ProductID }); i >= 0 {
cur = c.Items[i].Qty
}
c.Set(g.ProductID, cur+g.Qty, now)
}
c.UpdatedAt = now
}Project layout: service layer and handlers, ports and adapters Must-know
In plain words: handlers speak HTTP, services speak use cases, repositories speak SQL. A handler never opens a transaction; a service never sees an http.Request; a repository never decides whether an order may be cancelled.
Common misunderstanding: "A service layer is ceremony for a small API." In a shop the same use case is called from more than one place: Orders.Cancel from the customer endpoint and from the stock-release job; ApplyPayment from the webhook and from a reconciliation script. If the rule lives in the handler, the job has to copy it. The other one: "Put the repository interfaces next to the implementations." Go interfaces belong to the consumer: store declares what the services need, and both adapters satisfy it.
Definition: three layers plus a composition root. httpapi (edge) decodes, validates shape, authenticates and maps errors. service (application) runs one transaction script per use case over store.Store.InTx. store (ports) is a set of interfaces; memstore and pgstore (adapters) implement them. app wires concrete adapters chosen in cmd/api from the environment. The dependency arrows point inwards only.
Request Layer Package Knows about
1 POST /v1/orders edge httpapi HTTP, JSON, headers, Principal
2 Checkout.PlaceOrder(ctx, in) application service use case, transaction boundary
3 tx.Inventory().Reserve(...) port store interface only
4 UPDATE inventory ... adapter pgstore SQL, pgx, SQLSTATEs
5 tx.Outbox().Add(event) port/adapter pgstore same transaction as 4
6 201 Created edge httpapi DTO, Location headerReal scenario: the stock-release job and the customer cancel share cancelInTx; the webhook and an admin "mark paid" button share ApplyPayment; a CLI that imports products calls Catalog.CreateProduct; the tests call services directly without HTTP.
| Concern | Handler (httpapi) | Service (service) | Repository (pgstore) |
|---|---|---|---|
| JSON shape, unknown fields, body size | yes | no | no |
| Business validation (qty 0..10, price > 0) | no | yes | no (constraints as a net) |
| Authentication | middleware | receives Principal | no |
| Authorization per object | no | yes (CanSee) | no |
| Transaction boundary | no | InTx | implements it |
| SQL, locks, SQLSTATE mapping | no | no | yes |
| Status codes | yes, in one fail function | returns typed errors | returns domain errors |
Fix / how to use it: the ports are short and named after the aggregates; the services take them through a Deps struct with an injected clock and id generator.
// Package store declares the persistence ports the services need. There are
// two adapters: memstore (tests, local dev) and pgstore (PostgreSQL via pgx).
// The interfaces live here, next to their consumers' needs, not in the
// adapters.
package store
import (
"context"
"time"
"academy/ecommerce-api-project/domain"
)
// Store runs a unit of work. Everything fn does through tx commits or rolls
// back together: stock reservation, order, payment intent, outbox row and
// idempotency record are one transaction.
type Store interface {
InTx(ctx context.Context, fn func(ctx context.Context, tx Tx) error) error
Catalog() Catalog // read-only listing outside a transaction
}
// Tx gives access to the repositories inside one transaction.
type Tx interface {
Products() Products
Inventory() Inventory
Carts() Carts
Orders() Orders
Payments() Payments
Outbox() Outbox
Idempotency() Idempotency
}
// Catalog is the read side of the catalogue.
type Catalog interface {
ListProducts(ctx context.Context, q domain.ProductQuery) ([]domain.Product, error)
GetProduct(ctx context.Context, id int64) (domain.Product, error)
}
type Products interface {
Get(ctx context.Context, id int64) (domain.Product, error)
Create(ctx context.Context, p *domain.Product) error
// Update writes p only if the stored version is still expectedVersion
// (optimistic locking); otherwise domain.ErrConflict.
Update(ctx context.Context, p *domain.Product, expectedVersion int64) error
}
type Inventory interface {
Get(ctx context.Context, productID int64) (domain.Stock, error)
SetOnHand(ctx context.Context, productID, onHand int64) error
// Reserve holds stock for all reservations or for none
// (*domain.OutOfStockError). Input is sorted by product id.
Reserve(ctx context.Context, rs []domain.Reservation) error
Release(ctx context.Context, rs []domain.Reservation) error
// Ship turns a reservation into a shipment: on_hand -= qty, reserved -= qty.
Ship(ctx context.Context, rs []domain.Reservation) error
}
type Carts interface {
Get(ctx context.Context, id string) (domain.Cart, error)
ForUser(ctx context.Context, userID int64) (domain.Cart, error)
// Save is a compare-and-set on c.Version (0 = create): it fails with
// domain.ErrConflict if another transaction saved the cart since it was
// read, so a stale snapshot never overwrites a concurrent change. On
// success c.Version is the new version.
Save(ctx context.Context, c *domain.Cart) error
// Delete removes the cart only if it is still at version.
Delete(ctx context.Context, id string, version int64) error
// Abandoned lists customer carts not touched since before and not reminded.
Abandoned(ctx context.Context, before time.Time, limit int) ([]domain.Cart, error)
}
type Orders interface {
Create(ctx context.Context, o *domain.Order) error
Get(ctx context.Context, id string) (domain.Order, error)
// Update is a compare-and-set on version: it writes o only if the stored
// version is o.Version-1.
Update(ctx context.Context, o *domain.Order) error
ListForUser(ctx context.Context, userID int64, limit int) ([]domain.Order, error)
// Expired lists created (unpaid) orders whose ExpiresAt is before now.
Expired(ctx context.Context, now time.Time, limit int) ([]domain.Order, error)
}
type Payments interface {
Create(ctx context.Context, p domain.Payment) error
ForOrder(ctx context.Context, orderID string) (domain.Payment, error)
Update(ctx context.Context, p domain.Payment) error
}
// Outbox stores events in the business transaction; the relay publishes them.
type Outbox interface {
Add(ctx context.Context, events ...domain.Event) error
// Claim returns up to limit unpublished events, oldest first. The relay
// publishes them after this transaction and stops at the first event not
// yet due, so one relay per database keeps the order.
Claim(ctx context.Context, limit int) ([]domain.Event, error)
MarkPublished(ctx context.Context, ids []string, at time.Time) error
MarkFailed(ctx context.Context, id string, next time.Time) error
}
// IdemRecord is a stored response for an Idempotency-Key.
type IdemRecord struct {
Scope string // "POST /v1/orders user:7"
Key string
Fingerprint string // SHA-256 of the canonical request
Status int
Body []byte
CreatedAt time.Time
}
type Idempotency interface {
Get(ctx context.Context, scope, key string) (IdemRecord, error) // domain.ErrNotFound
// Put inserts the record; a concurrent insert of the same (scope, key)
// fails with ErrDuplicateKey and the whole transaction is retried, which
// then finds the winner's record and replays it.
Put(ctx context.Context, r IdemRecord) error
}
// Inbox remembers which events a consumer has already handled. Has is
// checked before the side effect and Mark called after it succeeded, so a
// crash in between repeats the side effect (at-least-once), never loses it.
type Inbox interface {
Has(ctx context.Context, consumer, eventID string) (bool, error)
Mark(ctx context.Context, consumer, eventID string) error
}// Package service is the application layer: one method per use case, each a
// transaction script over the store ports. Handlers translate HTTP to these
// calls; workers call them on a schedule. Nothing here knows about HTTP,
// SQL, RabbitMQ or SMTP.
package service
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/store"
)
// Deps are the collaborators every service shares. Clock and NewID are
// injected so tests are deterministic.
type Deps struct {
Store store.Store
Now func() time.Time
NewID func(prefix string) string
Currency money.Currency
TaxRates pricing.TaxRates
Discounts func(code string) (pricing.Discount, bool)
StockHold time.Duration // how long an unpaid order holds its stock
}
// RandomID returns prefix_ + 128 random bits in hex.
func RandomID(prefix string) string {
b := make([]byte, 16)
_, _ = rand.Read(b) // Go 1.24: "guaranteed not to fail"
return prefix + "_" + hex.EncodeToString(b)
}
// FieldError is one invalid input field.
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
}
// ValidationError collects every invalid field (422 in the API).
type ValidationError struct{ Fields []FieldError }
func (e *ValidationError) Error() string {
parts := make([]string, len(e.Fields))
for i, f := range e.Fields {
parts[i] = f.Field + ": " + f.Message
}
return "invalid input: " + strings.Join(parts, "; ")
}
func (e *ValidationError) add(field, format string, a ...any) {
e.Fields = append(e.Fields, FieldError{Field: field, Message: fmt.Sprintf(format, a...)})
}
func (e *ValidationError) orNil() error {
if len(e.Fields) == 0 {
return nil
}
return e
}
var (
// ErrIdempotencyMismatch: the key was used before with another body (422).
ErrIdempotencyMismatch = errors.New("idempotency key reused with a different request")
// ErrAmountMismatch: the PSP reports another amount than the order total.
ErrAmountMismatch = errors.New("captured amount differs from order total")
)
func requireAdmin(p domain.Principal) error {
if !p.IsAdmin() {
return domain.ErrForbidden
}
return nil
}Pricing and money in minor units Must-know
In plain words: a price is a whole number of cents (or yen, or fils) plus a currency code. Add integers, never floats; round once, at a known place, with a known rule.
Common misunderstanding: "float64 is fine if I round for display." The before test shows 0.1 + 0.2 != 0.3; summed over thousands of lines and compared with what the payment provider captured, those differences become support tickets. Another: "Every currency has two decimals." JPY has none and KWD has three; the money package keeps an exponent table and the PSP has its own exceptions (see Payment Processing Architecture).
Definition: money.Money{Amount int64, Currency} with Add/Sub/Mul that refuse mixed currencies and detect overflow, MulBasisPoints for percentages with half-even (banker's) rounding, and Allocate, which splits an amount by weights so the parts always sum to the whole. In PostgreSQL the columns are BIGINT plus CHAR(3). Fowler: "Monetary calculations are often rounded to the smallest currency unit. When you do this it's easy to lose pennies (or your local equivalent) because of rounding errors."
Step float64 money (int64 minor units)
1 0.10 EUR + 0.20 EUR 0.30000000000000004 10 + 20 = 30
2 10 % of 49.99 EUR 4.999 -> ? (display) 4999 * 1000 bp = 499.9 -> 500 (half-even)
3 spread 5.00 discount on 39.98 / 2 floats that may not Allocate([3998, 1001]) = 400 + 100 = 500
10.01 lines sum to 5.00
4 12.5 cents tax 12.5 half-even -> 12; 13.5 -> 14Real scenario: a 10 % code on a two-line cart where the line discounts must add up to the order discount for the invoice; tax per line on discounted amounts; a refund of one line of three; a report that sums total_minor across a million orders.
| Where | Type | Why |
|---|---|---|
| Go domain | money.Money (int64 + code) | exact, cheap, comparable with == |
| Go rates and percentages | basis points int64 (2000 = 20 %) | exact; math/big.Rat only for FX |
| PostgreSQL | BIGINT minor units, CHAR(3) | exact, indexable, CHECK (price_minor > 0) |
| JSON | {"amount": 3999, "currency": "EUR"} | no float in transit either |
| Laravel | integer columns, brick/money or bcmath | same idea |
Fix / how to use it: the whole package, and its test as the rounding table.
// Package money is a small value type for prices: an integer amount in the
// currency's minor unit (cents, yen, fils) plus an ISO 4217 code. There is no
// float anywhere, so 0.10 + 0.20 is exactly 0.30.
package money
import (
"errors"
"fmt"
"math"
"strings"
)
// Currency is an ISO 4217 alphabetic code such as "EUR".
type Currency string
// exponent is the number of minor-unit digits per currency (ISO 4217).
var exponent = map[Currency]int{"EUR": 2, "USD": 2, "GBP": 2, "JPY": 0, "KWD": 3}
var (
ErrCurrencyMismatch = errors.New("money: currency mismatch")
ErrOverflow = errors.New("money: overflow")
ErrUnknownCurrency = errors.New("money: unknown currency")
)
// Money is an amount in minor units. The zero value is "0 of no currency".
type Money struct {
Amount int64 `json:"amount"`
Currency Currency `json:"currency"`
}
// New returns amount minor units of cur, for example New(1999, "EUR") = 19.99 EUR.
func New(amount int64, cur Currency) Money { return Money{Amount: amount, Currency: cur} }
// Zero returns 0 in cur.
func Zero(cur Currency) Money { return Money{Currency: cur} }
// Exponent reports the minor-unit digits of cur.
func Exponent(cur Currency) (int, error) {
e, ok := exponent[cur]
if !ok {
return 0, fmt.Errorf("%w: %q", ErrUnknownCurrency, cur)
}
return e, nil
}
// Add returns m+o; both must have the same currency.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, fmt.Errorf("%w: %s + %s", ErrCurrencyMismatch, m.Currency, o.Currency)
}
s := m.Amount + o.Amount
if (o.Amount > 0 && s < m.Amount) || (o.Amount < 0 && s > m.Amount) {
return Money{}, ErrOverflow
}
return Money{Amount: s, Currency: m.Currency}, nil
}
// Sub returns m-o.
func (m Money) Sub(o Money) (Money, error) {
if o.Amount == math.MinInt64 {
return Money{}, ErrOverflow
}
return m.Add(Money{Amount: -o.Amount, Currency: o.Currency})
}
// Mul returns m*q (a quantity, never a fraction).
func (m Money) Mul(q int64) (Money, error) {
if q != 0 && (m.Amount*q)/q != m.Amount {
return Money{}, ErrOverflow
}
return Money{Amount: m.Amount * q, Currency: m.Currency}, nil
}
// MulBasisPoints returns m * bp / 10000 rounded half to even (banker's
// rounding). 2000 bp is 20 %. Tax and percentage discounts use it.
func (m Money) MulBasisPoints(bp int64) Money {
return Money{Amount: divRoundHalfEven(m.Amount*bp, 10000), Currency: m.Currency}
}
func divRoundHalfEven(n, d int64) int64 {
q, r := n/d, n%d
if r == 0 {
return q
}
twice := 2 * r
if twice < 0 {
twice = -twice
}
switch {
case twice > d, twice == d && q%2 != 0:
if n < 0 {
return q - 1
}
return q + 1
}
return q
}
// Allocate splits m by integer weights so the parts always sum to m (the
// largest-remainder rule: leftover minor units go to the first parts).
// Used to spread an order-level discount over the lines.
func (m Money) Allocate(weights []int64) []Money {
var total int64
for _, w := range weights {
total += w
}
out := make([]Money, len(weights))
if total == 0 {
for i := range out {
out[i] = Zero(m.Currency)
}
return out
}
var given int64
for i, w := range weights {
out[i] = Money{Amount: m.Amount * w / total, Currency: m.Currency}
given += out[i].Amount
}
for i := 0; given < m.Amount && len(out) > 0; i = (i + 1) % len(out) {
if weights[i] == 0 {
continue
}
out[i].Amount++
given++
}
return out
}
// IsZero reports whether the amount is 0.
func (m Money) IsZero() bool { return m.Amount == 0 }
// String formats 1999 EUR as "19.99 EUR" and 500 JPY as "500 JPY".
func (m Money) String() string {
e, err := Exponent(m.Currency)
if err != nil || e == 0 {
return fmt.Sprintf("%d %s", m.Amount, m.Currency)
}
sign, a := "", m.Amount
if a < 0 {
sign, a = "-", -a
}
p := int64(math.Pow10(e))
return fmt.Sprintf("%s%d.%0*d %s", sign, a/p, e, a%p, m.Currency)
}
// Parse reads "19.99" for cur without going through float64.
func Parse(s string, cur Currency) (Money, error) {
e, err := Exponent(cur)
if err != nil {
return Money{}, err
}
neg := strings.HasPrefix(s, "-")
s = strings.TrimPrefix(s, "-")
whole, frac, _ := strings.Cut(s, ".")
if len(frac) > e || whole == "" {
return Money{}, fmt.Errorf("money: %q has more than %d decimals or no integer part", s, e)
}
frac += strings.Repeat("0", e-len(frac))
var n int64
for _, c := range whole + frac {
if c < '0' || c > '9' {
return Money{}, fmt.Errorf("money: invalid amount %q", s)
}
if n > (math.MaxInt64-int64(c-'0'))/10 {
return Money{}, ErrOverflow
}
n = n*10 + int64(c-'0')
}
if neg {
n = -n
}
return Money{Amount: n, Currency: cur}, nil
}Tax/discount rules as pure functions Important
In plain words: "what does this cart cost" is a function from (lines, discounts, tax rates) to totals. It reads no clock, no database and no request, so it can be tested with a table and called again with the same inputs to get the same answer.
Common misunderstanding: "Discounts are a SQL UPDATE on the order." Then the rule lives in a query nobody tests, and an order replayed through idempotency could be priced differently. Another: "Tax on the total equals the sum of tax per line." It does not once rounding and different tax classes meet; pick one rule and document it. This project rounds tax per line, on the discounted net amount, half-even.
Definition: pricing.Quote(currency, lines, discounts, rates) returns Totals{Lines, Subtotal, Discount, Tax, Total, Applied}. A Discount is PercentOff (basis points) or AmountOff (minor units, capped at the subtotal) with an optional MinSubtotal. The order discount is allocated to lines by gross amount (Allocate), then each line's tax is Net * rate. Lines with quantity outside 1..99 or an unknown tax class are errors.
Line Gross Discount share Net Rate Tax (half-even)
1 2 x BOOK 19.99 3998 400 3598 7 % 251.86 -> 252
2 1 x MUG 10.01 1001 100 901 20 % 180.2 -> 180
3 order 4999 500 (TEN: 10 %) 4499 432 total 4931Real scenario: "10 % off orders over 50 EUR"; "5 EUR off, never below zero"; books at a reduced VAT rate next to a mug at the standard rate; a quote shown on the cart page that must equal the charged amount.
| Rule style | Testability | Where it runs | Risk |
|---|---|---|---|
Pure function (pricing.Quote) | table test, no setup | service, also the cart preview | none extra |
| SQL in the checkout query | needs a database | repository | rules hidden in SQL |
| Rules engine / DSL | needs the engine | anywhere | overkill until marketing writes rules |
| External tax service (Avalara, Stripe Tax) | contract tests | outside the transaction (quote first, then lock) | latency, availability |
Fix / how to use it:
// Package pricing turns cart lines into order totals. Every function here is
// pure: same input, same output, no clock, no database. That is what makes
// tax and discount rules testable with a table and safe to re-run when an
// order is replayed.
package pricing
import (
"errors"
"fmt"
"academy/ecommerce-api-project/money"
)
// Line is one cart line priced from the catalogue (never from the client).
type Line struct {
ProductID int64
SKU string
Unit money.Money
Qty int64
TaxClass string // "standard", "reduced", "zero"
}
// DiscountKind says how a discount is computed.
type DiscountKind int
const (
PercentOff DiscountKind = iota + 1 // BasisPoints of the subtotal
AmountOff // a fixed Amount, capped at the subtotal
)
// Discount is a promotion rule. MinSubtotal is in minor units.
type Discount struct {
Code string
Kind DiscountKind
BasisPoints int64
Amount int64
MinSubtotal int64
}
// TaxRates maps a tax class to a rate in basis points (2000 = 20 %).
type TaxRates map[string]int64
// PricedLine is a line after discount allocation and tax.
type PricedLine struct {
Line
Gross money.Money // Unit * Qty
Discount money.Money // share of the order discount
Net money.Money // Gross - Discount
Tax money.Money // Net * rate, rounded half-even per line
}
// Totals is the result of Quote.
type Totals struct {
Lines []PricedLine
Subtotal money.Money
Discount money.Money
Tax money.Money
Total money.Money
Applied []string // discount codes that applied
}
var (
ErrNoLines = errors.New("pricing: no lines")
ErrBadQuantity = errors.New("pricing: quantity must be between 1 and 99")
ErrUnknownTax = errors.New("pricing: unknown tax class")
)
// Quote prices the lines. Tax is computed on the discounted net amount of
// each line (tax-exclusive prices), which is how most EU and US shops do it.
func Quote(cur money.Currency, lines []Line, discounts []Discount, rates TaxRates) (Totals, error) {
if len(lines) == 0 {
return Totals{}, ErrNoLines
}
t := Totals{Subtotal: money.Zero(cur), Discount: money.Zero(cur), Tax: money.Zero(cur), Total: money.Zero(cur)}
weights := make([]int64, len(lines))
for i, l := range lines {
if l.Qty < 1 || l.Qty > 99 {
return Totals{}, fmt.Errorf("%w: %s qty %d", ErrBadQuantity, l.SKU, l.Qty)
}
gross, err := l.Unit.Mul(l.Qty)
if err != nil {
return Totals{}, err
}
if t.Subtotal, err = t.Subtotal.Add(gross); err != nil {
return Totals{}, err
}
t.Lines = append(t.Lines, PricedLine{Line: l, Gross: gross})
weights[i] = gross.Amount
}
off := int64(0)
for _, d := range discounts {
if t.Subtotal.Amount < d.MinSubtotal {
continue
}
off += discountAmount(d, t.Subtotal)
t.Applied = append(t.Applied, d.Code)
}
off = min(off, t.Subtotal.Amount) // never a negative total
t.Discount = money.New(off, cur)
shares := t.Discount.Allocate(weights)
for i := range t.Lines {
pl := &t.Lines[i]
rate, ok := rates[pl.TaxClass]
if !ok {
return Totals{}, fmt.Errorf("%w: %q", ErrUnknownTax, pl.TaxClass)
}
pl.Discount = shares[i]
pl.Net, _ = pl.Gross.Sub(pl.Discount)
pl.Tax = pl.Net.MulBasisPoints(rate)
t.Tax, _ = t.Tax.Add(pl.Tax)
}
net, _ := t.Subtotal.Sub(t.Discount)
t.Total, _ = net.Add(t.Tax)
return t, nil
}
func discountAmount(d Discount, subtotal money.Money) int64 {
switch d.Kind {
case PercentOff:
return subtotal.MulBasisPoints(d.BasisPoints).Amount
case AmountOff:
return d.Amount
}
return 0
}package pricing
import (
"errors"
"testing"
"academy/ecommerce-api-project/money"
)
var rates = TaxRates{"standard": 2000, "reduced": 700, "zero": 0}
func eur(a int64) money.Money { return money.New(a, "EUR") }
func TestQuote(t *testing.T) {
book := Line{ProductID: 1, SKU: "BOOK", Unit: eur(1999), Qty: 2, TaxClass: "reduced"}
mug := Line{ProductID: 2, SKU: "MUG", Unit: eur(1001), Qty: 1, TaxClass: "standard"}
tests := []struct {
name string
lines []Line
discounts []Discount
subtotal, discount, tax, total int64
applied int
}{
{"no discount", []Line{book, mug}, nil, 4999, 0, 280 + 200, 4999 + 480, 0},
{"10 percent off", []Line{book, mug}, []Discount{{Code: "TEN", Kind: PercentOff, BasisPoints: 1000}},
4999, 500, 252 + 180, 4499 + 432, 1},
{"amount off below threshold is ignored", []Line{mug}, []Discount{{Code: "FIVE", Kind: AmountOff, Amount: 500, MinSubtotal: 5000}},
1001, 0, 200, 1201, 0},
{"amount off capped at subtotal", []Line{mug}, []Discount{{Code: "BIG", Kind: AmountOff, Amount: 5000}},
1001, 1001, 0, 0, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Quote("EUR", tt.lines, tt.discounts, rates)
if err != nil {
t.Fatal(err)
}
if got.Subtotal.Amount != tt.subtotal || got.Discount.Amount != tt.discount ||
got.Tax.Amount != tt.tax || got.Total.Amount != tt.total || len(got.Applied) != tt.applied {
t.Fatalf("got sub %d disc %d tax %d total %d applied %v", got.Subtotal.Amount,
got.Discount.Amount, got.Tax.Amount, got.Total.Amount, got.Applied)
}
var lineDisc int64
for _, l := range got.Lines {
lineDisc += l.Discount.Amount
}
if lineDisc != got.Discount.Amount {
t.Fatalf("line discounts %d != order discount %d", lineDisc, got.Discount.Amount)
}
})
}
}
func TestQuoteRejectsBadInput(t *testing.T) {
if _, err := Quote("EUR", nil, nil, rates); !errors.Is(err, ErrNoLines) {
t.Fatalf("got %v", err)
}
if _, err := Quote("EUR", []Line{{SKU: "X", Unit: eur(1), Qty: 0, TaxClass: "zero"}}, nil, rates); !errors.Is(err, ErrBadQuantity) {
t.Fatalf("got %v", err)
}
if _, err := Quote("EUR", []Line{{SKU: "X", Unit: eur(1), Qty: 1, TaxClass: "luxury"}}, nil, rates); !errors.Is(err, ErrUnknownTax) {
t.Fatalf("got %v", err)
}
}Postgres schema and migrations Must-know
In plain words: the schema is the part of the business rules that holds even when the code has a bug. Give every money column an integer type, every status a CHECK, every "one of these per that" a UNIQUE, and every background scan a partial index. Change it only through numbered migration files.
Common misunderstanding: "Constraints duplicate the Go validation, so skip them." The Go code runs in one process at a time; the constraint runs for every writer, including the admin who fixes data by hand at 2 a.m. and the next service that writes to the table. The other: "Migrations can be applied by the app at start-up." With three replicas starting at once, three processes race to migrate; run migrations as a separate step of the deployment.
Definition: pgstore/migrations/0001_init.up.sql and .down.sql (the NNNN_name.up.sql/.down.sql naming of golang-migrate; goose uses one file with -- +goose Up/Down sections). The constraints that matter: inventory_no_oversell CHECK (reserved <= on_hand), payments.order_id UNIQUE (one intent per order), provider_key UNIQUE (one PSP key per attempt), outbox.event_id UNIQUE, idempotency_keys PRIMARY KEY (scope, key), carts_one_per_user (a partial unique index on user_id WHERE user_id IS NOT NULL). products.search is a stored generated column, to_tsvector('simple', name || ' ' || sku), with a GIN index. PostgreSQL's docs on partial indexes: they let you index "a subset of a table", which is what orders_unpaid_expiry ... WHERE status = 'created' and outbox_unpublished ... WHERE published_at IS NULL do: the background scans stay small however many old orders exist.
Migration step (deploy pipeline) Effect
1 migrate -path pgstore/migrations -database $URL up applies 0001 once, records version 1
2 new replicas start no DDL at start-up, they just connect
3 0002 adds a column NULLable, backfills in batches old code still works (expand)
4 deploy code that writes the column
5 0003 sets NOT NULL contract, once all writers are newReal scenario: a bug in a promotion sets reserved above on_hand and the CHECK turns it into an error instead of an oversell; a second payment intent for the same order fails on order_id UNIQUE; a webhook handler that inserts the same event twice fails on event_id UNIQUE; a guest cart table with millions of abandoned rows does not slow the reminder job because its index only covers customer carts not yet reminded.
| Table | Key constraints | Indexes | Why |
|---|---|---|---|
products | sku UNIQUE, price_minor > 0 | partial keyset indexes per sort, GIN on search | listing, search |
inventory | reserved >= 0, reserved <= on_hand | PK | the oversell net |
carts, cart_items | qty BETWEEN 1 AND 10, one cart per user | carts_abandoned partial | cart and reminders |
orders | status IN (...), total_minor >= 0 | (user_id, created_at DESC), partial on status = 'created' | history, expiry job |
order_items | PK (order_id, line), qty > 0 | PK | the snapshot |
payments | order_id UNIQUE, provider_key UNIQUE, provider_ref UNIQUE | uniques | one intent, one PSP object |
outbox | event_id UNIQUE | partial on unpublished | relay scan |
idempotency_keys | PK (scope, key), key length 8..255 | PK | replay |
processed_events | PK (consumer, event_id) | PK | inbox |
Fix / how to use it: the migration, embedded in the binary with //go:embed migrations/*.sql so a migrate sub-command or a test can read it.
-- 0001_init: the e-commerce schema. Money is BIGINT minor units + CHAR(3).
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
role TEXT NOT NULL DEFAULT 'customer' CHECK (role IN ('customer', 'admin')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE categories (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
parent_id BIGINT REFERENCES categories (id)
);
CREATE TABLE products (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
category_id BIGINT REFERENCES categories (id),
price_minor BIGINT NOT NULL CHECK (price_minor > 0),
currency CHAR(3) NOT NULL,
tax_class TEXT NOT NULL,
active BOOLEAN NOT NULL DEFAULT true,
version BIGINT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
search TSVECTOR GENERATED ALWAYS AS (to_tsvector('simple', name || ' ' || sku)) STORED
);
-- Keyset pagination: one index per sort order, partial on active rows.
CREATE INDEX products_newest ON products (created_at DESC, id DESC) WHERE active;
CREATE INDEX products_price ON products (price_minor, id) WHERE active;
CREATE INDEX products_name ON products ((name COLLATE "C"), id) WHERE active;
CREATE INDEX products_cat ON products (category_id, created_at DESC, id DESC) WHERE active;
CREATE INDEX products_search ON products USING GIN (search);
CREATE TABLE inventory (
product_id BIGINT PRIMARY KEY REFERENCES products (id),
on_hand BIGINT NOT NULL DEFAULT 0,
reserved BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT inventory_reserved_nonneg CHECK (reserved >= 0),
CONSTRAINT inventory_no_oversell CHECK (reserved <= on_hand)
);
CREATE TABLE carts (
id TEXT PRIMARY KEY, -- opaque random token (guest cookie)
user_id BIGINT REFERENCES users (id), -- NULL for guests
email TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
reminded_at TIMESTAMPTZ,
version BIGINT NOT NULL DEFAULT 1 -- compare-and-set on every save
);
CREATE UNIQUE INDEX carts_one_per_user ON carts (user_id) WHERE user_id IS NOT NULL;
CREATE INDEX carts_abandoned ON carts (updated_at) WHERE user_id IS NOT NULL AND reminded_at IS NULL;
CREATE TABLE cart_items (
cart_id TEXT NOT NULL REFERENCES carts (id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products (id),
qty INT NOT NULL CHECK (qty BETWEEN 1 AND 10),
PRIMARY KEY (cart_id, product_id)
);
CREATE TABLE orders (
id TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users (id),
email TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('created', 'paid', 'fulfilled', 'cancelled', 'refunded')),
subtotal_minor BIGINT NOT NULL,
discount_minor BIGINT NOT NULL DEFAULT 0,
tax_minor BIGINT NOT NULL,
total_minor BIGINT NOT NULL CHECK (total_minor >= 0),
currency CHAR(3) NOT NULL,
version BIGINT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX orders_by_user ON orders (user_id, created_at DESC);
-- The stock-release job scans only unpaid orders.
CREATE INDEX orders_unpaid_expiry ON orders (expires_at) WHERE status = 'created';
CREATE TABLE order_items (
order_id TEXT NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
line INT NOT NULL,
product_id BIGINT NOT NULL REFERENCES products (id),
sku TEXT NOT NULL,
name TEXT NOT NULL,
unit_minor BIGINT NOT NULL,
qty INT NOT NULL CHECK (qty > 0),
discount_minor BIGINT NOT NULL,
tax_minor BIGINT NOT NULL,
line_total_minor BIGINT NOT NULL,
PRIMARY KEY (order_id, line)
);
CREATE TABLE payments (
id TEXT PRIMARY KEY,
order_id TEXT NOT NULL UNIQUE REFERENCES orders (id), -- one intent per order
amount_minor BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
status TEXT NOT NULL CHECK (status IN ('requires_payment_method', 'succeeded', 'canceled', 'refund_pending', 'refunded')),
provider_key TEXT NOT NULL UNIQUE, -- <order>:attempt:<n>
provider_ref TEXT UNIQUE, -- pi_... from the PSP
updated_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE outbox (
seq BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_id TEXT NOT NULL UNIQUE,
type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
payload JSONB NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL,
attempts INT NOT NULL DEFAULT 0,
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX outbox_unpublished ON outbox (seq) WHERE published_at IS NULL;
CREATE TABLE idempotency_keys (
scope TEXT NOT NULL,
key TEXT NOT NULL CHECK (length(key) BETWEEN 8 AND 255),
fingerprint TEXT NOT NULL,
status INT NOT NULL,
body BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (scope, key)
);
CREATE TABLE processed_events (
consumer TEXT NOT NULL,
event_id TEXT NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, event_id)
);Repository + transactions: Store.InTx and the retry loop Must-know
In plain words: a service says "run this function in one transaction"; the store begins it, hands the function repositories bound to that transaction, commits if the function returns nil, rolls back otherwise, and runs the whole function again if PostgreSQL says the outcome depended on timing.
Common misunderstanding: "Pass *sql.Tx or pgx.Tx into the services." Then every service imports the driver and the in-memory fake has to imitate pgx. The opposite mistake: "Each repository method opens its own transaction." Then reserving stock and creating the order are two transactions, and a crash between them leaks stock. The third: "Retrying a transaction is safe for any function." Only if the function has no side effects outside the transaction; that is why PlaceOrder makes no HTTP call and publishes nothing.
Definition: store.Store.InTx(ctx, fn func(ctx, tx store.Tx) error) error. pgstore.Store.InTx begins READ COMMITTED, sets lock_timeout for the transaction (set_config('lock_timeout', '5s', true), the function form of SET LOCAL), runs fn, commits; on SQLSTATE 40001 (serialization_failure), 40P01 (deadlock_detected) or a lost idempotency race it re-runs up to MaxAttempts (3) with a small jitter; on 55P03 (lock_not_available) it returns store.ErrBusy. PostgreSQL's isolation chapter is explicit that applications must be ready for this: serialization failures "always return with an SQLSTATE value of '40001'". The rollback uses context.WithoutCancel(ctx) so a cancelled request still releases its locks promptly.
T1 (checkout A) T2 (checkout B), same last unit
1 BEGIN; lock stock row 42 (FOR UPDATE)
2 BEGIN; lock stock row 42 -> waits
3 INSERT order, payment, outbox; COMMIT
4 lock granted, reads committed row: available 0
5 OutOfStockError -> ROLLBACK -> 409
(with SERIALIZABLE instead of the lock: T2 fails at commit with 40001 and InTx re-runs it;
the re-run reads available 0 and returns 409 the same way)Real scenario: two admins restock and adjust the same product; a deadlock between a checkout and the fulfilment job on two stock rows (prevented by lock ordering, retried if it happens anyway); a flash sale where the second of two simultaneous checkouts must see the first's reservation; a request cancelled by the client mid-transaction.
| Error | SQLSTATE / value | InTx does | API answer |
|---|---|---|---|
| serialization_failure | 40001 | re-run (max 3) | after 3: 500 with store.ErrRetryable logged |
| deadlock_detected | 40P01 | re-run | as above |
unique_violation on idempotency_keys (or ErrDuplicateKey) | 23505 | re-run, which replays | 201 replayed |
| lock_not_available | 55P03 | return ErrBusy | 409 busy, Retry-After: 1 (a duplicate key still running, or a very hot stock row) |
check_violation inventory_no_oversell | 23514 | return | 409 out of stock (mapped in SetOnHand) |
business error (ErrEmptyCart, OutOfStockError) | n/a | return, no retry | 422 / 409 |
| context canceled | context.Canceled | return | client is gone |
Fix / how to use it: the adapter's transaction runner; the per-table SQL is in repos.go.
// Package pgstore implements store.Store on PostgreSQL with pgx v5.
// Transactions run at READ COMMITTED with explicit row locks where the
// business needs them (stock), compare-and-set version columns where it
// does not (orders, products), and are re-run on serialization failure
// (40001), deadlock (40P01) and a lost race on an idempotency key (23505).
package pgstore
import (
"context"
"embed"
"errors"
"math/rand/v2"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"academy/ecommerce-api-project/store"
)
// Migrations holds the versioned SQL files (golang-migrate / goose naming).
//
//go:embed migrations/*.sql
var Migrations embed.FS
// beginner is the part of *pgxpool.Pool this package needs; tests fake it.
type beginner interface {
BeginTx(ctx context.Context, opts pgx.TxOptions) (pgx.Tx, error)
}
// Store is the PostgreSQL adapter.
type Store struct {
db beginner
reader querier
MaxAttempts int
LockTimeout string // SET LOCAL lock_timeout, e.g. "5s"
FullText bool // search with tsvector instead of ILIKE
}
var _ store.Store = (*Store)(nil)
// New wraps a pool (*pgxpool.Pool satisfies both interfaces).
func New(pool interface {
beginner
querier
}) *Store {
return &Store{db: pool, reader: pool, MaxAttempts: 3, LockTimeout: "5s"}
}
// InTx runs fn in a transaction and re-runs it from the start when
// PostgreSQL says the outcome depends on timing. fn must therefore have no
// side effects outside tx (no HTTP calls, no publishing).
func (s *Store) InTx(ctx context.Context, fn func(ctx context.Context, tx store.Tx) error) error {
var err error
for attempt := 1; ; attempt++ {
err = s.once(ctx, fn)
if err == nil || attempt >= max(s.MaxAttempts, 1) || !retryable(err) {
return classify(err)
}
// Jitter so two retried transactions do not collide again.
t := time.NewTimer(time.Duration(rand.IntN(20*attempt)+1) * time.Millisecond)
select {
case <-ctx.Done():
t.Stop()
return errors.Join(err, ctx.Err())
case <-t.C:
}
}
}
func (s *Store) once(ctx context.Context, fn func(ctx context.Context, tx store.Tx) error) (err error) {
tx, err := s.db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return err
}
defer func() {
if err != nil {
// Rollback with a context that survives the request's cancellation.
_ = tx.Rollback(context.WithoutCancel(ctx))
}
}()
if s.LockTimeout != "" {
if _, err = tx.Exec(ctx, "SELECT set_config('lock_timeout', $1, true)", s.LockTimeout); err != nil {
return err
}
}
if err = fn(ctx, &pgTx{tx: tx, fullText: s.FullText}); err != nil {
return err
}
return tx.Commit(ctx)
}
// SQLSTATE codes this package reacts to (PostgreSQL Appendix A).
const (
codeUniqueViolation = "23505"
codeCheckViolation = "23514"
codeSerialization = "40001"
codeDeadlock = "40P01"
codeLockNotAvailable = "55P03"
constraintNoOversell = "inventory_no_oversell"
constraintIdempotency = "idempotency_keys_pkey"
)
func pgCode(err error) (string, string) {
var pe *pgconn.PgError
if errors.As(err, &pe) {
return pe.Code, pe.ConstraintName
}
return "", ""
}
func retryable(err error) bool {
code, constraint := pgCode(err)
switch {
case code == codeSerialization, code == codeDeadlock:
return true
case code == codeUniqueViolation && constraint == constraintIdempotency:
return true // the winner committed; the re-run finds its record and replays
}
return errors.Is(err, store.ErrDuplicateKey)
}
// classify turns driver errors into store errors the services understand.
func classify(err error) error {
switch code, _ := pgCode(err); code {
case codeLockNotAvailable:
return errors.Join(store.ErrBusy, err)
case codeSerialization, codeDeadlock:
return errors.Join(store.ErrRetryable, err)
}
return err
}Stock: SELECT FOR UPDATE vs optimistic version Must-know
In plain words: for the hot, contended number (stock of a popular product) take a row lock for the few milliseconds of the checkout. For things people edit slowly in a form (a product's price, an order's status changed by a job), do not hold a lock: remember the version you read and write only if it has not changed.
Common misunderstanding: "Optimistic locking is always faster." Under contention, optimistic writers lose and retry; for the last 10 units of a sale item with 1,000 buyers, almost every attempt is wasted work. The opposite: "FOR UPDATE everywhere is safest." A lock held while an admin edits a form for five minutes blocks every checkout for that product. Choose per resource. The third: "Locking order does not matter." Two checkouts that lock products 9 then 3 and 3 then 9 deadlock (40P01); domain.SortReservations puts every reservation in product-id order first.
Definition: pessimistic: SELECT product_id, on_hand - reserved FROM inventory WHERE product_id = ANY($1) ORDER BY product_id FOR UPDATE, check every line, then UPDATE ... SET reserved = reserved + $2. PostgreSQL: "To prevent the operation from waiting for other transactions to commit, use either the NOWAIT or SKIP LOCKED option"; neither fits a checkout (both would turn "wait 3 ms" into a failure), but SKIP LOCKED fits the abandoned-cart scan. A one-line alternative is the atomic conditional update UPDATE inventory SET reserved = reserved + $2 WHERE product_id = $1 AND on_hand - reserved >= $2, checking RowsAffected. Optimistic: UPDATE products SET ..., version = version + 1 WHERE id = $1 AND version = $2; zero rows means someone else won (domain.ErrConflict → 412 for If-Match, or a re-read and retry for jobs via retryConflict). The general trade-off is in Optimistic & Pessimistic Locking.
Admin A (form) Admin B (form) Checkout C
1 GET product 7 -> ETag "3" GET product 7 -> ETag "3"
2 FOR UPDATE stock 7 (3 ms) ... COMMIT
3 PUT price, If-Match "3" -> 200, version 4
4 PUT price, If-Match "3" -> 412 (version is 4)
5 GET again, decide, PUT If-Match "4" -> 200
No lock was held during the minutes between 1 and 3; the checkout never waited for an admin.Real scenario: a flash sale on one SKU (lock); an admin price edit (version); the stock-release job and a late payment racing for the same order (version on orders, the loser re-reads and sees the new status); a warehouse sync that sets on_hand (lock, short); a bulk import (one transaction per batch, lock order by id).
| Resource | Contention | Hold time | Choice here | Failure mode |
|---|---|---|---|---|
inventory row | high in sales | milliseconds | SELECT ... FOR UPDATE, id order | wait; 55P03 after lock_timeout |
products row | low | minutes (form) | version + If-Match | 412, user reloads |
orders row | low, but job vs webhook | milliseconds | version compare-and-set | ErrConflict, re-read and retry |
carts for reminders | none (batch) | milliseconds | FOR UPDATE SKIP LOCKED | rows skipped by a second worker |
| Whole checkout | any | milliseconds | SERIALIZABLE + retry (alternative) | 40001, re-run |
Fix / how to use it: the inventory, order and product repositories (and the rest of the SQL).
package pgstore
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/store"
)
// querier is what both pgx.Tx and *pgxpool.Pool offer.
type querier interface {
Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
type pgTx struct {
tx pgx.Tx
fullText bool
}
func (t *pgTx) Products() store.Products { return products{t.tx} }
func (t *pgTx) Inventory() store.Inventory { return inventory{t.tx} }
func (t *pgTx) Carts() store.Carts { return carts{t.tx} }
func (t *pgTx) Orders() store.Orders { return orders{t.tx} }
func (t *pgTx) Payments() store.Payments { return payments{t.tx} }
func (t *pgTx) Outbox() store.Outbox { return outbox{t.tx} }
func (t *pgTx) Idempotency() store.Idempotency { return idem{t.tx} }
func notFound(err error) error {
if errors.Is(err, pgx.ErrNoRows) {
return domain.ErrNotFound
}
return err
}
// ---- products ----
type products struct{ q querier }
const productCols = `id, sku, name, coalesce(category_id, 0), price_minor, currency, tax_class, active, version, created_at`
func scanProduct(r pgx.Row) (domain.Product, error) {
var p domain.Product
var cur string
err := r.Scan(&p.ID, &p.SKU, &p.Name, &p.CategoryID, &p.Price.Amount, &cur, &p.TaxClass, &p.Active, &p.Version, &p.CreatedAt)
p.Price.Currency = money.Currency(cur)
return p, notFound(err)
}
func (r products) Get(ctx context.Context, id int64) (domain.Product, error) {
return scanProduct(r.q.QueryRow(ctx, `SELECT `+productCols+` FROM products WHERE id = $1`, id))
}
func (r products) Create(ctx context.Context, p *domain.Product) error {
err := r.q.QueryRow(ctx, `
INSERT INTO products (sku, name, category_id, price_minor, currency, tax_class, active, created_at)
VALUES ($1, $2, nullif($3, 0), $4, $5, $6, $7, $8) RETURNING id, version`,
p.SKU, p.Name, p.CategoryID, p.Price.Amount, string(p.Price.Currency), p.TaxClass, p.Active, p.CreatedAt,
).Scan(&p.ID, &p.Version)
if err != nil {
return err
}
_, err = r.q.Exec(ctx, `INSERT INTO inventory (product_id) VALUES ($1)`, p.ID)
return err
}
// Update is optimistic: no lock is held while the admin edits the form; the
// write succeeds only if nobody else wrote in between.
func (r products) Update(ctx context.Context, p *domain.Product, expected int64) error {
tag, err := r.q.Exec(ctx, `
UPDATE products SET name = $3, price_minor = $4, tax_class = $5, active = $6, version = version + 1
WHERE id = $1 AND version = $2`,
p.ID, expected, p.Name, p.Price.Amount, p.TaxClass, p.Active)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrConflict
}
p.Version = expected + 1
return nil
}
// ---- inventory ----
type inventory struct{ q querier }
func (r inventory) Get(ctx context.Context, id int64) (domain.Stock, error) {
s := domain.Stock{ProductID: id}
err := r.q.QueryRow(ctx, `SELECT on_hand, reserved FROM inventory WHERE product_id = $1`, id).Scan(&s.OnHand, &s.Reserved)
return s, notFound(err)
}
func (r inventory) SetOnHand(ctx context.Context, id, onHand int64) error {
_, err := r.q.Exec(ctx, `UPDATE inventory SET on_hand = $2, updated_at = now() WHERE product_id = $1`, id, onHand)
if code, c := pgCode(err); code == codeCheckViolation && c == constraintNoOversell {
return &domain.OutOfStockError{ProductID: id, Available: onHand}
}
return err
}
// Reserve locks every stock row of the order with SELECT ... FOR UPDATE, in
// product-id order (rs is sorted), checks availability for all of them and
// only then increments reserved. A concurrent checkout for the same product
// waits on the row lock and re-reads the committed numbers afterwards.
func (r inventory) Reserve(ctx context.Context, rs []domain.Reservation) error {
ids := make([]int64, len(rs))
for i, x := range rs {
ids[i] = x.ProductID
}
rows, err := r.q.Query(ctx, `
SELECT product_id, on_hand - reserved FROM inventory
WHERE product_id = ANY($1) ORDER BY product_id FOR UPDATE`, ids)
if err != nil {
return err
}
avail, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) ([2]int64, error) {
var v [2]int64
err := row.Scan(&v[0], &v[1])
return v, err
})
if err != nil {
return err
}
have := map[int64]int64{}
for _, v := range avail {
have[v[0]] = v[1]
}
for _, x := range rs {
if have[x.ProductID] < x.Qty {
return &domain.OutOfStockError{ProductID: x.ProductID, Wanted: x.Qty, Available: have[x.ProductID]}
}
}
return r.add(ctx, rs, 1, 0)
}
func (r inventory) Release(ctx context.Context, rs []domain.Reservation) error {
return r.add(ctx, rs, -1, 0)
}
func (r inventory) Ship(ctx context.Context, rs []domain.Reservation) error {
return r.add(ctx, rs, -1, -1)
}
func (r inventory) add(ctx context.Context, rs []domain.Reservation, reservedSign, onHandSign int64) error {
for _, x := range rs {
if _, err := r.q.Exec(ctx, `
UPDATE inventory SET reserved = reserved + $2, on_hand = on_hand + $3, updated_at = now()
WHERE product_id = $1`, x.ProductID, reservedSign*x.Qty, onHandSign*x.Qty); err != nil {
return err
}
}
return nil
}
// ---- carts ----
type carts struct{ q querier }
func (r carts) Get(ctx context.Context, id string) (domain.Cart, error) {
c := domain.Cart{ID: id}
var uid *int64
var email *string
err := r.q.QueryRow(ctx, `SELECT user_id, email, updated_at, reminded_at, version FROM carts WHERE id = $1`, id).
Scan(&uid, &email, &c.UpdatedAt, &c.RemindedAt, &c.Version)
if err != nil {
return c, notFound(err)
}
if uid != nil {
c.UserID = *uid
}
if email != nil {
c.Email = *email
}
rows, err := r.q.Query(ctx, `SELECT product_id, qty FROM cart_items WHERE cart_id = $1 ORDER BY product_id`, id)
if err != nil {
return c, err
}
c.Items, err = pgx.CollectRows(rows, pgx.RowToStructByPos[domain.CartItem])
return c, err
}
func (r carts) ForUser(ctx context.Context, userID int64) (domain.Cart, error) {
var id string
if err := r.q.QueryRow(ctx, `SELECT id FROM carts WHERE user_id = $1`, userID).Scan(&id); err != nil {
return domain.Cart{}, notFound(err)
}
return r.Get(ctx, id)
}
// Save is a compare-and-set on version. Under READ COMMITTED a concurrent
// save of the same cart makes this UPDATE wait, then re-check the WHERE
// clause against the committed row: the stale writer matches 0 rows and gets
// ErrConflict instead of replacing the items with its old snapshot. A new
// cart (version 0) is inserted; a second new cart for the same customer hits
// carts_one_per_user and is reported as a conflict too.
func (r carts) Save(ctx context.Context, c *domain.Cart) error {
var tag pgconn.CommandTag
var err error
if c.Version == 0 {
tag, err = r.q.Exec(ctx, `
INSERT INTO carts (id, user_id, email, updated_at, reminded_at, version)
VALUES ($1, nullif($2, 0), nullif($3, ''), $4, $5, 1) ON CONFLICT (id) DO NOTHING`,
c.ID, c.UserID, c.Email, c.UpdatedAt, c.RemindedAt)
} else {
tag, err = r.q.Exec(ctx, `
UPDATE carts SET user_id = nullif($3, 0), email = nullif($4, ''), updated_at = $5,
reminded_at = $6, version = version + 1
WHERE id = $1 AND version = $2`,
c.ID, c.Version, c.UserID, c.Email, c.UpdatedAt, c.RemindedAt)
}
if code, _ := pgCode(err); code == codeUniqueViolation {
return domain.ErrConflict
}
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrConflict
}
c.Version++
if _, err := r.q.Exec(ctx, `DELETE FROM cart_items WHERE cart_id = $1`, c.ID); err != nil {
return err
}
for _, it := range c.Items {
if _, err := r.q.Exec(ctx, `INSERT INTO cart_items (cart_id, product_id, qty) VALUES ($1, $2, $3)`,
c.ID, it.ProductID, it.Qty); err != nil {
return err
}
}
return nil
}
func (r carts) Delete(ctx context.Context, id string, version int64) error {
tag, err := r.q.Exec(ctx, `DELETE FROM carts WHERE id = $1 AND version = $2`, id, version)
if err == nil && tag.RowsAffected() == 0 {
return domain.ErrConflict
}
return err
}
func (r carts) Abandoned(ctx context.Context, before time.Time, limit int) ([]domain.Cart, error) {
rows, err := r.q.Query(ctx, `
SELECT c.id FROM carts c
WHERE c.user_id IS NOT NULL AND c.reminded_at IS NULL AND c.updated_at < $1
AND EXISTS (SELECT 1 FROM cart_items i WHERE i.cart_id = c.id)
ORDER BY c.updated_at LIMIT $2 FOR UPDATE SKIP LOCKED`, before, limit)
if err != nil {
return nil, err
}
ids, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
return nil, err
}
out := make([]domain.Cart, 0, len(ids))
for _, id := range ids {
c, err := r.Get(ctx, id)
if err != nil {
return nil, err
}
out = append(out, c)
}
return out, nil
}
// ---- orders ----
type orders struct{ q querier }
const orderCols = `id, user_id, email, status, subtotal_minor, discount_minor, tax_minor, total_minor, currency,
version, created_at, updated_at, expires_at`
func scanOrder(r pgx.Row) (domain.Order, error) {
var o domain.Order
var cur string
err := r.Scan(&o.ID, &o.UserID, &o.Email, &o.Status, &o.Subtotal.Amount, &o.Discount.Amount, &o.Tax.Amount,
&o.Total.Amount, &cur, &o.Version, &o.CreatedAt, &o.UpdatedAt, &o.ExpiresAt)
c := money.Currency(cur)
o.Subtotal.Currency, o.Discount.Currency, o.Tax.Currency, o.Total.Currency = c, c, c, c
return o, notFound(err)
}
func (r orders) Create(ctx context.Context, o *domain.Order) error {
_, err := r.q.Exec(ctx, `INSERT INTO orders (`+orderCols+`) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
o.ID, o.UserID, o.Email, string(o.Status), o.Subtotal.Amount, o.Discount.Amount, o.Tax.Amount, o.Total.Amount,
string(o.Total.Currency), o.Version, o.CreatedAt, o.UpdatedAt, o.ExpiresAt)
if err != nil {
return err
}
for i, it := range o.Items {
if _, err := r.q.Exec(ctx, `
INSERT INTO order_items (order_id, line, product_id, sku, name, unit_minor, qty, discount_minor, tax_minor, line_total_minor)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
o.ID, i+1, it.ProductID, it.SKU, it.Name, it.Unit.Amount, it.Qty, it.Discount.Amount, it.Tax.Amount, it.LineTotal.Amount); err != nil {
return err
}
}
return nil
}
func (r orders) Get(ctx context.Context, id string) (domain.Order, error) {
o, err := scanOrder(r.q.QueryRow(ctx, `SELECT `+orderCols+` FROM orders WHERE id = $1`, id))
if err != nil {
return o, err
}
rows, err := r.q.Query(ctx, `
SELECT product_id, sku, name, unit_minor, qty, discount_minor, tax_minor, line_total_minor
FROM order_items WHERE order_id = $1 ORDER BY line`, id)
if err != nil {
return o, err
}
cur := o.Total.Currency
o.Items, err = pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.OrderItem, error) {
var it domain.OrderItem
err := row.Scan(&it.ProductID, &it.SKU, &it.Name, &it.Unit.Amount, &it.Qty, &it.Discount.Amount, &it.Tax.Amount, &it.LineTotal.Amount)
it.Unit.Currency, it.Discount.Currency, it.Tax.Currency, it.LineTotal.Currency = cur, cur, cur, cur
return it, err
})
return o, err
}
// Update is a compare-and-set on version. Under READ COMMITTED a concurrent
// UPDATE of the same row waits, then re-checks the WHERE clause against the
// committed row: the loser matches 0 rows and gets ErrConflict.
func (r orders) Update(ctx context.Context, o *domain.Order) error {
tag, err := r.q.Exec(ctx, `UPDATE orders SET status = $2, version = $3, updated_at = $4 WHERE id = $1 AND version = $3 - 1`,
o.ID, string(o.Status), o.Version, o.UpdatedAt)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrConflict
}
return nil
}
func (r orders) ListForUser(ctx context.Context, userID int64, limit int) ([]domain.Order, error) {
rows, err := r.q.Query(ctx, `SELECT `+orderCols+` FROM orders WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2`, userID, limit)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Order, error) { return scanOrder(row) })
}
func (r orders) Expired(ctx context.Context, now time.Time, limit int) ([]domain.Order, error) {
rows, err := r.q.Query(ctx, `SELECT `+orderCols+` FROM orders WHERE status = 'created' AND expires_at < $1
ORDER BY expires_at LIMIT $2`, now, limit)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Order, error) { return scanOrder(row) })
}
// ---- payments ----
type payments struct{ q querier }
func (r payments) Create(ctx context.Context, p domain.Payment) error {
_, err := r.q.Exec(ctx, `INSERT INTO payments (id, order_id, amount_minor, currency, status, provider_key, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)`, p.ID, p.OrderID, p.Amount.Amount, string(p.Amount.Currency), string(p.Status), p.ProviderKey, p.UpdatedAt)
return err
}
func (r payments) ForOrder(ctx context.Context, orderID string) (domain.Payment, error) {
var p domain.Payment
var cur string
var ref *string
err := r.q.QueryRow(ctx, `SELECT id, order_id, amount_minor, currency, status, provider_key, provider_ref, updated_at
FROM payments WHERE order_id = $1`, orderID).
Scan(&p.ID, &p.OrderID, &p.Amount.Amount, &cur, &p.Status, &p.ProviderKey, &ref, &p.UpdatedAt)
p.Amount.Currency = money.Currency(cur)
if ref != nil {
p.ProviderRef = *ref
}
return p, notFound(err)
}
func (r payments) Update(ctx context.Context, p domain.Payment) error {
_, err := r.q.Exec(ctx, `UPDATE payments SET status = $2, provider_ref = nullif($3, ''), updated_at = $4 WHERE id = $1`,
p.ID, string(p.Status), p.ProviderRef, p.UpdatedAt)
return err
}
// ---- outbox ----
type outbox struct{ q querier }
func (r outbox) Add(ctx context.Context, evs ...domain.Event) error {
for _, e := range evs {
if _, err := r.q.Exec(ctx, `INSERT INTO outbox (event_id, type, aggregate_id, payload, occurred_at)
VALUES ($1,$2,$3,$4,$5)`, e.ID, e.Type, e.AggregateID, []byte(e.Payload), e.OccurredAt); err != nil {
return err
}
}
return nil
}
func (r outbox) Claim(ctx context.Context, limit int) ([]domain.Event, error) {
rows, err := r.q.Query(ctx, `SELECT event_id, type, aggregate_id, payload, occurred_at, attempts, next_attempt_at
FROM outbox WHERE published_at IS NULL ORDER BY seq LIMIT $1`, limit)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Event, error) {
var e domain.Event
err := row.Scan(&e.ID, &e.Type, &e.AggregateID, &e.Payload, &e.OccurredAt, &e.Attempts, &e.NextAttempt)
return e, err
})
}
func (r outbox) MarkPublished(ctx context.Context, ids []string, at time.Time) error {
_, err := r.q.Exec(ctx, `UPDATE outbox SET published_at = $2 WHERE event_id = ANY($1)`, ids, at)
return err
}
func (r outbox) MarkFailed(ctx context.Context, id string, next time.Time) error {
_, err := r.q.Exec(ctx, `UPDATE outbox SET attempts = attempts + 1, next_attempt_at = $2 WHERE event_id = $1`, id, next)
return err
}
// ---- idempotency ----
type idem struct{ q querier }
func (r idem) Get(ctx context.Context, scope, key string) (store.IdemRecord, error) {
rec := store.IdemRecord{Scope: scope, Key: key}
err := r.q.QueryRow(ctx, `SELECT fingerprint, status, body, created_at FROM idempotency_keys
WHERE scope = $1 AND key = $2 AND created_at > now() - interval '24 hours'`, scope, key).
Scan(&rec.Fingerprint, &rec.Status, &rec.Body, &rec.CreatedAt)
return rec, notFound(err)
}
// Put claims the key (first statement of the checkout after the lookup), or
// takes over a row older than the 24 h window. If a concurrent transaction
// claimed the same key and has not committed, this INSERT waits on the
// primary key; once the other commits, ON CONFLICT sees a fresh row, updates
// nothing, and we report ErrDuplicateKey: InTx re-runs the whole use case,
// whose Get now finds the winner's record. If the other rolled back, the
// INSERT proceeds and this request does the work itself.
func (r idem) Put(ctx context.Context, rec store.IdemRecord) error {
tag, err := r.q.Exec(ctx, `INSERT INTO idempotency_keys (scope, key, fingerprint, status, body, created_at)
VALUES ($1,$2,$3,$4,$5,$6)
ON CONFLICT (scope, key) DO UPDATE SET fingerprint = excluded.fingerprint, status = excluded.status,
body = excluded.body, created_at = excluded.created_at
WHERE idempotency_keys.created_at <= now() - interval '24 hours'`,
rec.Scope, rec.Key, rec.Fingerprint, rec.Status, rec.Body, rec.CreatedAt)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("%w: idempotency key %q", store.ErrDuplicateKey, rec.Key)
}
return nil
}
// ---- inbox ----
// Inbox is store.Inbox on the processed_events table.
type Inbox struct{ DB querier }
func (i Inbox) Has(ctx context.Context, consumer, id string) (bool, error) {
var ok bool
err := i.DB.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM processed_events WHERE consumer = $1 AND event_id = $2)`,
consumer, id).Scan(&ok)
return ok, err
}
func (i Inbox) Mark(ctx context.Context, consumer, id string) error {
_, err := i.DB.Exec(ctx, `INSERT INTO processed_events (consumer, event_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, consumer, id)
return err
}Place order: reserve stock, create order, record payment intent atomically Must-know
In plain words: the checkout is one transaction with seven steps; either all of them happen or none. If the customer's network drops, the stock is either reserved for an order that exists or not reserved at all.
Common misunderstanding: "Charge the card inside the checkout transaction." A PSP call takes hundreds of milliseconds to seconds, can time out with an unknown outcome, and cannot be rolled back; holding stock row locks across it serialises the whole shop behind the slowest payment. The order records the intent (amount, derived PSP key ord_...:attempt:1); the payment itself happens in the payments flow, and its result arrives as a verified event. Another: "Read the cart before the transaction to keep it short." Then the cart can change between read and reservation; read it inside.
Definition: Checkout.PlaceOrder inside InTx: (1) look up (scope, key) in idempotency_keys, replay or 422, otherwise claim the key at once with the pre-generated order id, so a concurrent duplicate blocks right here instead of doing the work; (2) read the customer's cart and each product's current price, refusing inactive products; (3) pricing.Quote; (4) reserve all lines with Inventory().Reserve, sorted; (5) insert the order (created, version 1, expires_at = now + StockHold) and its items; (6) insert the payment intent (requires_payment_method, amount = total, provider key); (7) insert order.placed:<order>:v1 into the outbox and delete the cart. Commit. Any failure rolls everything back, the key claim included, so a retry after a 409 runs again. In one line: place order: reserve stock, create order, record payment intent atomically; SELECT FOR UPDATE vs optimistic version decides how the stock step and the later status changes stay correct under concurrency.
Step Statement (pgstore) Fails with Effect of failure
1 1 SELECT ... FROM idempotency_keys WHERE scope=$1 AND key=$2 (row found) replay, nothing else runs
2 1 INSERT INTO idempotency_keys ... ON CONFLICT ... 0 rows: lost race re-run -> replay
3 2 SELECT ... FROM carts / cart_items / products ErrEmptyCart 422, nothing written
4 4 SELECT ... FROM inventory ... ORDER BY product_id FOR UPDATE OutOfStockError 409, key claim rolled back
5 5 INSERT INTO orders ...; INSERT INTO order_items ... 23505 (id clash) rollback
6 6 INSERT INTO payments ... provider_key 'ord_x:attempt:1' 23505 order_id rollback
7 7 INSERT INTO outbox ...; DELETE FROM carts ... 23505 event_id rollback
8 COMMIT 40001 / 40P01 re-run allReal scenario: 50 customers press "buy" on the last 10 units (TestNoOversellUnderConcurrency: exactly 10 orders, 40 × 409); a two-line checkout whose first line reserves and whose second runs out must leave nothing behind, stock, order, event or key claim (TestMultiLineCheckoutRollsBackEarlierReservations), and a failure late in the transaction must release stock reserved a few statements earlier (TestLateFailureRollsBackReservation); a client times out after commit and retries (replay); the process is killed between step 6 and commit (nothing happened, the client's retry creates the order).
| Approach | Atomic? | Lock time | Payment risk |
|---|---|---|---|
| One transaction, intent only (this project) | yes | ms | none: the PSP call is elsewhere, with a derived key |
| Transaction + PSP call inside | yes, until the PSP times out | seconds | unknown outcome while holding locks |
| Reserve in one tx, order in another | no | ms | stock leaks on crash |
| Saga across inventory/order/payment services | eventually, with compensations | ms per step | needs compensations and idempotent steps (Payment Processing Architecture) |
Fix / how to use it: the service is the After snippet; the table-driven tests below prove the atomicity, the replay and the concurrency claim.
package service
import (
"context"
"errors"
"strconv"
"sync"
"testing"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/store"
)
func TestPlaceOrder(t *testing.T) {
tests := []struct {
name string
stock int64
qty int64
discount string
wantErr error
total int64
}{
{"happy path", 5, 2, "", nil, 2 * 1000 * 12 / 10},
{"discount code", 5, 2, "TEN", nil, 1800 * 12 / 10},
{"unknown discount is ignored", 5, 1, "NOPE", nil, 1200},
{"out of stock", 1, 2, "", &domain.OutOfStockError{}, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := newFixture(t)
id := f.product(t, "MUG", 1000, tt.stock)
if _, err := f.carts.SetItem(t.Context(), Owner{Principal: alice}, id, tt.qty); err != nil {
t.Fatal(err)
}
res, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice,
IdempotencyKey: "key-" + tt.name, Fingerprint: "fp", DiscountCode: tt.discount})
if tt.wantErr != nil {
var oos *domain.OutOfStockError
if !errors.As(err, &oos) {
t.Fatalf("want out of stock, got %v", err)
}
if s := f.stock(t, id); s.Reserved != 0 {
t.Fatalf("failed checkout left %d reserved", s.Reserved)
}
if len(f.store.Unpublished()) != 0 {
t.Fatal("failed checkout wrote an event")
}
return
}
if err != nil {
t.Fatal(err)
}
o := res.Order
if o.Status != domain.OrderCreated || o.Total.Amount != tt.total {
t.Fatalf("status %s total %d, want created %d", o.Status, o.Total.Amount, tt.total)
}
if res.Payment.ProviderKey != o.ID+":attempt:1" || res.Payment.Amount != o.Total {
t.Fatalf("payment %+v", res.Payment)
}
if s := f.stock(t, id); s.Reserved != tt.qty {
t.Fatalf("reserved %d", s.Reserved)
}
evs := f.store.Unpublished()
if len(evs) != 1 || evs[0].Type != domain.EvOrderPlaced || evs[0].ID != "order.placed:"+o.ID+":v1" {
t.Fatalf("outbox %v", evs)
}
if _, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "another-key"}); !errors.Is(err, domain.ErrEmptyCart) {
t.Fatalf("cart must be empty after checkout, got %v", err)
}
})
}
}
func TestPlaceOrderIsIdempotent(t *testing.T) {
f := newFixture(t)
id := f.product(t, "MUG", 1000, 5)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, id, 1)
in := PlaceOrderInput{Who: alice, IdempotencyKey: "8e03c2d1-retry", Fingerprint: "sha256:aaa"}
first, err := f.checkout.PlaceOrder(t.Context(), in)
if err != nil {
t.Fatal(err)
}
again, err := f.checkout.PlaceOrder(t.Context(), in)
if err != nil || !again.Replayed || again.Order.ID != first.Order.ID {
t.Fatalf("retry: %+v %v", again, err)
}
if s := f.stock(t, id); s.Reserved != 1 {
t.Fatalf("retry reserved again: %d", s.Reserved)
}
in.Fingerprint = "sha256:bbb"
if _, err := f.checkout.PlaceOrder(t.Context(), in); !errors.Is(err, ErrIdempotencyMismatch) {
t.Fatalf("other body, same key: %v", err)
}
// The key is scoped per user: Bob may use the same string.
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: bob}, id, 1)
if r, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: bob, IdempotencyKey: in.IdempotencyKey}); err != nil || r.Replayed {
t.Fatalf("bob: %+v %v", r, err)
}
}
// 50 customers race for the last 10 units: exactly 10 orders, never 11.
func TestNoOversellUnderConcurrency(t *testing.T) {
f := newFixture(t)
id := f.product(t, "LAST", 500, 10)
var wg sync.WaitGroup
var mu sync.Mutex
ok, oos := 0, 0
for i := range 50 {
u := domain.Principal{UserID: int64(100 + i), Role: domain.RoleCustomer}
if _, err := f.carts.SetItem(t.Context(), Owner{Principal: u}, id, 1); err != nil {
t.Fatal(err)
}
wg.Add(1)
go func() {
defer wg.Done()
_, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: u, IdempotencyKey: "checkout-" + strconv.Itoa(i)})
mu.Lock()
defer mu.Unlock()
var e *domain.OutOfStockError
switch {
case err == nil:
ok++
case errors.As(err, &e):
oos++
default:
t.Error(err)
}
}()
}
wg.Wait()
if ok != 10 || oos != 40 {
t.Fatalf("ok %d out-of-stock %d", ok, oos)
}
if s := f.stock(t, id); s.Reserved != 10 || s.Available() != 0 {
t.Fatalf("stock %+v", s)
}
}
func TestOnlyCustomersPlaceOrders(t *testing.T) {
f := newFixture(t)
_, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{IdempotencyKey: "anonymous-key"})
if !errors.Is(err, domain.ErrForbidden) {
t.Fatalf("got %v", err)
}
var v *ValidationError
if _, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "short"}); !errors.As(err, &v) {
t.Fatalf("short key: %v", err)
}
}
// The first line reserves successfully, the second runs out: nothing of the
// checkout may survive (reservation, order, payment, outbox, key claim).
func TestMultiLineCheckoutRollsBackEarlierReservations(t *testing.T) {
f := newFixture(t)
a := f.product(t, "A", 1000, 5)
b := f.product(t, "B", 1000, 1)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, a, 2)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, b, 2)
in := PlaceOrderInput{Who: alice, IdempotencyKey: "multi-line-1", Fingerprint: "fp"}
var oos *domain.OutOfStockError
if _, err := f.checkout.PlaceOrder(t.Context(), in); !errors.As(err, &oos) || oos.ProductID != b {
t.Fatalf("got %v", err)
}
if s := f.stock(t, a); s.Reserved != 0 {
t.Fatalf("line A still reserved: %+v", s)
}
if len(f.store.Unpublished()) != 0 {
t.Fatal("event written by a failed checkout")
}
if c, _ := f.carts.Get(t.Context(), Owner{Principal: alice}); len(c.Items) != 2 {
t.Fatalf("cart lost: %v", c.Items)
}
// The key claim rolled back too: after a restock the same key places the order.
if err := f.store.InTx(t.Context(), func(ctx context.Context, tx store.Tx) error {
return tx.Inventory().SetOnHand(ctx, b, 5)
}); err != nil {
t.Fatal(err)
}
if r, err := f.checkout.PlaceOrder(t.Context(), in); err != nil || r.Replayed {
t.Fatalf("after restock: %+v %v", r, err)
}
}
// A write late in the transaction fails (order id clash): the stock reserved
// a few statements earlier must be released by the rollback.
func TestLateFailureRollsBackReservation(t *testing.T) {
f := newFixture(t)
a := f.product(t, "A", 1000, 5)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, a, 1)
first, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "late-fail-1"})
if err != nil {
t.Fatal(err)
}
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, a, 2)
c := f.checkout
c.NewID = func(string) string { return first.Order.ID } // forces 23505-like duplicate on orders
if _, err := c.PlaceOrder(t.Context(), PlaceOrderInput{Who: alice, IdempotencyKey: "late-fail-2"}); !errors.Is(err, store.ErrDuplicateKey) {
t.Fatalf("got %v", err)
}
if s := f.stock(t, a); s.Reserved != 1 {
t.Fatalf("reserved %d, want only the first order's 1", s.Reserved)
}
}Idempotent order placement: the Idempotency-Key Must-know
In plain words: the app sends a fresh random key with each checkout attempt and the same key on every retry of that attempt. The server stores "this key produced order X" in the same transaction as the order, so a retry gets order X back instead of a second order.
Common misunderstanding: "Store the key in Redis before the work, then do the work." If the work fails or the process dies, the key says "in progress" or "done" for an order that does not exist. Writing the record in the checkout transaction makes "key stored" and "order exists" the same fact. Another: "The same key from another user is a replay." Keys are scoped (POST /v1/orders user:7); Bob's key that happens to equal Alice's is a new request. A third: "Reuse the client's key for the PSP." The PSP key is derived from the order (ord_x:attempt:1), so a restarted payment worker sends the same one; see the two-keys rule in Payment Processing Architecture.
Definition: the IETF draft: "The idempotency key MUST be unique and MUST NOT be reused with another request with a different request payload", and "If the request is retried, while the original request is still being processed, the resource SHOULD reply with an HTTP 409". Stripe API v1: the first response is saved and "Retries with the same key return the saved response"; keys "are up to 255 characters long"; "you can remove keys from the system automatically after they’re at least 24 hours old". Here: the header is required (400 without it), 8–255 characters; the fingerprint is SHA-256 of the raw body; a different fingerprint is 422 idempotency-key-reused; the record lives 24 h (created_at > now() - interval '24 hours', and an expired row is taken over by ON CONFLICT ... DO UPDATE ... WHERE created_at <= now() - interval '24 hours'). The key is claimed right after the lookup, before any other work, and the claim shares the checkout transaction: a concurrent duplicate's INSERT waits on the primary key, and when the first commits the re-run replays (if the first rolled back, the duplicate does the work itself). Claiming late, after the stock step, would be a bug: the duplicate would wait on the stock row instead and answer 409 out of stock, or 422 empty cart, for an order that exists. Only if the wait exceeds lock_timeout does the duplicate get 409 busy with Retry-After: 1. The replay returns the order as it is now (it may already be paid) with Idempotent-Replayed: true, a deliberate simplification of Stripe's byte-for-byte replay; the generic middleware that stores response bytes is in A REST API in Go.
Client Tx 1 (first attempt) Tx 2 (retry, same key)
1 POST key=K body=B
2 BEGIN; idem K? no; INSERT idem K (claim)
3 reserve last unit; insert order ...
4 (timeout, retries) BEGIN; idem K? no (Tx 1 not committed)
5 INSERT idem K: waits on Tx 1's key
6 COMMIT -> 201 (response lost)
7 ON CONFLICT: fresh row, 0 rows -> ErrDuplicateKey
8 InTx re-runs: idem K? yes -> replay order
9 <- 201 same order, Idempotent-Replayed: true (never "out of stock" for its own unit)Real scenario: a double tap on "Place order"; a mobile app that retries after switching from Wi-Fi to 4G; a load balancer that returns 504 while the backend commits; a script that resends a batch after a crash; a client bug that reuses one key for two different carts (422).
| Case | Status | Body | Stored? |
|---|---|---|---|
| No header | 400 | idempotency-key-missing | no |
| Key shorter than 8 or longer than 255 | 422 | validation | no |
| First request succeeds | 201 | order | yes, with the order |
| Same key, same body | 201 + Idempotent-Replayed: true | same order (current state) | no change |
| Same key, other body | 422 | idempotency-key-reused | no change |
Same key while the first runs longer than lock_timeout | 409 + Retry-After: 1 | busy | no |
| First request fails (out of stock) | 409 | out-of-stock | no: the transaction rolled back, a retry runs again |
| After 24 h | treated as new | row replaced |
Fix / how to use it: the key handling is step 1 of PlaceOrder; the adapter side is idem.Get/idem.Put in repos.go; TestPlaceOrderIsIdempotent and the integration test TestSameIdempotencyKeyConcurrentlyCreatesOneOrder prove it.
Order state machine Must-know
In plain words: an order's status can only move along a few arrows. Anything that tries another move (a late webhook, a double click on "ship", a cancel after payment) gets "not allowed in the current status" instead of silently overwriting what happened.
Common misunderstanding: "Status is a column; set it to what the event says." Stripe "doesn’t guarantee the delivery of events in the order that they’re generated"; blindly applying the last event can turn a paid order back into pending. Another: "Cancel and refund are the same." Before payment, cancelling releases stock and nothing else; after payment, money moved, so the order is refunded (a money movement) and never cancelled. Third: "One status column for order and payment." They are two machines; the payment mirrors the PSP's PaymentIntent (whose failed attempt "returns to requires_payment_method so that the payment can be retried"), the order mirrors the business.
Definition: domain.OrderStatus with edges created → paid | cancelled, paid → fulfilled | refunded, fulfilled → refunded; cancelled and refunded are terminal. Order.Transition(to, now) returns ErrInvalidTransition for anything else and bumps Version, and the repository writes with WHERE version = $new - 1. Each transition writes an event in the same transaction, with the id <type>:<order>:v<version>, so a re-run of the same transition produces the same event id. PaymentStatus is requires_payment_method, succeeded, canceled, refund_pending, refunded.
Event (arrival order) Order before Payment before Result
1 order placed - - created v1, requires_payment_method
2 payment_intent.succeeded (evt_1) created v1 requires_payment_method paid v2, succeeded, payment.captured:ord:v2
3 payment_intent.succeeded (evt_1 again) paid v2 succeeded no-op, 204 to the PSP
4 customer cancel paid v2 succeeded 409 invalid transition
5 admin fulfil paid v2 succeeded fulfilled v3, stock shippedReal scenario: a webhook redelivered three times; a customer cancelling while the payment is being captured (one wins by version, the other re-reads); the stock-release job cancelling an order whose payment arrives one second later (payment becomes refund_pending, see workers); an admin fulfilling an unpaid order by mistake (409).
| Current | paid | fulfilled | cancelled | refunded |
|---|---|---|---|---|
created | yes (capture) | no | yes (customer, timeout) | no |
paid | (duplicate: no-op) | yes (admin) | no: refund instead | yes |
fulfilled | no | (duplicate) | no | yes (return) |
cancelled | no: late capture → refund | no | (duplicate) | no |
refunded | no | no | no | (duplicate) |
Fix / how to use it: the transition table is in domain/order.go above; the services apply it.
package service
import (
"context"
"errors"
"strconv"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
)
// Orders reads and moves orders after checkout.
type Orders struct{ Deps }
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
// Get returns the order if who may see it. A customer asking for someone
// else's order gets ErrNotFound, not ErrForbidden: do not confirm it exists.
func (s Orders) Get(ctx context.Context, who domain.Principal, id string) (domain.Order, error) {
var o domain.Order
err := s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
o, err = tx.Orders().Get(ctx, id)
return err
})
if err == nil && !who.CanSee(o.UserID) {
return domain.Order{}, domain.ErrNotFound
}
return o, err
}
// List returns the caller's latest orders.
func (s Orders) List(ctx context.Context, who domain.Principal) ([]domain.Order, error) {
var out []domain.Order
err := s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
out, err = tx.Orders().ListForUser(ctx, who.UserID, 50)
return err
})
return out, err
}
// Cancel cancels an unpaid order and releases its stock exactly once (the
// version check makes a concurrent cancel or payment lose and retry).
func (s Orders) Cancel(ctx context.Context, who domain.Principal, id string) (domain.Order, error) {
var o domain.Order
err := retryConflict(func() error {
return s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if o, err = tx.Orders().Get(ctx, id); err != nil {
return err
}
if !who.CanSee(o.UserID) {
return domain.ErrNotFound
}
return cancelInTx(ctx, tx, &o, s.Now(), "customer")
})
})
return o, err
}
func cancelInTx(ctx context.Context, tx Tx, o *domain.Order, now timeT, reason string) error {
if err := o.Transition(domain.OrderCancelled, now); err != nil {
return err
}
if err := tx.Orders().Update(ctx, o); err != nil {
return err
}
if err := tx.Inventory().Release(ctx, o.Reservations()); err != nil {
return err
}
if p, err := tx.Payments().ForOrder(ctx, o.ID); err == nil && p.Status == domain.PaymentRequiresMethod {
p.Status, p.UpdatedAt = domain.PaymentCanceled, now
if err := tx.Payments().Update(ctx, p); err != nil {
return err
}
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvOrderCancelled, o.ID, o.Version, now,
map[string]string{"order_id": o.ID, "reason": reason}))
}
// Fulfil marks a paid order shipped (admin) and turns reservations into shipments.
func (s Orders) Fulfil(ctx context.Context, who domain.Principal, id string) (domain.Order, error) {
if err := requireAdmin(who); err != nil {
return domain.Order{}, err
}
var o domain.Order
err := retryConflict(func() error {
return s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if o, err = tx.Orders().Get(ctx, id); err != nil {
return err
}
now := s.Now()
if err := o.Transition(domain.OrderFulfilled, now); err != nil {
return err
}
if err := tx.Orders().Update(ctx, &o); err != nil {
return err
}
if err := tx.Inventory().Ship(ctx, o.Reservations()); err != nil {
return err
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvOrderFulfilled, o.ID, o.Version, now,
map[string]string{"order_id": o.ID}))
})
})
return o, err
}
// PSPEvent is a verified payment event (signature already checked by the
// webhook handler; see the payment-processing chapter for that part).
type PSPEvent struct {
EventID string
Type string // "payment_intent.succeeded" | "payment_intent.payment_failed"
OrderID string
ProviderRef string
Amount money.Money
}
// ApplyPayment records a PSP event. Duplicates and late events are no-ops;
// a capture that arrives after the order was cancelled (the stock-release
// timeout won) does not resurrect the order: it asks for a refund instead.
func (s Orders) ApplyPayment(ctx context.Context, ev PSPEvent) (domain.Order, error) {
var o domain.Order
err := retryConflict(func() error {
return s.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if o, err = tx.Orders().Get(ctx, ev.OrderID); err != nil {
return err
}
p, err := tx.Payments().ForOrder(ctx, o.ID)
if err != nil {
return err
}
if ev.Type != "payment_intent.succeeded" || (p.Status != domain.PaymentRequiresMethod && p.Status != domain.PaymentCanceled) {
return nil // failure (stays retryable at the PSP), duplicate or late: ack and ignore
}
if ev.Amount != p.Amount {
return ErrAmountMismatch
}
now := s.Now()
p.ProviderRef, p.UpdatedAt = ev.ProviderRef, now
if o.Status == domain.OrderCancelled {
p.Status = domain.PaymentRefundPending
if err := tx.Payments().Update(ctx, p); err != nil {
return err
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvRefundRequested, p.ID, 1, now,
domain.PaymentCaptured{OrderID: o.ID, PaymentID: p.ID, Amount: p.Amount.Amount}))
}
if err := o.Transition(domain.OrderPaid, now); err != nil {
return err
}
p.Status = domain.PaymentSucceeded
if err := tx.Orders().Update(ctx, &o); err != nil {
return err
}
if err := tx.Payments().Update(ctx, p); err != nil {
return err
}
return tx.Outbox().Add(ctx, domain.NewEvent(domain.EvPaymentCaptured, o.ID, o.Version, now,
domain.PaymentCaptured{OrderID: o.ID, PaymentID: p.ID, Amount: p.Amount.Amount}))
})
})
return o, err
}
// retryConflict re-runs fn when an optimistic version check lost.
func retryConflict(fn func() error) error {
var err error
for range 3 {
if err = fn(); !errors.Is(err, domain.ErrConflict) {
return err
}
}
return err
}Cart: server-side cart table vs session, merging guest cart on login Must-know
In plain words: the cart lives in the database, identified by a random token in a cookie for guests and by the user id for customers. It holds products and quantities only, never prices. When a guest logs in, their guest cart is folded into the customer's cart and deleted.
Common misunderstanding: "Keep the cart in the session (or a JWT, or localStorage)." A session cart disappears when the session store is flushed or the user switches device, cannot be seen by the abandoned-cart job, and in a client-side token can be edited by the user, including prices if you were tempted to store them. The other: "Store the price in the cart line so the checkout is faster." Then the cart shows a price that is no longer true; the checkout reads current prices anyway, inside the transaction.
Definition: carts (id TEXT PRIMARY KEY, user_id BIGINT NULL, email, updated_at, reminded_at) with a partial unique index so a customer has at most one cart, a version column, and cart_items (cart_id, product_id, qty 1..10). Every save is a compare-and-set: UPDATE carts SET ..., version = version + 1 WHERE id = $1 AND version = $2, then the items are replaced. Without it two tabs adding items at once lose one: both read [A], one saves [A, B], the other saves its stale [A, C] and B is gone. With it the stale writer matches 0 rows (under READ COMMITTED it waits for the first, then re-checks the WHERE clause), gets ErrConflict, and SetItem re-reads and applies its change again; memstore models the same race in TestCartSaveRejectsStaleSnapshot. The checkout deletes the cart with the same version check, so an item added while the order is being placed makes the checkout re-run instead of vanishing. The guest token is 128 random bits (service.RandomID), set as cart_id with HttpOnly, Secure, SameSite=Lax, Path=/, 30 days. Carts.MergeOnLogin(guestID, principal) sums quantities per product, caps each at MaxQtyPerLine (10), saves the customer cart, deletes the guest cart, and refuses to merge a cart that already belongs to a user (so a guessed customer cart id cannot be stolen). The login handler calls it right after the session or token is issued; the client calls POST /v1/cart/merge in this project.
Browser Server
1 PUT /v1/cart/items/1 {"qty":3} (no auth) new cart_9f.. saved, Set-Cookie: cart_id=cart_9f..; HttpOnly; Secure
2 GET /v1/cart (cookie) cart_9f..: [1 x 3]
3 POST /login session / JWT issued (authentication chapter)
4 POST /v1/cart/merge (cookie + bearer) customer cart: [1 x 9] + [1 x 3] -> [1 x 10] (cap), guest cart deleted
5 Set-Cookie: cart_id=; Max-Age=0Real scenario: a guest fills the cart on a phone, logs in on the same phone and expects the items to stay; a customer who already had items from last week; a shared computer where the next guest must not see the previous customer's cart; a reminder mail to customers who left items for 24 hours.
| Storage | Survives login | Survives device switch | Visible to jobs | Tamper-proof | Cost |
|---|---|---|---|---|---|
| Server-side table (this project) | yes, merge | yes, for customers | yes | yes | one table, a cookie |
Server session (Redis, scs) | only if the session is kept | no | hard | yes | session store |
| Signed cookie or JWT | needs merge logic | no | no | signed, but size-limited | none |
localStorage + API only at checkout | needs merge | no | no | no (client edits) | none |
| Redis hash per cart | yes, with merge | yes | yes (scan) | yes | TTL tuning, second store |
Fix / how to use it:
package service
import (
"context"
"errors"
"academy/ecommerce-api-project/domain"
)
// Carts manages server-side carts. A guest is identified by an opaque cart
// id (cookie); a signed-in customer by user id.
type Carts struct{ Deps }
// Owner is whoever the cart belongs to: a principal, a guest cart id, or both
// (during login, when the guest cart is merged).
type Owner struct {
Principal domain.Principal
GuestID string
}
func (c Carts) load(ctx context.Context, tx Tx, o Owner) (domain.Cart, error) {
if o.Principal.UserID != 0 {
cart, err := tx.Carts().ForUser(ctx, o.Principal.UserID)
if errors.Is(err, domain.ErrNotFound) {
return domain.Cart{ID: c.NewID("cart"), UserID: o.Principal.UserID, Email: o.Principal.Email}, nil
}
return cart, err
}
if o.GuestID != "" {
cart, err := tx.Carts().Get(ctx, o.GuestID)
if err == nil && cart.UserID == 0 {
return cart, nil
}
if err != nil && !errors.Is(err, domain.ErrNotFound) {
return domain.Cart{}, err
}
}
return domain.Cart{ID: c.NewID("cart")}, nil // new guest cart; the handler sets the cookie
}
// Get returns the cart (possibly new and empty, not yet saved).
func (c Carts) Get(ctx context.Context, o Owner) (domain.Cart, error) {
var cart domain.Cart
err := c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
cart, err = c.load(ctx, tx, o)
return err
})
return cart, err
}
// SetItem sets the quantity of one product (0 removes it).
func (c Carts) SetItem(ctx context.Context, o Owner, productID, qty int64) (domain.Cart, error) {
if qty < 0 || qty > domain.MaxQtyPerLine {
return domain.Cart{}, &ValidationError{Fields: []FieldError{{"qty", "between 0 and 10"}}}
}
var cart domain.Cart
// The cart is read and saved with a version check, so two tabs adding
// items at once cannot lose one; the loser re-reads and applies again.
err := retryConflict(func() error {
return c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
p, err := tx.Products().Get(ctx, productID)
if err != nil {
return err
}
if !p.Active {
return domain.ErrInactiveProduct
}
if cart, err = c.load(ctx, tx, o); err != nil {
return err
}
cart.Set(productID, qty, c.Now())
return tx.Carts().Save(ctx, &cart)
})
})
return cart, err
}
// MergeOnLogin moves the guest cart into the customer's cart and deletes it.
// Called by the login handler right after the session or token is issued.
func (c Carts) MergeOnLogin(ctx context.Context, guestID string, who domain.Principal) (domain.Cart, error) {
var cart domain.Cart
err := retryConflict(func() error {
return c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if cart, err = c.load(ctx, tx, Owner{Principal: who}); err != nil {
return err
}
guest, err := tx.Carts().Get(ctx, guestID)
if errors.Is(err, domain.ErrNotFound) || (err == nil && guest.UserID != 0) {
return nil // nothing to merge, or not a guest cart: never steal a customer's cart
}
if err != nil {
return err
}
cart.Merge(guest, c.Now())
if err := tx.Carts().Save(ctx, &cart); err != nil {
return err
}
return tx.Carts().Delete(ctx, guest.ID, guest.Version)
})
})
return cart, err
}Catalogue listing: pagination/filter/sort for catalogue, keyset, search Must-know
In plain words: the catalogue is read thousands of times more often than it is written. Page it with a cursor that says "after this row", filter and sort only on whitelisted fields backed by indexes, and start search with ILIKE, moving to full-text search when it matters.
Common misunderstanding: "LIMIT 20 OFFSET 2000 is fine." The database still reads and throws away 2,000 rows, and a product inserted while the user pages shows up twice or not at all; Use The Index, Luke's "no offset" page and Pagination explain why. Another: "Let the client pass the sort column." ORDER BY cannot be a bind parameter, so the column ends up concatenated into SQL; map a small set of names to fixed strings instead. Third: "ILIKE '%term%' uses the B-tree index." It does not; with a leading wildcard a plain B-tree cannot help (the pg_trgm extension's GIN or GiST trigram indexes can).
Definition: GET /v1/products?q=&category=&min_price=&max_price=&sort=newest|price|-price|name&limit=1..100&cursor=. service.Catalog.List validates everything into a domain.ProductQuery, asks for limit + 1 rows to know whether a next page exists, and returns next_cursor, an opaque base64url JSON of {sort, value, id}; a cursor issued for one sort is refused for another. pgstore.listSQL turns the cursor into a row comparison, e.g. (price_minor, id) > ($2, $3) ORDER BY price_minor, id LIMIT $4, backed by products_price (price_minor, id) WHERE active. Search is (name ILIKE $1 OR sku ILIKE $1) with %, _ and \ escaped; with FullText on it is search @@ websearch_to_tsquery('simple', $1) against the generated tsvector column and its GIN index. That is the ILIKE/tsvector pointer: start with ILIKE for a few thousand products, move to tsvector (stemming, ranking with ts_rank) or pg_trgm (typo tolerance) when search becomes a feature, and to OpenSearch, Meilisearch or Typesense when it becomes a product. The handler also sends Link: <...cursor=...>; rel="next".
Page Request SQL predicate Returns
1 1 ?sort=price&limit=2 active 100, 200 (+1 probe row) next_cursor=c1
2 2 ?sort=price&limit=2&cursor=c1 active AND (price_minor, id) > (200, 2) 300, 400 next_cursor=c2
3 - admin inserts a product at 150 (page 2 already read) no duplicate, no gap after the cursor
4 3 ?sort=price&limit=2&cursor=c2 active AND (price_minor, id) > (400, 4) 500, no next_cursor
5 - ?sort=name&cursor=c2 cursor sort != name 422 cursor invalidReal scenario: an infinite-scroll mobile catalogue; a "price low to high" listing in one category; search for "go book" that must find "The Go Programming Book"; a crawler hammering page 10,000 (keyset makes it as cheap as page 1).
| Need | This project | Next step | Index |
|---|---|---|---|
| Paging | keyset with opaque cursor | same | (sort_col, id) WHERE active per sort |
| Filter by category, price | whitelisted params | faceted counts in a search engine | (category_id, created_at DESC, id DESC) |
| Sort | 4 fixed orders | per-locale collations | one per order; name COLLATE "C" here |
| Substring search | ILIKE with escaped wildcards | pg_trgm GIN | none (seq scan) / trigram |
| Word search | tsvector generated column (FullText) | weights, ts_rank, synonyms | GIN on search |
| Relevance, typos, facets at scale | OpenSearch / Meilisearch / Typesense via the outbox | external |
Fix / how to use it: the validation and cursor code, then the SQL builder.
package service
import (
"context"
"encoding/base64"
"encoding/json"
"strconv"
"strings"
"time"
"academy/ecommerce-api-project/domain"
)
// Catalog lists and manages products.
type Catalog struct{ Deps }
// ListParams is the raw query string, as strings, before validation.
type ListParams struct {
Search, Category, MinPrice, MaxPrice, Sort, Limit, Cursor string
}
// Page is one keyset page.
type Page struct {
Items []domain.Product
NextCursor string // empty on the last page
}
var sorts = map[string]domain.SortField{"": domain.SortNewest, "newest": domain.SortNewest,
"price": domain.SortPriceAsc, "-price": domain.SortPriceDesc, "name": domain.SortName}
// List validates the parameters, then asks the store for Limit+1 rows: the
// extra row only tells us whether there is a next page.
func (c Catalog) List(ctx context.Context, in ListParams) (Page, error) {
q, err := parseList(in)
if err != nil {
return Page{}, err
}
limit := q.Limit
q.Limit++
rows, err := c.Store.Catalog().ListProducts(ctx, q)
if err != nil {
return Page{}, err
}
p := Page{Items: rows}
if len(rows) > limit {
p.Items = rows[:limit]
p.NextCursor = EncodeCursor(cursorFor(q.Sort, p.Items[limit-1]))
}
return p, nil
}
func parseList(in ListParams) (domain.ProductQuery, error) {
var v ValidationError
q := domain.ProductQuery{Search: strings.TrimSpace(in.Search), Limit: 20}
if len(q.Search) > 100 {
v.add("q", "at most 100 characters")
}
s, ok := sorts[in.Sort]
if !ok {
v.add("sort", "one of newest, price, -price, name")
}
q.Sort = s
num := func(field, raw string, lo, hi int64) int64 {
if raw == "" {
return 0
}
n, err := strconv.ParseInt(raw, 10, 64)
if err != nil || n < lo || n > hi {
v.add(field, "integer between %d and %d", lo, hi)
}
return n
}
q.CategoryID = num("category", in.Category, 1, 1<<53)
q.MinPrice = num("min_price", in.MinPrice, 0, 1<<53)
q.MaxPrice = num("max_price", in.MaxPrice, 0, 1<<53)
if l := num("limit", in.Limit, 1, 100); l > 0 {
q.Limit = int(l)
}
if q.MaxPrice > 0 && q.MinPrice > q.MaxPrice {
v.add("min_price", "must not exceed max_price")
}
if in.Cursor != "" {
c, err := DecodeCursor(in.Cursor)
if err != nil || c.Sort != q.Sort {
v.add("cursor", "invalid or issued for another sort order")
} else {
q.After = &c
}
}
return q, v.orNil()
}
func cursorFor(s domain.SortField, p domain.Product) domain.Cursor {
c := domain.Cursor{Sort: s, ID: p.ID}
switch s {
case domain.SortPriceAsc, domain.SortPriceDesc:
c.Value = strconv.FormatInt(p.Price.Amount, 10)
case domain.SortName:
c.Value = p.Name
default:
c.Value = p.CreatedAt.UTC().Format(time.RFC3339Nano)
}
return c
}
// EncodeCursor makes the opaque next_cursor string (base64url JSON).
func EncodeCursor(c domain.Cursor) string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
// DecodeCursor reverses EncodeCursor.
func DecodeCursor(s string) (domain.Cursor, error) {
var c domain.Cursor
b, err := base64.RawURLEncoding.DecodeString(s)
if err == nil {
err = json.Unmarshal(b, &c)
}
return c, err
}
// Get returns one active product.
func (c Catalog) Get(ctx context.Context, id int64) (domain.Product, error) {
return c.Store.Catalog().GetProduct(ctx, id)
}
// ProductInput is the admin create/update body.
type ProductInput struct {
SKU, Name, TaxClass string
CategoryID int64
Price int64 // minor units
Stock int64
}
func (in ProductInput) validate(rates map[string]int64) error {
var v ValidationError
if in.SKU == "" || len(in.SKU) > 32 {
v.add("sku", "1 to 32 characters")
}
if in.Name == "" || len(in.Name) > 200 {
v.add("name", "1 to 200 characters")
}
if in.Price <= 0 {
v.add("price", "positive amount in minor units")
}
if _, ok := rates[in.TaxClass]; !ok {
v.add("tax_class", "unknown tax class")
}
if in.Stock < 0 {
v.add("stock", "must not be negative")
}
return v.orNil()
}
// CreateProduct is admin-only.
func (c Catalog) CreateProduct(ctx context.Context, who domain.Principal, in ProductInput) (domain.Product, error) {
if err := requireAdmin(who); err != nil {
return domain.Product{}, err
}
if err := in.validate(c.TaxRates); err != nil {
return domain.Product{}, err
}
p := domain.Product{SKU: in.SKU, Name: in.Name, CategoryID: in.CategoryID, TaxClass: in.TaxClass,
Price: c.money(in.Price), Active: true, CreatedAt: c.Now()}
err := c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
if err := tx.Products().Create(ctx, &p); err != nil {
return err
}
return tx.Inventory().SetOnHand(ctx, p.ID, in.Stock)
})
return p, err
}
// UpdatePrice changes a price if nobody else changed the product since the
// admin loaded it (version from the ETag / request body).
func (c Catalog) UpdatePrice(ctx context.Context, who domain.Principal, id, price, version int64) (domain.Product, error) {
if err := requireAdmin(who); err != nil {
return domain.Product{}, err
}
if price <= 0 {
return domain.Product{}, &ValidationError{Fields: []FieldError{{"price", "positive amount in minor units"}}}
}
var p domain.Product
err := c.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
var err error
if p, err = tx.Products().Get(ctx, id); err != nil {
return err
}
p.Price = c.money(price)
return tx.Products().Update(ctx, &p, version)
})
return p, err
}package pgstore
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/jackc/pgx/v5"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/store"
)
// Catalog returns the read side (it runs on the pool, outside transactions).
func (s *Store) Catalog() store.Catalog { return catalog{q: s.reader, fullText: s.FullText} }
type catalog struct {
q querier
fullText bool
}
func (c catalog) GetProduct(ctx context.Context, id int64) (domain.Product, error) {
return scanProduct(c.q.QueryRow(ctx, `SELECT `+productCols+` FROM products WHERE id = $1 AND active`, id))
}
func (c catalog) ListProducts(ctx context.Context, q domain.ProductQuery) ([]domain.Product, error) {
sql, args := listSQL(q, c.fullText)
rows, err := c.q.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Product, error) { return scanProduct(row) })
}
// order maps a sort field to its ORDER BY and keyset comparison. Only these
// four strings ever reach the SQL: user input picks a key, never a column.
var order = map[domain.SortField]struct{ by, cmp, col string }{
domain.SortNewest: {"created_at DESC, id DESC", "<", "created_at"},
domain.SortPriceAsc: {"price_minor, id", ">", "price_minor"},
domain.SortPriceDesc: {"price_minor DESC, id DESC", "<", "price_minor"},
domain.SortName: {"name COLLATE \"C\", id", ">", "name COLLATE \"C\""},
}
// listSQL builds the keyset query. Every value is a $n parameter.
func listSQL(q domain.ProductQuery, fullText bool) (string, []any) {
var where []string
var args []any
arg := func(v any) string { args = append(args, v); return "$" + strconv.Itoa(len(args)) }
where = append(where, "active")
if q.CategoryID != 0 {
where = append(where, "category_id = "+arg(q.CategoryID))
}
if q.MinPrice > 0 {
where = append(where, "price_minor >= "+arg(q.MinPrice))
}
if q.MaxPrice > 0 {
where = append(where, "price_minor <= "+arg(q.MaxPrice))
}
if q.Search != "" {
if fullText {
where = append(where, "search @@ websearch_to_tsquery('simple', "+arg(q.Search)+")")
} else {
p := arg("%" + escapeLike(q.Search) + "%")
where = append(where, "(name ILIKE "+p+" OR sku ILIKE "+p+")")
}
}
o, ok := order[q.Sort]
if !ok {
o = order[domain.SortNewest]
}
if c := q.After; c != nil {
var v any = c.Value
switch q.Sort {
case domain.SortPriceAsc, domain.SortPriceDesc:
v, _ = strconv.ParseInt(c.Value, 10, 64)
case domain.SortName:
default:
v, _ = time.Parse(time.RFC3339Nano, c.Value)
}
where = append(where, fmt.Sprintf("(%s, id) %s (%s, %s)", o.col, o.cmp, arg(v), arg(c.ID)))
}
sql := `SELECT ` + productCols + ` FROM products WHERE ` + strings.Join(where, " AND ") +
` ORDER BY ` + o.by + ` LIMIT ` + arg(q.Limit)
return sql, args
}
// escapeLike makes %, _ and \ literal inside an ILIKE pattern.
func escapeLike(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}Authentication, sessions/JWT, and authorization: customer vs admin Must-know
In plain words: authentication answers "who is calling" once per request, in middleware; authorization answers "may this caller do this to this object", at two levels: the route (is this an admin endpoint?) and the object (is this order theirs?).
Common misunderstanding: "If the route requires login, the data is safe." OWASP's API Security Top 10 puts Broken Object Level Authorization first (API1:2023): "Every API endpoint that receives an ID of an object, and performs any action on the object, should implement object-level authorization checks." A logged-in Bob calling GET /v1/orders/ord_alice must get 404. Another: "Return 403 for someone else's order." 403 confirms the order exists; 404 does not. Third: "Put roles in the URL or a header the client sets." The role comes from the verified session or token.
Definition: httpapi.Authenticator turns a request into a domain.Principal{UserID, Email, Role} placed in the context; this project ships StaticTokens (tests, and two dev tokens in cmd/api when ECOM_ENV=development), and production plugs in the session store or JWT verifier from Authentication in Go (Argon2id, scs, golang-jwt/jwt/v5). Route level: customer(h) answers 401 with WWW-Authenticate: Bearer realm="shop", admin(h) answers 403. Object level: Principal.CanSee(ownerID) in Orders.Get and Orders.Cancel, and requireAdmin in Fulfil, CreateProduct, UpdatePrice (defence in depth: the service is also called by jobs and scripts). Sessions vs JWT for a shop: a cookie session suits the web storefront (revocable, CSRF protection needed), a short-lived JWT plus refresh suits the mobile app; both end up as the same Principal.
Request Middleware Route guard Service check Result
1 GET /v1/orders/ord_a (no token) no principal customer: 401 401
2 GET /v1/orders/ord_a Bearer bob Principal{8, customer} ok CanSee(7)? no 404
3 GET /v1/orders/ord_a Bearer alice Principal{7, customer} ok CanSee(7)? yes 200
4 POST /v1/admin/products Bearer alice Principal{7, customer} admin: 403 403
5 POST /v1/admin/orders/x/fulfil admin Principal{1, admin} ok requireAdmin ok 200 / 409Real scenario: order ids that are guessable (sequential integers make BOLA trivial; OWASP says "Prefer the use of random and unpredictable values as GUIDs for records' IDs", and this project uses 128 random bits, which helps but is not authorization); a support agent role that may read but not refund; a webhook endpoint that has no user at all and authenticates with an HMAC instead; a mobile app and a web shop sharing the same API.
| Check | Where | Answer | Example |
|---|---|---|---|
| Is there a caller? | customer guard | 401 + WWW-Authenticate | place order anonymously |
| Is the caller an admin? | admin guard and requireAdmin | 403 | customer creating a product |
| Does the object belong to the caller? | service (CanSee) | 404 | Bob reading Alice's order |
| Is the cart a guest cart? | MergeOnLogin | ignored | merging someone else's customer cart |
| Is the PSP the caller? | HMAC on the raw body | 400 | forged webhook |
Fix / how to use it: the middleware (authentication, guards, rate limiter, security headers) is one file.
package httpapi
import (
"context"
"crypto/rand"
"encoding/hex"
"log/slog"
"net"
"net/http"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
"academy/ecommerce-api-project/domain"
)
type ctxKey struct{}
// PrincipalFrom returns the authenticated caller, if any.
func PrincipalFrom(ctx context.Context) (domain.Principal, bool) {
p, ok := ctx.Value(ctxKey{}).(domain.Principal)
return p, ok
}
// Authenticator resolves the caller. Production uses sessions or JWT (see the
// authentication chapter); tests and local runs use StaticTokens.
type Authenticator interface {
Authenticate(r *http.Request) (domain.Principal, bool)
}
// StaticTokens maps a bearer token to a principal.
type StaticTokens map[string]domain.Principal
func (s StaticTokens) Authenticate(r *http.Request) (domain.Principal, bool) {
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok {
return domain.Principal{}, false
}
p, ok := s[tok]
return p, ok
}
func chain(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if id == "" || len(id) > 64 {
b := make([]byte, 8)
_, _ = rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r)
})
}
// securityHeaders sets the headers the OWASP REST Security Cheat Sheet lists
// for API responses.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Cache-Control", "no-store")
h.Set("Content-Security-Policy", "frame-ancestors 'none'")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
h.Set("Referrer-Policy", "no-referrer")
next.ServeHTTP(w, r)
})
}
func (a *API) recoverer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
if v == http.ErrAbortHandler {
panic(v)
}
a.Log.ErrorContext(r.Context(), "panic", "value", v, "path", r.URL.Path)
writeProblem(w, r, Problem{Title: "Internal Server Error", Status: 500})
}
}()
next.ServeHTTP(w, r)
})
}
func (a *API) logRequests(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(sw, r)
a.Log.LogAttrs(r.Context(), slog.LevelInfo, "http",
slog.String("method", r.Method), slog.String("path", r.URL.Path), slog.Int("status", sw.status),
slog.Duration("took", time.Since(start)), slog.String("request_id", w.Header().Get("X-Request-ID")))
})
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (s *statusWriter) WriteHeader(c int) { s.status = c; s.ResponseWriter.WriteHeader(c) }
func (a *API) authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if p, ok := a.Auth.Authenticate(r); ok {
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, p))
}
next.ServeHTTP(w, r)
})
}
// customer and admin wrap single routes: authorization per route, and the
// services check again per object.
func customer(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := PrincipalFrom(r.Context()); !ok {
w.Header().Set("WWW-Authenticate", `Bearer realm="shop"`)
writeProblem(w, r, Problem{Title: "Unauthorized", Status: 401})
return
}
h(w, r)
}
}
func admin(h http.HandlerFunc) http.HandlerFunc {
return customer(func(w http.ResponseWriter, r *http.Request) {
if p, _ := PrincipalFrom(r.Context()); !p.IsAdmin() {
writeProblem(w, r, Problem{Title: "Forbidden", Status: 403})
return
}
h(w, r)
})
}
// IPLimiter is a token bucket per client IP (golang.org/x/time/rate). Behind
// a proxy, derive the IP from a header only the proxy can set.
type IPLimiter struct {
mu sync.Mutex
buckets map[string]*rate.Limiter
r rate.Limit
burst int
}
func NewIPLimiter(perSecond float64, burst int) *IPLimiter {
return &IPLimiter{buckets: map[string]*rate.Limiter{}, r: rate.Limit(perSecond), burst: burst}
}
func (l *IPLimiter) allow(ip string) bool {
l.mu.Lock()
b, ok := l.buckets[ip]
if !ok {
b = rate.NewLimiter(l.r, l.burst)
l.buckets[ip] = b
}
l.mu.Unlock()
return b.Allow()
}
func (a *API) rateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
if a.Limiter != nil && !a.Limiter.allow(ip) {
w.Header().Set("Retry-After", "1")
writeProblem(w, r, Problem{Type: problemBase + "rate-limited", Title: "Too Many Requests", Status: 429})
return
}
next.ServeHTTP(w, r)
})
}Input validation and error envelope Must-know
In plain words: reject a bad request before it touches the database, say exactly which fields are wrong, and use one JSON shape for every error so clients can handle them all the same way.
Common misunderstanding: "Validation is one layer." Shape (valid JSON, no unknown fields, body under 1 MiB) is the handler's job; business rules (quantity 0..10, price positive, known tax class, cursor matches the sort) are the service's job, because jobs and scripts call the service too; the database constraints are the net. Another: "Return 400 for everything." 400 means the request could not be parsed (or a required header is missing); 422 means it was parsed and is semantically invalid; 409 means it conflicts with the current state (stock, status, in-flight key); 412 means a precondition (If-Match) failed; 428 means the precondition is required.
Definition: readBody uses http.MaxBytesReader and a json.Decoder with DisallowUnknownFields; service.ValidationError{Fields []FieldError} collects every invalid field; httpapi.fail maps each error type to one RFC 9457 problem (application/problem+json, members type, title, status, detail, instance, plus extensions request_id, errors, product_id, available). RFC 9457 defines a "problem detail" "to carry machine-readable details of errors in HTTP response content". Internal errors are logged with the request id and answered with a generic 500 that leaks nothing. Hand-written validation keeps this module small; A REST API in Go compares it with go-playground/validator, which "implements value validations for structs and individual fields based on tags".
Input Layer Answer
1 {"qty":1,"price":1} (unknown field "price") handler 422 validation, field body
2 {"qty":11} service 422 validation, field qty
3 ?sort=hack&limit=1000 service 422, two fields: sort, limit
4 POST /v1/orders without Idempotency-Key handler 400 idempotency-key-missing
5 cart line for a product with 1 left, qty 2 service 409 out-of-stock, product_id, available 1
6 a nil pointer in a handler recoverer 500, logged with request_id, body genericReal scenario: a mobile client sending "qty": "2" as a string (decoder error, 422); a malicious client trying to set the price through an extra field (unknown field, 422); a partner integration that needs the field name to show the error next to the input; a support engineer who searches the logs by the request_id in the customer's screenshot.
| Situation | Status | type (suffix of https://shop.example/problems/) |
|---|---|---|
| Invalid fields | 422 | validation |
| Not enough stock | 409 | out-of-stock |
| Status does not allow it | 409 | invalid-transition |
Stale If-Match | 412 | version-conflict |
| Empty cart, inactive product | 422 | cart |
| Key reused with another body | 422 | idempotency-key-reused |
| Lock wait timed out (duplicate key still running, hot row) | 409 | busy |
| Missing key | 400 | idempotency-key-missing |
| Rate limited | 429 | rate-limited |
| Not found, unauthorized, forbidden, internal | 404, 401, 403, 500 | about:blank |
Fix / how to use it:
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/service"
"academy/ecommerce-api-project/store"
)
// Problem is the RFC 9457 error envelope, served as application/problem+json.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
RequestID string `json:"request_id,omitempty"`
Errors []service.FieldError `json:"errors,omitempty"`
ProductID int64 `json:"product_id,omitempty"`
Available *int64 `json:"available,omitempty"`
}
const problemBase = "https://shop.example/problems/"
func writeProblem(w http.ResponseWriter, r *http.Request, p Problem) {
p.Instance = r.URL.Path
p.RequestID = w.Header().Get("X-Request-ID")
if p.Type == "" {
p.Type = "about:blank"
}
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}
// fail maps service and store errors to statuses in one place.
func (a *API) fail(w http.ResponseWriter, r *http.Request, err error) {
var ve *service.ValidationError
var oos *domain.OutOfStockError
switch {
case errors.As(err, &ve):
writeProblem(w, r, Problem{Type: problemBase + "validation", Title: "Invalid input", Status: 422, Errors: ve.Fields})
case errors.As(err, &oos):
writeProblem(w, r, Problem{Type: problemBase + "out-of-stock", Title: "Not enough stock", Status: 409,
Detail: oos.Error(), ProductID: oos.ProductID, Available: &oos.Available})
case errors.Is(err, domain.ErrNotFound):
writeProblem(w, r, Problem{Title: "Not Found", Status: 404})
case errors.Is(err, domain.ErrForbidden):
writeProblem(w, r, Problem{Title: "Forbidden", Status: 403})
case errors.Is(err, domain.ErrInvalidTransition):
writeProblem(w, r, Problem{Type: problemBase + "invalid-transition", Title: "Not allowed in the current status", Status: 409, Detail: err.Error()})
case errors.Is(err, domain.ErrConflict):
writeProblem(w, r, Problem{Type: problemBase + "version-conflict", Title: "Changed by someone else", Status: 412})
case errors.Is(err, domain.ErrEmptyCart), errors.Is(err, domain.ErrInactiveProduct):
writeProblem(w, r, Problem{Type: problemBase + "cart", Title: "Cart cannot be checked out", Status: 422, Detail: err.Error()})
case errors.Is(err, service.ErrIdempotencyMismatch):
writeProblem(w, r, Problem{Type: problemBase + "idempotency-key-reused", Title: "Idempotency-Key reused with another body", Status: 422})
case errors.Is(err, store.ErrBusy):
w.Header().Set("Retry-After", "1")
// lock_timeout expired: usually a duplicate request with the same
// Idempotency-Key still running, sometimes a very hot stock row.
writeProblem(w, r, Problem{Type: problemBase + "busy", Title: "Conflicting request still running, retry shortly", Status: 409})
case errors.Is(err, service.ErrAmountMismatch):
writeProblem(w, r, Problem{Type: problemBase + "amount-mismatch", Title: "Amount differs from the order", Status: 422})
default:
a.Log.ErrorContext(r.Context(), "internal error", "err", err, "path", r.URL.Path)
writeProblem(w, r, Problem{Title: "Internal Server Error", Status: 500}) // never leak err text
}
}Events: OrderPlaced and PaymentCaptured via outbox to RabbitMQ or in-process bus Must-know
In plain words: when an order is placed or paid, other parts of the system must hear about it. Write the event as a row in the same transaction as the change; a relay reads the rows and hands them to the in-process bus (local consumers such as the mail worker) and, when other services exist, to RabbitMQ.
Common misunderstanding: "Publish to RabbitMQ right after COMMIT." A crash between the two loses the event (the order exists, nobody mails or ships it); publishing before COMMIT announces orders that roll back. Another: "Exactly-once delivery." The relay marks a row published only after the publisher returned nil, so a crash in between publishes it again: delivery is at least once, and consumers make the effect once by remembering event ids (an inbox). Third: "Several relays make it faster." Two relays reading the same table publish out of order and twice; run one per database, which this project enforces with APP_ROLE and a leader lease (see Monolith), or partition by aggregate.
Definition: domain.Event{ID, Type, AggregateID, OccurredAt, Payload} with deterministic ids such as order.placed:ord_x:v1 and payment.captured:ord_x:v2. outbox.Relay.RunOnce reads a batch oldest first (ORDER BY seq), publishes outside any transaction, stops at the first failure or at the first event still backing off (so payment.captured never overtakes order.placed), then in a second short transaction marks the published ones and gives the failed one attempts + 1 and a later next_attempt_at (exponential, capped at 10 minutes). bus.Bus routes by type to named handlers and joins their errors; outbox.Fanout{bus, rabbit} sends to both. rabbit.Publisher declares a durable topic exchange, puts the channel in confirm mode and waits for the broker's ack (PublishWithDeferredConfirmWithContext + WaitContext); messages are persistent JSON with MessageId = event id. amqp091-go does not reconnect by itself (its source: "To reconnect after a transport or protocol error, register a listener here and re-run your setup process"), so the publisher registers NotifyClose, drops the dead connection and channel, and the next Publish redials, declares the exchange and enables confirms again, with exponential backoff between failed dials; while the broker is down Publish fails, the event stays in the outbox, and the relay resumes after the restart (TestPublisherRedialsAfterBrokerRestart). The RabbitMQ guide puts the reason plainly: publisher confirms exist because "Networks can fail in less-than-obvious ways". The microservices.io pattern and the relay variants (polling vs CDC with Debezium) are in Outbox Pattern; consumers, Watermill and SQS in Event-Driven Go; domain vs integration events in Domain Events vs Integration Events.
Checkout tx Relay Consumers
1 INSERT orders ... ; INSERT outbox (order.placed:ord_1:v1); COMMIT
2 SELECT ... WHERE published_at IS NULL ORDER BY seq
3 bus: mail handler -> inbox? no -> send -> mark
4 rabbit: publish, wait for confirm (ack)
5 (crash before marking)
6 restart: publish order.placed:ord_1:v1 again
7 mail inbox: seen -> skip
8 warehouse: MessageId seen -> skip
9 UPDATE outbox SET published_at = now() WHERE event_id = ANY(...)Real scenario: the SMTP server is down for ten minutes on Black Friday (events back off and drain later, in order); RabbitMQ restarts during publishing (no ack, the publisher redials, the relay retries); the analytics service is deployed a week later and replays from its own queue; a receipt must never be sent for an order whose transaction rolled back.
| Transport | When | Delivery | Ordering | Here |
|---|---|---|---|---|
| In-process bus | monolith, local consumers | at least once (relay retries) | per relay | bus.Bus |
| RabbitMQ topic exchange + confirms | other services consume | at least once, persistent | per queue, single consumer | rabbit.Publisher |
| Kafka topic, key = order id | high volume, replay | at least once | per partition | (see Event-Driven Go) |
CDC (Debezium) on outbox | no polling, WAL-based | at least once | per table/key | (see Outbox Pattern) |
Laravel dispatch(...)->afterCommit() | Laravel monolith | after commit, but not in the transaction | per queue | For PHP/Laravel developers |
Fix / how to use it: the relay, the bus and the RabbitMQ publisher.
// Package outbox relays events from the outbox table to a publisher (the
// in-process bus or RabbitMQ). Delivery is at least once: an event is
// marked published only after Publish returned nil, so a crash in between
// publishes it again and consumers dedupe by event id.
package outbox
import (
"context"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/store"
)
// Publisher sends one event to the outside world.
type Publisher interface {
Publish(ctx context.Context, e domain.Event) error
}
// Relay polls the outbox.
type Relay struct {
Store store.Store
Pub Publisher
Now func() time.Time
Batch int
Backoff func(attempt int) time.Duration // delay before the next try of a failed event
}
// RunOnce reads a batch, publishes in order outside any transaction, and
// then records the outcome in a second short transaction. It stops at the
// first failure or at the first event still backing off: a later event
// (payment.captured) must not overtake an earlier one (order.placed). Run
// one relay per database (a single worker replica, or a leader lease) to
// keep that order; a second relay would only cause duplicates, which
// consumers drop.
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
now := r.Now()
var evs []domain.Event
err := r.Store.InTx(ctx, func(ctx context.Context, tx store.Tx) error {
var err error
evs, err = tx.Outbox().Claim(ctx, max(r.Batch, 1))
return err
})
if err != nil {
return 0, err
}
var done []string
var failed *domain.Event
var pubErr error
for _, e := range evs {
if e.NextAttempt.After(now) {
break // the head of the queue is backing off; nothing may overtake it
}
if pubErr = r.Pub.Publish(ctx, e); pubErr != nil {
failed = &e
break
}
done = append(done, e.ID)
}
if len(done) == 0 && failed == nil {
return 0, nil
}
// A crash before this commit republishes done: at-least-once.
err = r.Store.InTx(context.WithoutCancel(ctx), func(ctx context.Context, tx store.Tx) error {
if len(done) > 0 {
if err := tx.Outbox().MarkPublished(ctx, done, now); err != nil {
return err
}
}
if failed != nil {
return tx.Outbox().MarkFailed(ctx, failed.ID, now.Add(r.backoff(failed.Attempts+1)))
}
return nil
})
if err != nil {
return 0, err
}
return len(done), pubErr
}
func (r *Relay) backoff(attempt int) time.Duration {
if r.Backoff != nil {
return r.Backoff(attempt)
}
return min(time.Second<<min(attempt, 10), 10*time.Minute)
}
// Run calls RunOnce every interval until ctx is done. Errors are reported
// to onErr (a logger) and never stop the loop.
func (r *Relay) Run(ctx context.Context, every time.Duration, onErr func(error)) {
t := time.NewTicker(every)
defer t.Stop()
for {
if _, err := r.RunOnce(ctx); err != nil && onErr != nil && ctx.Err() == nil {
onErr(err)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// Fanout publishes to several publishers in order (the in-process bus for
// local consumers, RabbitMQ for other services). If one fails the event is
// retried for all; every consumer dedupes by event id.
type Fanout []Publisher
func (f Fanout) Publish(ctx context.Context, e domain.Event) error {
for _, p := range f {
if err := p.Publish(ctx, e); err != nil {
return err
}
}
return nil
}// Package bus is an in-process event bus: the outbox relay publishes to it
// and the worker's handlers subscribe. It is the "monolith" transport; the
// rabbit package is a drop-in Publisher for when consumers move out.
package bus
import (
"context"
"errors"
"fmt"
"sync"
"academy/ecommerce-api-project/domain"
)
// Handler handles one event. It must be idempotent: the relay redelivers.
type Handler func(ctx context.Context, e domain.Event) error
// Bus routes events by type to named handlers.
type Bus struct {
mu sync.RWMutex
subs map[string][]sub
}
type sub struct {
name string
h Handler
}
func New() *Bus { return &Bus{subs: map[string][]sub{}} }
// Subscribe registers h for an event type under a consumer name (the name
// is the inbox key, so two consumers of the same event dedupe separately).
func (b *Bus) Subscribe(eventType, consumer string, h Handler) {
b.mu.Lock()
defer b.mu.Unlock()
b.subs[eventType] = append(b.subs[eventType], sub{consumer, h})
}
// Publish calls every handler for e.Type synchronously and joins their
// errors. A failure makes the relay retry the event for all handlers, and
// the handlers that already succeeded skip it through their inbox.
func (b *Bus) Publish(ctx context.Context, e domain.Event) error {
b.mu.RLock()
subs := b.subs[e.Type]
b.mu.RUnlock()
var errs []error
for _, s := range subs {
if err := s.h(ctx, e); err != nil {
errs = append(errs, fmt.Errorf("%s: %w", s.name, err))
}
}
return errors.Join(errs...)
}// Package rabbit is an outbox.Publisher for RabbitMQ (amqp091-go). It
// publishes to a durable topic exchange with publisher confirms, so Publish
// returns nil only after the broker has taken responsibility for the
// message; the relay then marks the outbox row published. It survives a
// broker restart by redialling.
package rabbit
import (
"context"
"errors"
"fmt"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
"academy/ecommerce-api-project/domain"
)
// Confirmation is the broker's answer for one publish (*amqp.DeferredConfirmation).
type Confirmation interface {
WaitContext(ctx context.Context) (bool, error)
}
// Channel is the part of *amqp.Channel the publisher uses.
type Channel interface {
ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table) error
Confirm(noWait bool) error
Publish(ctx context.Context, exchange, key string, msg amqp.Publishing) (Confirmation, error)
Close() error
}
// Conn is the part of *amqp.Connection the publisher uses.
type Conn interface {
Channel() (Channel, error)
NotifyClose(receiver chan *amqp.Error) chan *amqp.Error
Close() error
}
type amqpConn struct{ c *amqp.Connection }
func (a amqpConn) Channel() (Channel, error) {
ch, err := a.c.Channel()
if err != nil {
return nil, err
}
return amqpChannel{ch}, nil
}
func (a amqpConn) NotifyClose(r chan *amqp.Error) chan *amqp.Error { return a.c.NotifyClose(r) }
func (a amqpConn) Close() error { return a.c.Close() }
type amqpChannel struct{ *amqp.Channel }
// Publish uses publisher confirms. mandatory=false: queues are declared and
// bound at deploy time; an unroutable message would be acked and dropped
// (catch that with an alternate exchange, or mandatory=true plus NotifyReturn).
func (c amqpChannel) Publish(ctx context.Context, exchange, key string, msg amqp.Publishing) (Confirmation, error) {
dc, err := c.PublishWithDeferredConfirmWithContext(ctx, exchange, key, false, false, msg)
if err != nil {
return nil, err
}
return dc, nil
}
// Dial returns a dialer for an AMQP URL.
func Dial(url string) func() (Conn, error) {
return func() (Conn, error) {
c, err := amqp.Dial(url)
if err != nil {
return nil, err
}
return amqpConn{c}, nil
}
}
// ErrUnavailable: the broker is down and the next redial is not due yet.
var ErrUnavailable = errors.New("rabbit: broker unavailable, redial backing off")
// Publisher holds one connection and one channel in confirm mode, and
// replaces both after the broker closes them. amqp091-go does not reconnect
// by itself: a closed connection stays closed and every channel on it is
// gone. NotifyClose marks the publisher broken; the next Publish redials
// (exchange declared again, confirm mode again) with exponential backoff
// between failed dials. While it is down Publish returns an error, the
// relay keeps the event in the outbox and retries it later, so nothing is
// lost and nothing overtakes it.
type Publisher struct {
dial func() (Conn, error)
exchange string
MinBackoff, MaxBackoff time.Duration
mu sync.Mutex // also serialises publishing: a channel is not safe for concurrent use
conn Conn
ch Channel
gen int
backoff time.Duration
nextDial time.Time
}
// New connects to url and declares the exchange.
func New(url, exchange string) (*Publisher, error) { return NewWithDialer(Dial(url), exchange) }
// NewWithDialer is New with an injectable dialer (tests).
func NewWithDialer(dial func() (Conn, error), exchange string) (*Publisher, error) {
p := &Publisher{dial: dial, exchange: exchange, MinBackoff: 500 * time.Millisecond, MaxBackoff: 30 * time.Second}
p.mu.Lock()
defer p.mu.Unlock()
return p, p.connectLocked()
}
func (p *Publisher) connectLocked() error {
conn, err := p.dial()
if err != nil {
return err
}
ch, err := conn.Channel()
if err == nil {
err = ch.ExchangeDeclare(p.exchange, "topic", true, false, false, false, nil)
}
if err == nil {
err = ch.Confirm(false)
}
if err != nil {
_ = conn.Close()
return err
}
p.conn, p.ch = conn, ch
p.gen++
gen := p.gen
notify := conn.NotifyClose(make(chan *amqp.Error, 1))
go func() {
for range notify { // closed by the library after the close reason (if any)
}
p.mu.Lock()
defer p.mu.Unlock()
if p.gen == gen {
p.dropLocked()
}
}()
return nil
}
func (p *Publisher) dropLocked() {
if p.ch != nil {
_ = p.ch.Close()
}
if p.conn != nil {
_ = p.conn.Close()
}
p.ch, p.conn = nil, nil
}
func (p *Publisher) broken() bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.ch == nil
}
// Publish sends e with routing key e.Type ("order.placed") and waits for the
// broker's ack. A nack, a timeout or a closed channel is an error: the relay
// retries, and the consumer dedupes by MessageId.
func (p *Publisher) Publish(ctx context.Context, e domain.Event) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.ch == nil {
if time.Now().Before(p.nextDial) {
return ErrUnavailable
}
if err := p.connectLocked(); err != nil {
p.backoff = min(max(p.backoff*2, p.MinBackoff), p.MaxBackoff)
p.nextDial = time.Now().Add(p.backoff)
return fmt.Errorf("rabbit: redial: %w", err)
}
p.backoff = 0
}
dc, err := p.ch.Publish(ctx, p.exchange, e.Type, ToPublishing(e))
if err != nil {
p.dropLocked() // e.g. amqp.ErrClosed: redial on the next call
return err
}
ok, err := dc.WaitContext(ctx)
if err != nil {
return err
}
if !ok {
return errors.New("rabbit: broker nacked " + e.ID)
}
return nil
}
// Close closes the channel and the connection.
func (p *Publisher) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
p.gen++
p.dropLocked()
return nil
}
// ToPublishing maps an event to an AMQP message: persistent, JSON, with the
// event id as MessageId (the consumer's dedupe key).
func ToPublishing(e domain.Event) amqp.Publishing {
return amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
MessageId: e.ID,
Type: e.Type,
Timestamp: e.OccurredAt,
Headers: amqp.Table{"aggregate_id": e.AggregateID},
Body: e.Payload,
}
}
// RoutingKeyFor documents the binding a consumer uses, e.g. "order.*".
func RoutingKeyFor(aggregate string) string { return fmt.Sprintf("%s.*", aggregate) }SMTP order confirmation mail: go-mail and templates Important
In plain words: the confirmation is rendered from two templates (plain text and HTML) embedded in the binary and sent over SMTP with STARTTLS by a library that handles MIME, encodings and authentication, never from inside the checkout request.
Common misunderstanding: "Use net/smtp." Its source says "The smtp package is frozen and is not accepting new features"; it does not build multipart MIME messages, and you would write headers, boundaries and encodings by hand. Another: "Render the HTML with text/template." Then a product named <script>alert(1)</script> is executed in webmail; html/template escapes it (the test checks <script>). Third: "A failed send should fail the order." The order is already committed; a mail failure is retried by the worker and, if permanent, alerted on.
Definition: mailer.OrderConfirmation(order, eventID, domain) executes templates/order_confirmation.txt.tmpl with text/template and .html.tmpl with html/template, loaded with //go:embed templates/*.tmpl, and sets Message-ID to <eventID@domain> so a resend after a crash is recognisable. mailer.SMTP wraps a go-mail client: mail.NewClient(host, mail.WithPort(587), mail.WithTLSPortPolicy(mail.TLSMandatory), mail.WithSMTPAuth(mail.SMTPAuthPlain), mail.WithUsername(...), mail.WithPassword(...)), and per message NewMsg, From, To, Subject, SetMessageIDWithValue, SetDate, SetBodyString(mail.TypeTextPlain, ...), AddAlternativeString(mail.TypeTextHTML, ...), sent with DialAndSendWithContext(ctx, msg). A *mail.SendError whose ErrorCode() is 5xx becomes mailer.PermanentError, which stops the retries. go-mail's source says the code "will start with 5 on permanent errors and with 4 on a temporary error" and is 0 for errors not returned by the server; such a dial or TLS failure also has IsTemp() == false, so testing IsTemp() alone would wrongly give up on a mail when the network blips (TestOnlyServer5xxIsPermanent). The README describes go-mail as "a modern, feature-rich library for composing and sending mail with Go" that "keeps a small dependency footprint by building primarily on the Go Standard Library and the official Go extended packages". v0.7.2 is the last release whose go.mod says 1.24.
Worker SMTP server (submission, port 587)
1 DialAndSendWithContext(ctx, msg) 220 smtp.example ESMTP
2 EHLO -> 250 STARTTLS, AUTH PLAIN LOGIN
3 STARTTLS (TLSMandatory) TLS handshake
4 AUTH PLAIN (only inside TLS) 235 Authentication successful
5 MAIL FROM / RCPT TO / DATA 421 4.7.0 try again later -> IsTemp: retry with backoff
6 (retry 2) ... DATA 250 OK queued -> inbox.Mark(event id)Real scenario: a transactional mail provider (Postmark, SES SMTP, Mailgun) behind port 587; Mailpit or MailHog in development; a recipient domain that rejects with 550 5.1.1 user unknown (permanent: do not retry, alert); a provider rate limit answering 421 (temporary: back off).
| Option | Pros | Cons |
|---|---|---|
| go-mail over SMTP (this project) | any provider, standard protocol, MIME done right | connection per send unless you keep one open |
net/smtp | stdlib | frozen, no MIME builder |
| Provider HTTP API (SES, Postmark, SendGrid SDK) | webhooks for bounces, templates at the provider | vendor lock-in, another SDK |
Laravel Mail + ShouldQueue mailable | built in | PHP only |
Fix / how to use it: templates, renderer, sender.
Hello,
thank you for your order {{.OrderID}}.
{{range .Items}}{{.Qty}} x {{.Name}} {{.LineTotal}}
{{end}}
Subtotal: {{.Subtotal}}
{{if .HasDiscount}}Discount: -{{.Discount}}
{{end}}Tax: {{.Tax}}
Total: {{.Total}}
We will e-mail you again when it ships.// Package mailer renders the order confirmation from embedded templates and
// sends it over SMTP with github.com/wneessen/go-mail. The text part uses
// text/template; the HTML part uses html/template, which escapes product
// names (a product called "<script>" stays text).
package mailer
import (
"bytes"
"context"
"embed"
htmltpl "html/template"
"sync"
texttpl "text/template"
"academy/ecommerce-api-project/domain"
)
//go:embed templates/*.tmpl
var files embed.FS
var (
textT = texttpl.Must(texttpl.ParseFS(files, "templates/order_confirmation.txt.tmpl"))
htmlT = htmltpl.Must(htmltpl.ParseFS(files, "templates/order_confirmation.html.tmpl"))
)
// Message is a rendered mail.
type Message struct {
To, Subject, Text, HTML string
MessageID string // deterministic per event: retries reuse it
}
// Sender delivers a message. Implementations: SMTP (go-mail), Recorder (tests).
type Sender interface {
Send(ctx context.Context, m Message) error
}
type line struct {
Qty int64
Name, LineTotal string
}
type view struct {
OrderID string
Items []line
Subtotal, Discount, Tax, Total string
HasDiscount bool
}
// OrderConfirmation renders the mail for o. eventID becomes the Message-ID.
func OrderConfirmation(o domain.Order, eventID, domainName string) (Message, error) {
v := view{OrderID: o.ID, Subtotal: o.Subtotal.String(), Discount: o.Discount.String(),
Tax: o.Tax.String(), Total: o.Total.String(), HasDiscount: !o.Discount.IsZero()}
for _, it := range o.Items {
v.Items = append(v.Items, line{Qty: it.Qty, Name: it.Name, LineTotal: it.LineTotal.String()})
}
var txt, html bytes.Buffer
if err := textT.Execute(&txt, v); err != nil {
return Message{}, err
}
if err := htmlT.Execute(&html, v); err != nil {
return Message{}, err
}
return Message{To: o.Email, Subject: "Your order " + o.ID, Text: txt.String(), HTML: html.String(),
MessageID: eventID + "@" + domainName}, nil
}
// Recorder is a Sender that keeps messages in memory.
type Recorder struct {
mu sync.Mutex
sent []Message
Fail int // fail this many calls first (to exercise retries)
}
func (r *Recorder) Send(_ context.Context, m Message) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.Fail > 0 {
r.Fail--
return errTemporary
}
r.sent = append(r.sent, m)
return nil
}
// Sent returns a copy of what was sent.
func (r *Recorder) Sent() []Message {
r.mu.Lock()
defer r.mu.Unlock()
return append([]Message(nil), r.sent...)
}
type tempErr struct{}
func (tempErr) Error() string { return "421 4.7.0 try again later" }
func (tempErr) Temporary() bool { return true }
var errTemporary error = tempErr{}
// LogSender writes mails to a logger instead of sending them (development).
type LogSender struct {
Log interface{ Info(string, ...any) }
}
func (l LogSender) Send(_ context.Context, m Message) error {
l.Log.Info("mail (not sent)", "to", m.To, "subject", m.Subject, "message_id", m.MessageID)
return nil
}package mailer
import (
"context"
"errors"
"github.com/wneessen/go-mail"
)
// SMTPConfig comes from the environment (see the config package).
type SMTPConfig struct {
Host, Username, Password, From string
Port int
}
// SMTP sends through one go-mail Client. DialAndSendWithContext opens a
// connection per call, which is fine for a worker sending a few mails a
// second; a high-volume sender keeps the connection open (DialWithContext +
// Send) or hands the job to an e-mail API.
type SMTP struct {
c *mail.Client
from string
}
// NewSMTP builds the client: STARTTLS is mandatory and AUTH PLAIN is used,
// which is safe only because the connection is already encrypted.
func NewSMTP(cfg SMTPConfig) (*SMTP, error) {
c, err := mail.NewClient(cfg.Host,
mail.WithPort(cfg.Port),
mail.WithTLSPortPolicy(mail.TLSMandatory),
mail.WithSMTPAuth(mail.SMTPAuthPlain),
mail.WithUsername(cfg.Username),
mail.WithPassword(cfg.Password),
)
if err != nil {
return nil, err
}
return &SMTP{c: c, from: cfg.From}, nil
}
// Send delivers m. ctx bounds the whole SMTP conversation.
func (s *SMTP) Send(ctx context.Context, m Message) error {
msg, err := build(s.from, m)
if err != nil {
return Permanent(err) // a bad address will not get better with retries
}
return classify(s.c.DialAndSendWithContext(ctx, msg))
}
// classify marks only a 5xx server reply as permanent. go-mail's ErrorCode
// "will start with 5 on permanent errors and with 4 on a temporary error",
// and is 0 when the error did not come from the server (dial, TLS, timeout):
// those must be retried, even though IsTemp() reports false for them.
func classify(err error) error {
var se *mail.SendError
if errors.As(err, &se) && se.ErrorCode() >= 500 && se.ErrorCode() < 600 {
return Permanent(err)
}
return err
}
func build(from string, m Message) (*mail.Msg, error) {
msg := mail.NewMsg()
if err := msg.From(from); err != nil {
return nil, err
}
if err := msg.To(m.To); err != nil {
return nil, err
}
msg.Subject(m.Subject)
msg.SetMessageIDWithValue(m.MessageID)
msg.SetDate()
msg.SetBodyString(mail.TypeTextPlain, m.Text)
msg.AddAlternativeString(mail.TypeTextHTML, m.HTML)
return msg, nil
}
// PermanentError marks a failure that retrying cannot fix.
type PermanentError struct{ Err error }
func (e *PermanentError) Error() string { return "permanent: " + e.Err.Error() }
func (e *PermanentError) Unwrap() error { return e.Err }
// Permanent wraps err.
func Permanent(err error) error { return &PermanentError{Err: err} }Background workers: async via worker with retries, abandoned cart, stock release timeout Must-know
In plain words: some work happens later: send the mail, give back stock that an unpaid order has held too long, remind customers about the cart they left. Each is a small function that runs on a ticker or on an event, can run twice without harm, and stops cleanly at shutdown.
Common misunderstanding: "A go sendMail() in the handler is async enough." The goroutine dies with the process, has no retry and no record; the outbox plus a worker survive restarts. Another: "The stock-release job can UPDATE orders SET status = 'cancelled' WHERE expires_at < now()." A payment can arrive in the same millisecond; the job must re-read each order, check it is still created, and write with the version check, so either the payment or the cancel wins, never both. Third: "Retry forever." Permanent failures (bad address) must stop and alert; temporary ones need capped exponential backoff with jitter.
Definition: worker.OrderMail.Handle is a bus handler: Inbox.Has (skip if already done), load the order, render, Retry up to 3 attempts with Backoff{Base: 200ms, Max: 5s} and full jitter (rand.N(min(Max, Base<<n))), Inbox.Mark after success (so a crash in between resends rather than loses the mail); a permanent error is logged and marked done; a temporary one after the last attempt is returned so the relay backs off and redelivers. Housekeeping.ReleaseExpired lists created orders with expires_at < now (default hold 15 minutes, ECOM_STOCK_HOLD) and cancels each in its own short transaction through the same cancelInTx as the customer cancel, releasing stock exactly once. If a capture arrives after that, ApplyPayment does not resurrect the order: the payment becomes refund_pending and payment.refund_requested is emitted. Housekeeping.RemindAbandoned finds customer carts idle for AbandonedAfter (24 h) and not reminded, marks them and writes cart.abandoned in the same transaction (FOR UPDATE SKIP LOCKED lets two workers share the scan). worker.RunJobs runs each job on its own ticker and returns when the context is done and every current run finished.
t Order ord_1 (hold 15 min) Stock-release job PSP webhook
1 10:00 created v1, reserved 3
2 10:16 Expired(now): [ord_1]
3 10:16 re-read: created, expired -> cancel v2, release 3
4 10:16 succeeded for ord_1
5 10:16 order cancelled -> payment refund_pending
6 10:17 Expired(now): [] (status is cancelled) -> nothing
Reverse order: capture first -> paid v2; the job's re-read sees paid and skips; stock stays reserved for shipping.Real scenario: a customer who opens the PSP page and walks away (stock comes back after 15 minutes); a bank transfer that settles after the hold (refund requested, or a longer hold for that payment method); a reminder mail that must go once, not every minute; a deploy in the middle of a batch (the job finishes its current order, then exits).
| Job | Trigger | Idempotent because | Concurrency guard |
|---|---|---|---|
| Confirmation mail | order.placed | inbox per consumer, Message-ID = event id | one relay |
| Stock release timeout | every minute | re-check status + version CAS | version on orders |
| Abandoned cart reminder | every minute | reminded_at set in the same tx as the event | FOR UPDATE SKIP LOCKED |
| Outbox relay | every second | published_at, consumers dedupe | leader lease (pgstore.Lease), APP_ROLE |
| Refund for late capture | payment.refund_requested | refund key derived from the payment | payments system |
Fix / how to use it:
package worker
import (
"context"
"errors"
"log/slog"
"sync"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/store"
)
// OrderMail sends the confirmation for order.placed, at least once and in
// practice once: the inbox skips redeliveries, and the Message-ID is the
// event id so a duplicate after a crash is recognisable.
type OrderMail struct {
Inbox store.Inbox
LoadOrder func(ctx context.Context, id string) (domain.Order, error)
Sender mailer.Sender
Backoff Backoff
Domain string // for Message-ID, e.g. "shop.example"
Log *slog.Logger
}
const mailConsumer = "order-confirmation-mail"
// Handle is a bus.Handler.
func (w OrderMail) Handle(ctx context.Context, e domain.Event) error {
done, err := w.Inbox.Has(ctx, mailConsumer, e.ID)
if err != nil || done {
return err
}
o, err := w.LoadOrder(ctx, e.AggregateID)
if err != nil {
return err
}
msg, err := mailer.OrderConfirmation(o, e.ID, w.Domain)
if err != nil {
return err
}
err = Retry(ctx, w.Backoff, func(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
return w.Sender.Send(ctx, msg)
})
var pe *mailer.PermanentError
if errors.As(err, &pe) {
w.Log.ErrorContext(ctx, "confirmation mail rejected", "order", o.ID, "err", err)
return w.Inbox.Mark(ctx, mailConsumer, e.ID) // do not redeliver forever: alert instead
}
if err != nil {
return err // the relay backs off and redelivers
}
return w.Inbox.Mark(ctx, mailConsumer, e.ID)
}
// Job is one periodic task.
type Job struct {
Name string
Every time.Duration
Run func(ctx context.Context) (int, error)
}
// RunJobs starts every job on its own ticker and returns when ctx is done
// and every job has finished its current run (graceful shutdown).
func RunJobs(ctx context.Context, log *slog.Logger, jobs ...Job) {
var wg sync.WaitGroup
for _, j := range jobs {
wg.Add(1)
go func() {
defer wg.Done()
t := time.NewTicker(j.Every)
defer t.Stop()
for {
if n, err := j.Run(ctx); err != nil && ctx.Err() == nil {
log.ErrorContext(ctx, "job failed", "job", j.Name, "err", err)
} else if n > 0 {
log.InfoContext(ctx, "job done", "job", j.Name, "items", n)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}()
}
wg.Wait()
}// Package worker holds the background side of the shop: the event handlers
// (order confirmation mail) and the periodic jobs (outbox relay, stock
// release timeout, abandoned-cart reminders), all stopped by one context.
package worker
import (
"context"
"errors"
"math/rand/v2"
"time"
"academy/ecommerce-api-project/mailer"
)
// Backoff is capped exponential backoff with full jitter: attempt n waits a
// random duration in [0, min(Max, Base*2^n)).
type Backoff struct {
Base, Max time.Duration
Attempts int
}
func (b Backoff) delay(n int) time.Duration {
d := min(b.Max, b.Base<<min(n, 20))
if d <= 0 {
return 0
}
return rand.N(d)
}
// Sleep waits d or until ctx is done. Tests replace it.
var Sleep = func(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// Retry runs fn up to b.Attempts times. A *mailer.PermanentError or a
// cancelled ctx stops it at once.
func Retry(ctx context.Context, b Backoff, fn func(context.Context) error) error {
var err error
for n := range max(b.Attempts, 1) {
if err = fn(ctx); err == nil {
return nil
}
var pe *mailer.PermanentError
if errors.As(err, &pe) || n == b.Attempts-1 {
return err
}
if serr := Sleep(ctx, b.delay(n)); serr != nil {
return errors.Join(err, serr)
}
}
return err
}The lease that keeps the relay and jobs on one replica, in memory and on a PostgreSQL advisory lock:
package worker
import (
"context"
"log/slog"
"sync"
"time"
)
// Lease is leadership for the background side: only the holder runs the
// outbox relay and the jobs, so N worker replicas give one relay (order kept,
// no duplicate scans) and a hot standby. pgstore.Lease implements it with
// pg_try_advisory_lock on a dedicated connection; MemLease is for one process.
type Lease interface {
// TryAcquire returns ok=false at once if someone else holds the lease.
// lost is closed if the lease is lost while held (connection dropped);
// release gives it up.
TryAcquire(ctx context.Context) (release func(), lost <-chan struct{}, ok bool, err error)
}
// RunWithLease retries TryAcquire every retry until it holds the lease, then
// runs the jobs until ctx is done or the lease is lost, then releases it.
// After a loss it goes back to waiting.
func RunWithLease(ctx context.Context, lease Lease, retry time.Duration, log *slog.Logger, jobs ...Job) {
for ctx.Err() == nil {
release, lost, ok, err := lease.TryAcquire(ctx)
if err != nil && ctx.Err() == nil {
log.ErrorContext(ctx, "lease", "err", err)
}
if ok {
log.InfoContext(ctx, "lease acquired: running background jobs")
jctx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-lost:
log.WarnContext(ctx, "lease lost: stopping background jobs")
cancel()
case <-jctx.Done():
}
}()
RunJobs(jctx, log, jobs...)
cancel()
release()
continue
}
t := time.NewTimer(retry)
select {
case <-ctx.Done():
t.Stop()
case <-t.C:
}
}
}
// MemLease is an in-process Lease (tests, a single binary with APP_ROLE=all).
type MemLease struct {
mu sync.Mutex
held bool
}
func NewMemLease() *MemLease { return &MemLease{} }
func (l *MemLease) TryAcquire(context.Context) (func(), <-chan struct{}, bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
if l.held {
return nil, nil, false, nil
}
l.held = true
return func() { l.mu.Lock(); l.held = false; l.mu.Unlock() }, make(chan struct{}), true, nil
}package pgstore
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// Lease is a leader lease on a PostgreSQL session-level advisory lock. The
// lock lives as long as the session, so it is taken on a connection checked
// out of the pool and held; if that connection dies, PostgreSQL releases the
// lock (another replica can take it) and lost is closed here.
type Lease struct {
Pool *pgxpool.Pool
Key int64 // e.g. 7340001, one per database
Check time.Duration // how often the held connection is pinged (default 5s)
}
func (l Lease) TryAcquire(ctx context.Context) (func(), <-chan struct{}, bool, error) {
conn, err := l.Pool.Acquire(ctx)
if err != nil {
return nil, nil, false, err
}
var ok bool
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, l.Key).Scan(&ok); err != nil || !ok {
conn.Release()
return nil, nil, false, err
}
lost := make(chan struct{})
stop := make(chan struct{})
every := l.Check
if every <= 0 {
every = 5 * time.Second
}
go func() {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-stop:
return
case <-t.C:
pctx, cancel := context.WithTimeout(context.Background(), every)
err := conn.Ping(pctx)
cancel()
if err != nil {
close(lost)
return
}
}
}
}()
release := func() {
close(stop)
_, _ = conn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, l.Key)
conn.Release()
}
return release, lost, true, nil
}package service
import (
"context"
"errors"
"time"
"academy/ecommerce-api-project/domain"
)
type timeT = time.Time
// Housekeeping holds the background jobs the worker runs on a ticker.
type Housekeeping struct {
Deps
AbandonedAfter time.Duration // e.g. 24h
}
// ReleaseExpired cancels unpaid orders whose stock hold ran out. Each order
// gets its own short transaction, re-reads the order and re-checks the
// status, so an order paid a millisecond ago is left alone.
func (h Housekeeping) ReleaseExpired(ctx context.Context) (int, error) {
now := h.Now()
var ids []string
err := h.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
os, err := tx.Orders().Expired(ctx, now, 100)
for _, o := range os {
ids = append(ids, o.ID)
}
return err
})
if err != nil {
return 0, err
}
n := 0
for _, id := range ids {
err := retryConflict(func() error {
return h.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
o, err := tx.Orders().Get(ctx, id)
if err != nil {
return err
}
if o.Status != domain.OrderCreated || !o.ExpiresAt.Before(now) {
return errSkip
}
return cancelInTx(ctx, tx, &o, now, "stock hold expired")
})
})
switch {
case err == nil:
n++
case errors.Is(err, errSkip):
default:
return n, err
}
}
return n, nil
}
var errSkip = errors.New("skip")
// RemindAbandoned writes one cart.abandoned event per customer cart idle
// for AbandonedAfter and marks the cart reminded, in the same transaction.
func (h Housekeeping) RemindAbandoned(ctx context.Context) (int, error) {
now := h.Now()
n := 0
err := h.Store.InTx(ctx, func(ctx context.Context, tx Tx) error {
cs, err := tx.Carts().Abandoned(ctx, now.Add(-h.AbandonedAfter), 100)
if err != nil {
return err
}
for _, c := range cs {
c.RemindedAt = &now
if err := tx.Carts().Save(ctx, &c); err != nil {
return err
}
ev := domain.NewEvent(domain.EvCartAbandoned, c.ID, c.UpdatedAt.Unix(), now,
map[string]any{"cart_id": c.ID, "user_id": c.UserID, "email": c.Email})
if err := tx.Outbox().Add(ctx, ev); err != nil {
return err
}
n++
}
return nil
})
return n, err
}Payment webhook: from PSP event to order status Important
In plain words: the payment provider tells you a payment succeeded by calling your webhook. Check the signature on the raw body, apply the event through the state machine, and answer 2xx quickly, also for duplicates.
Common misunderstanding: "The redirect back from the payment page means paid." The browser can close before the redirect, and the redirect can be faked; only the signed server-to-server event counts. Another: "Return 500 for an event about an order we do not know." The PSP retries it for days; acknowledge what is not yours and log it.
Definition: POST /v1/webhooks/psp reads the body under MaxBytesReader, verifies X-Signature: sha256=<hex> as HMAC-SHA256 of the raw body with hmac.Equal (constant time), decodes, and calls Orders.ApplyPayment. That method ignores anything but payment_intent.succeeded, ignores duplicates (payment already succeeded), refuses an amount different from the intent (422, alert), moves created → paid with payment.captured, or records refund_pending for a cancelled order. Stripe's real header (Stripe-Signature with a timestamp and replay window), event ordering and reconciliation are in Payment Processing Architecture; Stripe states that a succeeded PaymentIntent means "you can confidently fulfill the order".
PSP API Result
1 POST evt_1 succeeded, valid signature verify -> ApplyPayment -> paid v2 204
2 POST evt_1 again (retry) verify -> already succeeded -> no-op 204
3 POST forged body, signature sha256=00 hmac.Equal false 400
4 POST evt for unknown order ErrNotFound -> ack 204, logged
5 POST evt amount 1 instead of 7702 ErrAmountMismatch 422, alertReal scenario: a PSP that delivers each event at least once; an attacker posting "succeeded" for their own unpaid order; a partial capture configuration that sends a different amount; a webhook that arrives before the browser redirect.
| Check | Without it | Here |
|---|---|---|
| Signature on the raw body | anyone marks orders paid | HMAC-SHA256, hmac.Equal |
| Dedupe | double "paid" events, double mails | payment status + deterministic event id |
| Amount equals intent | underpayment accepted | ErrAmountMismatch |
| State machine | late event overwrites a final status | no edge, no change |
| Quick 2xx | PSP retries, duplicates pile up | 204 after one short transaction |
Fix / how to use it: pspWebhook and validSignature in the handlers file below; ApplyPayment in service/orders.go above.
Swagger/OpenAPI: swag annotations or oapi-codegen Important
In plain words: the API contract is a file clients can read and generate code from. Either write Go first and generate the file from comments (swag), or write the file first and generate Go from it (oapi-codegen). Whichever you pick, a test must fail when the code and the file disagree.
Common misunderstanding: "swag gives me OpenAPI 3." swag's README: "Swag converts Go annotations to Swagger Documentation 2.0"; for 3.x you convert, or use a spec-first tool. Another: "Generated docs are always right." Comments drift exactly like hand-written docs; only a test against the running routes keeps them honest.
Definition: the handlers carry swag declarative comments (@Summary, @Tags, @Security BearerAuth, @Param Idempotency-Key header string true "...", @Success 201 {object} OrderResponse, @Failure 409 {object} Problem, @Router /v1/orders [post]), so swag init -g cmd/api/main.go would produce a Swagger 2.0 docs/ package served by http-swagger. The served contract is the hand-maintained httpapi/openapi.json (OpenAPI 3.1.0, embedded, GET /openapi.json); TestEveryRouteIsInTheOpenAPIDocument walks API.Routes() and fails for any method and path missing from it. The spec-first alternative: oapi-codegen "to convert OpenAPI specifications to Go code, be it server-side implementations, API clients, or simply HTTP models", with a std-http-server target for net/http; then the interface is generated and the handlers implement it. Note the README's current table: the generated servers depend on github.com/oapi-codegen/runtime, "which requires Go 1.26", so a module pinned to Go 1.24 like this one must stay on an older oapi-codegen release or move its go line. A REST API in Go compares swag, oapi-codegen and ogen in depth.
Workflow Source of truth Generate Drift check
1 code-first (swag) Go comments swag init -> docs/swagger.json test routes vs generated file
2 spec-first (oapi) openapi.yaml oapi-codegen -> types + interface compiler: unimplemented method fails
3 this project openapi.json + routes (none) TestEveryRouteIsInTheOpenAPIDocumentReal scenario: a mobile team that generates its Swift/Kotlin client from the contract; a partner that needs a sandbox and docs; an API gateway that validates requests against the schema; a breaking change caught in review because the diff touched openapi.json.
| Tool | Direction | Output | OpenAPI version |
|---|---|---|---|
| swaggo/swag | code → spec | Swagger JSON/YAML + Go docs package | 2.0 |
| oapi-codegen | spec → code | server interface, models, client | 3.0, 3.1 (per its README) |
| ogen | spec → code | typed server and client | 3.x |
| hand-written + test (here) | both, checked | openapi.json | 3.1.0 |
Fix / how to use it: the handlers with their annotations, and the routes table the test walks.
package httpapi
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/service"
)
const maxBody = 1 << 20
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// readBody reads at most maxBody bytes and decodes strictly.
func readBody(w http.ResponseWriter, r *http.Request, dst any) ([]byte, error) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody))
if err != nil {
return nil, &service.ValidationError{Fields: []service.FieldError{{Field: "body", Message: "too large or unreadable"}}}
}
if len(raw) == 0 {
raw = []byte("{}")
}
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return nil, &service.ValidationError{Fields: []service.FieldError{{Field: "body", Message: err.Error()}}}
}
return raw, nil
}
func pathID(r *http.Request, name string) (int64, error) {
n, err := strconv.ParseInt(r.PathValue(name), 10, 64)
if err != nil || n <= 0 {
return 0, &service.ValidationError{Fields: []service.FieldError{{Field: name, Message: "positive integer"}}}
}
return n, nil
}
// listProducts godoc
//
// @Summary List the catalogue (keyset pagination)
// @Tags catalogue
// @Param q query string false "search in name and SKU"
// @Param category query int false "category id"
// @Param min_price query int false "minor units"
// @Param max_price query int false "minor units"
// @Param sort query string false "newest | price | -price | name"
// @Param limit query int false "1..100, default 20"
// @Param cursor query string false "next_cursor of the previous page"
// @Success 200 {object} ProductPage
// @Failure 422 {object} Problem
// @Router /v1/products [get]
func (a *API) listProducts(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
page, err := a.Catalog.List(r.Context(), service.ListParams{Search: q.Get("q"), Category: q.Get("category"),
MinPrice: q.Get("min_price"), MaxPrice: q.Get("max_price"), Sort: q.Get("sort"), Limit: q.Get("limit"),
Cursor: q.Get("cursor")})
if err != nil {
a.fail(w, r, err)
return
}
out := ProductPage{Items: []ProductResponse{}, NextCursor: page.NextCursor}
for _, p := range page.Items {
out.Items = append(out.Items, toProduct(p))
}
if page.NextCursor != "" {
q.Set("cursor", page.NextCursor)
w.Header().Set("Link", `<`+(&url.URL{Path: r.URL.Path, RawQuery: q.Encode()}).String()+`>; rel="next"`)
}
writeJSON(w, http.StatusOK, out)
}
// getProduct godoc
//
// @Summary One product; ETag carries the version
// @Tags catalogue
// @Param id path int true "product id"
// @Success 200 {object} ProductResponse
// @Failure 404 {object} Problem
// @Router /v1/products/{id} [get]
func (a *API) getProduct(w http.ResponseWriter, r *http.Request) {
id, err := pathID(r, "id")
if err == nil {
var p domain.Product
if p, err = a.Catalog.Get(r.Context(), id); err == nil {
w.Header().Set("ETag", strconv.Quote(strconv.FormatInt(p.Version, 10)))
writeJSON(w, http.StatusOK, toProduct(p))
return
}
}
a.fail(w, r, err)
}
// createProduct godoc
//
// @Summary Create a product (admin)
// @Tags admin
// @Security BearerAuth
// @Param body body CreateProductRequest true "product"
// @Success 201 {object} ProductResponse
// @Failure 401,403 {object} Problem
// @Failure 422 {object} Problem
// @Router /v1/admin/products [post]
func (a *API) createProduct(w http.ResponseWriter, r *http.Request) {
var in CreateProductRequest
if _, err := readBody(w, r, &in); err != nil {
a.fail(w, r, err)
return
}
who, _ := PrincipalFrom(r.Context())
p, err := a.Catalog.CreateProduct(r.Context(), who, service.ProductInput{SKU: in.SKU, Name: in.Name,
CategoryID: in.CategoryID, Price: in.Price, TaxClass: in.TaxClass, Stock: in.Stock})
if err != nil {
a.fail(w, r, err)
return
}
w.Header().Set("Location", "/v1/products/"+strconv.FormatInt(p.ID, 10))
writeJSON(w, http.StatusCreated, toProduct(p))
}
// updatePrice godoc
//
// @Summary Change a price; If-Match must carry the ETag (optimistic lock)
// @Tags admin
// @Security BearerAuth
// @Param id path int true "product id"
// @Param If-Match header string true "ETag from GET"
// @Param body body PriceRequest true "new price in minor units"
// @Success 200 {object} ProductResponse
// @Failure 412,428 {object} Problem
// @Router /v1/admin/products/{id}/price [put]
func (a *API) updatePrice(w http.ResponseWriter, r *http.Request) {
id, err := pathID(r, "id")
if err != nil {
a.fail(w, r, err)
return
}
version, err := strconv.ParseInt(strings.Trim(r.Header.Get("If-Match"), `"`), 10, 64)
if err != nil {
writeProblem(w, r, Problem{Title: "Precondition Required", Status: 428, Detail: "send If-Match with the ETag"})
return
}
var in PriceRequest
if _, err := readBody(w, r, &in); err != nil {
a.fail(w, r, err)
return
}
who, _ := PrincipalFrom(r.Context())
p, err := a.Catalog.UpdatePrice(r.Context(), who, id, in.Price, version)
if err != nil {
a.fail(w, r, err)
return
}
w.Header().Set("ETag", strconv.Quote(strconv.FormatInt(p.Version, 10)))
writeJSON(w, http.StatusOK, toProduct(p))
}
const cartCookie = "cart_id"
func (a *API) owner(r *http.Request) service.Owner {
o := service.Owner{}
o.Principal, _ = PrincipalFrom(r.Context())
if c, err := r.Cookie(cartCookie); err == nil {
o.GuestID = c.Value
}
return o
}
func setCartCookie(w http.ResponseWriter, id string, maxAge int) {
http.SetCookie(w, &http.Cookie{Name: cartCookie, Value: id, Path: "/", MaxAge: maxAge,
HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
}
// getCart godoc
//
// @Summary The caller's cart (customer, or guest via the cart_id cookie)
// @Tags cart
// @Success 200 {object} CartResponse
// @Router /v1/cart [get]
func (a *API) getCart(w http.ResponseWriter, r *http.Request) {
c, err := a.Carts.Get(r.Context(), a.owner(r))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toCart(c))
}
// putCartItem godoc
//
// @Summary Set the quantity of a product in the cart (0 removes it)
// @Tags cart
// @Param productID path int true "product id"
// @Param body body CartItemRequest true "quantity 0..10"
// @Success 200 {object} CartResponse
// @Failure 404,422 {object} Problem
// @Router /v1/cart/items/{productID} [put]
func (a *API) putCartItem(w http.ResponseWriter, r *http.Request) {
pid, err := pathID(r, "productID")
var in CartItemRequest
if err == nil {
_, err = readBody(w, r, &in)
}
if err != nil {
a.fail(w, r, err)
return
}
o := a.owner(r)
c, err := a.Carts.SetItem(r.Context(), o, pid, in.Qty)
if err != nil {
a.fail(w, r, err)
return
}
if o.Principal.UserID == 0 && o.GuestID != c.ID {
setCartCookie(w, c.ID, 30*24*3600)
}
writeJSON(w, http.StatusOK, toCart(c))
}
// mergeCart godoc
//
// @Summary Merge the guest cart (cookie) into the customer's cart after login
// @Tags cart
// @Security BearerAuth
// @Success 200 {object} CartResponse
// @Router /v1/cart/merge [post]
func (a *API) mergeCart(w http.ResponseWriter, r *http.Request) {
o := a.owner(r)
c, err := a.Carts.MergeOnLogin(r.Context(), o.GuestID, o.Principal)
if err != nil {
a.fail(w, r, err)
return
}
setCartCookie(w, "", -1)
writeJSON(w, http.StatusOK, toCart(c))
}
// placeOrder godoc
//
// @Summary Place an order from the cart (idempotent)
// @Tags orders
// @Security BearerAuth
// @Param Idempotency-Key header string true "8..255 chars, a UUID per checkout attempt"
// @Param body body PlaceOrderRequest false "optional discount code"
// @Success 201 {object} OrderResponse
// @Failure 400,401 {object} Problem
// @Failure 409 {object} Problem "out of stock, or same key still in flight"
// @Failure 422 {object} Problem "validation, empty cart, key reused with another body"
// @Router /v1/orders [post]
func (a *API) placeOrder(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" {
writeProblem(w, r, Problem{Type: problemBase + "idempotency-key-missing", Title: "Idempotency-Key header is required", Status: 400})
return
}
var in PlaceOrderRequest
raw, err := readBody(w, r, &in)
if err != nil {
a.fail(w, r, err)
return
}
sum := sha256.Sum256(raw)
who, _ := PrincipalFrom(r.Context())
res, err := a.Checkout.PlaceOrder(r.Context(), service.PlaceOrderInput{Who: who, IdempotencyKey: key,
Fingerprint: hex.EncodeToString(sum[:]), DiscountCode: in.DiscountCode})
if err != nil {
a.fail(w, r, err)
return
}
if res.Replayed {
w.Header().Set("Idempotent-Replayed", "true")
}
w.Header().Set("Location", "/v1/orders/"+res.Order.ID)
writeJSON(w, http.StatusCreated, toOrder(res.Order, &res.Payment))
}
// getOrder godoc
//
// @Summary One order (owner or admin)
// @Tags orders
// @Security BearerAuth
// @Param id path string true "order id"
// @Success 200 {object} OrderResponse
// @Failure 404 {object} Problem
// @Router /v1/orders/{id} [get]
func (a *API) getOrder(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
o, err := a.Orders.Get(r.Context(), who, r.PathValue("id"))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toOrder(o, nil))
}
// listOrders godoc
//
// @Summary The caller's latest orders
// @Tags orders
// @Security BearerAuth
// @Success 200 {array} OrderResponse
// @Router /v1/orders [get]
func (a *API) listOrders(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
os, err := a.Orders.List(r.Context(), who)
if err != nil {
a.fail(w, r, err)
return
}
out := []OrderResponse{}
for _, o := range os {
out = append(out, toOrder(o, nil))
}
writeJSON(w, http.StatusOK, out)
}
// cancelOrder godoc
//
// @Summary Cancel an unpaid order and release its stock
// @Tags orders
// @Security BearerAuth
// @Param id path string true "order id"
// @Success 200 {object} OrderResponse
// @Failure 404 {object} Problem
// @Failure 409 {object} Problem "already paid: ask for a refund"
// @Router /v1/orders/{id}/cancel [post]
func (a *API) cancelOrder(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
o, err := a.Orders.Cancel(r.Context(), who, r.PathValue("id"))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toOrder(o, nil))
}
// fulfilOrder godoc
//
// @Summary Mark a paid order as shipped (admin)
// @Tags admin
// @Security BearerAuth
// @Param id path string true "order id"
// @Success 200 {object} OrderResponse
// @Failure 409 {object} Problem
// @Router /v1/admin/orders/{id}/fulfil [post]
func (a *API) fulfilOrder(w http.ResponseWriter, r *http.Request) {
who, _ := PrincipalFrom(r.Context())
o, err := a.Orders.Fulfil(r.Context(), who, r.PathValue("id"))
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, toOrder(o, nil))
}
// pspWebhook godoc
//
// @Summary Payment provider events (HMAC-SHA256 signed body)
// @Tags payments
// @Param X-Signature header string true "sha256=<hex hmac of the raw body>"
// @Success 204
// @Failure 400 {object} Problem
// @Router /v1/webhooks/psp [post]
func (a *API) pspWebhook(w http.ResponseWriter, r *http.Request) {
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody))
if err != nil || !a.validSignature(raw, r.Header.Get("X-Signature")) {
writeProblem(w, r, Problem{Title: "Bad signature", Status: 400})
return
}
var ev PSPWebhook
if err := json.Unmarshal(raw, &ev); err != nil {
writeProblem(w, r, Problem{Title: "Bad body", Status: 400})
return
}
_, err = a.Orders.ApplyPayment(r.Context(), service.PSPEvent{EventID: ev.ID, Type: ev.Type, OrderID: ev.Data.OrderID,
ProviderRef: ev.Data.ProviderRef, Amount: money.New(ev.Data.Amount, money.Currency(strings.ToUpper(ev.Data.Currency)))})
if errors.Is(err, domain.ErrNotFound) {
err = nil // not ours (or deleted): ack so the PSP stops retrying
}
if err != nil {
a.fail(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *API) validSignature(body []byte, header string) bool {
got, ok := strings.CutPrefix(header, "sha256=")
if !ok || len(a.WebhookSecret) == 0 {
return false
}
want := hmac.New(sha256.New, a.WebhookSecret)
want.Write(body)
sig, err := hex.DecodeString(got)
return err == nil && hmac.Equal(sig, want.Sum(nil))
}// Package httpapi is the HTTP edge: Go 1.22 ServeMux patterns, DTOs, RFC
// 9457 problems, authentication, per-route authorization, rate limiting and
// security headers. Handlers carry swag annotations; openapi.json is the
// served contract and a test keeps the two in step.
package httpapi
import (
_ "embed"
"log/slog"
"net/http"
"academy/ecommerce-api-project/service"
)
//go:embed openapi.json
var openapiJSON []byte
// API holds the services the handlers call.
type API struct {
Catalog service.Catalog
Carts service.Carts
Checkout service.Checkout
Orders service.Orders
Auth Authenticator
Limiter *IPLimiter
WebhookSecret []byte
Ready func() error // database ping for /readyz
Log *slog.Logger
}
// Route is one line of the routes table.
type Route struct {
Pattern string
Handler http.HandlerFunc
}
// Routes is the whole API surface in one place.
func (a *API) Routes() []Route {
return []Route{
{"GET /v1/products", a.listProducts},
{"GET /v1/products/{id}", a.getProduct},
{"POST /v1/admin/products", admin(a.createProduct)},
{"PUT /v1/admin/products/{id}/price", admin(a.updatePrice)},
{"GET /v1/cart", a.getCart},
{"PUT /v1/cart/items/{productID}", a.putCartItem},
{"POST /v1/cart/merge", customer(a.mergeCart)},
{"POST /v1/orders", customer(a.placeOrder)},
{"GET /v1/orders", customer(a.listOrders)},
{"GET /v1/orders/{id}", customer(a.getOrder)},
{"POST /v1/orders/{id}/cancel", customer(a.cancelOrder)},
{"POST /v1/admin/orders/{id}/fulfil", admin(a.fulfilOrder)},
{"POST /v1/webhooks/psp", a.pspWebhook},
{"GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }},
{"GET /readyz", a.readyz},
{"GET /openapi.json", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(openapiJSON)
}},
}
}
func (a *API) readyz(w http.ResponseWriter, r *http.Request) {
if a.Ready != nil {
if err := a.Ready(); err != nil {
writeProblem(w, r, Problem{Title: "Not ready", Status: 503, Detail: "database unreachable"})
return
}
}
w.WriteHeader(http.StatusNoContent)
}
// Handler builds the mux and wraps it, outermost first.
func (a *API) Handler() http.Handler {
if a.Log == nil {
a.Log = slog.New(slog.DiscardHandler)
}
if a.Auth == nil {
a.Auth = StaticTokens{}
}
mux := http.NewServeMux()
for _, rt := range a.Routes() {
mux.HandleFunc(rt.Pattern, rt.Handler)
}
return chain(mux, requestID, a.logRequests, a.recoverer, securityHeaders, a.rateLimit, a.authenticate)
}Rate limiting and security headers Important
In plain words: limit how fast one client may call you, so a script cannot test stolen cards, scrape the catalogue or exhaust stock with fake checkouts, and send the few response headers that stop browsers from misusing your JSON.
Common misunderstanding: "Rate limiting is the gateway's job." Usually yes in front, but the application knows things the gateway does not (customer id, which endpoint places orders) and is the last line when the gateway is misconfigured. Another: "Use X-Forwarded-For as the client IP." Anyone can send that header; trust it only when your own proxy sets it and strips the client's.
Definition: httpapi.IPLimiter keeps one golang.org/x/time/rate token bucket per client IP (rate.NewLimiter(r, burst), Allow()); over the limit the API answers 429 with Retry-After: 1 (defaults 20 requests/s, burst 40, ECOM_RATE_RPS, ECOM_RATE_BURST). The x/time/rate source: "A Limiter controls how frequently events are allowed to happen. It implements a "token bucket" of size b, initially full and refilled at rate r tokens per second." securityHeaders sets what the OWASP REST Security Cheat Sheet lists for API responses: Cache-Control: no-store, Content-Security-Policy: frame-ancestors 'none', X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Strict-Transport-Security, plus Referrer-Policy: no-referrer. The full middleware set (CORS, compression, logging, recover) is in Middlewares; algorithms (token bucket, sliding window, Redis-backed limits for many replicas) in Rate Limiting in Go.
Request (one IP, 1 rps, burst 2) Tokens before Answer
1 GET /healthz 2 204
2 GET /healthz 1 204
3 GET /healthz 0 429 rate-limited, Retry-After: 1
4 GET /healthz (same second) 0 429Real scenario: card testing through the checkout (many small orders, see the payments chapter's card-testing fix); a scraper paging the catalogue; a bot reserving stock with unpaid orders during a launch (the stock-release timeout plus a per-customer limit on open orders); an XSS on another site trying to frame your API responses.
| Header | Value | Stops |
|---|---|---|
Cache-Control | no-store | personal data in shared caches |
Content-Security-Policy | frame-ancestors 'none' | framing (clickjacking) |
X-Content-Type-Options | nosniff | JSON interpreted as HTML |
X-Frame-Options | DENY | framing in old browsers |
Strict-Transport-Security | max-age=63072000; includeSubDomains | downgrade to HTTP |
Referrer-Policy | no-referrer | URLs with ids leaking to third parties |
Fix / how to use it: see securityHeaders, IPLimiter and rateLimit in the middleware file; TestRateLimit asserts 204 204 429 429.
Testing: table-driven services with fake repos, httptest API tests, transaction tests on a real Postgres pointer Must-know
In plain words: most rules are tested against the in-memory store, fast and in parallel; the HTTP layer is tested through a real server on a random port; the few things only PostgreSQL can prove (locks, ON CONFLICT, constraints) get a separate test that runs against a real database when you ask for it.
Common misunderstanding: "Mock every repository method with a mocking library." For a shop, a working fake (memstore) is better than mocks: it enforces the same contract (rollback on error, version checks, keyset order), so the service tests read like specifications. Another: "The in-memory store proves there is no oversell in production." It serialises transactions with one mutex, which is stronger than PostgreSQL's READ COMMITTED; it proves the business rule, and only the integration test proves the locking. Third: "go test ./... should start a database." Then nobody runs the tests; keep the database tests behind a build tag.
Definition: three levels. Services: table-driven tests (TestPlaceOrder with happy path, discount, unknown code, out of stock), concurrency under -race (50 buyers, 10 units), race between expiry and capture (both orders and concurrent), idempotency, BOLA, optimistic locking, all with memstore, a fake clock and a counter id generator. HTTP: httptest.NewTLSServer(api.Handler()) (TLS so the Secure cart cookie round-trips through a cookiejar), table-driven problem tests, the spec-drift test. Adapters: pgstore_test.go fakes pgx.Tx by embedding the interface and implementing only Exec, Commit, Rollback, to prove the retry loop on 40001/40P01/23505 and ErrBusy on 55P03; the SQL builder is tested as strings and args. The real-Postgres tests are in integration_test.go with //go:build integration and ECOM_TEST_DATABASE_URL: each run creates a throwaway schema, applies the migration, and checks that 20 concurrent checkouts for 5 units give exactly 5 orders and that two concurrent requests with one Idempotency-Key create one order. Testcontainers-go is the usual way to start that database from the test; it is not used here (no Docker in this lab). Test techniques in general: Testing & Benchmarking.
Level Test Needs Time (this machine)
1 unit money, pricing, domain nothing < 0.1 s
2 service checkout, orders, cart, catalogue (memstore) nothing < 0.1 s, -race ok
3 adapter pgstore retry, SQL builder, migration text nothing < 0.1 s
4 HTTP httptest server, cookies, problems, spec nothing < 0.5 s
5 end to end app: HTTP -> outbox -> relay -> mail nothing ~0.2 s
6 database -tags integration, ECOM_TEST_DATABASE_URL PostgreSQL expected, not run hereReal scenario: a pricing change reviewed by reading the table diff; a regression where a refactor dropped the version check, caught by the expiry-vs-capture test; a handler that forgot to map a new error, caught by the problem table test; a new route without documentation, caught by the spec test.
| What | Proved by | File |
|---|---|---|
| No oversell (rule) | TestNoOversellUnderConcurrency | service/checkout_test.go |
| No oversell (locks) | TestConcurrentCheckoutsNeverOversell | pgstore/integration_test.go |
| Retry replays, other body 422 | TestPlaceOrderIsIdempotent, TestCheckoutEndToEnd | service, httpapi |
| Late capture vs timeout | TestStockReleaseTimeout | service/orders_test.go |
| One mail per event | TestRedeliveredOrderPlacedSendsOneMail | worker/worker_test.go |
| Relay order kept | TestRelayStopsAtFirstFailureThenResumesInOrder | outbox/outbox_test.go |
| Spec matches routes | TestEveryRouteIsInTheOpenAPIDocument | httpapi/httpapi_test.go |
| Graceful stop | TestOrderPlacedReachesTheMailboxAndShutdownIsClean | app/app_test.go |
Fix / how to use it: the service fixture and the order tests; the HTTP tests; the integration test.
package service
import (
"errors"
"sync"
"testing"
"time"
"academy/ecommerce-api-project/domain"
)
func placed(t *testing.T, f *fixture, who domain.Principal, qty int64) (domain.Order, int64) {
t.Helper()
id := f.product(t, "SKU-"+who.Email, 1000, 10)
if _, err := f.carts.SetItem(t.Context(), Owner{Principal: who}, id, qty); err != nil {
t.Fatal(err)
}
r, err := f.checkout.PlaceOrder(t.Context(), PlaceOrderInput{Who: who, IdempotencyKey: "key-" + who.Email})
if err != nil {
t.Fatal(err)
}
return r.Order, id
}
func succeeded(o domain.Order) PSPEvent {
return PSPEvent{EventID: "evt_1", Type: "payment_intent.succeeded", OrderID: o.ID, ProviderRef: "pi_1", Amount: o.Total}
}
func TestPaymentMovesOrderToPaidOnce(t *testing.T) {
f := newFixture(t)
o, _ := placed(t, f, alice, 1)
for range 2 { // the PSP delivers the webhook twice
got, err := f.orders.ApplyPayment(t.Context(), succeeded(o))
if err != nil || got.Status != domain.OrderPaid || got.Version != 2 {
t.Fatalf("got %s v%d %v", got.Status, got.Version, err)
}
}
n := 0
for _, e := range f.store.Unpublished() {
if e.Type == domain.EvPaymentCaptured {
n++
}
}
if n != 1 {
t.Fatalf("%d payment.captured events", n)
}
bad := succeeded(o)
bad.Amount = eur(1)
o2, _ := placed(t, f, bob, 1)
bad.OrderID = o2.ID
if _, err := f.orders.ApplyPayment(t.Context(), bad); !errors.Is(err, ErrAmountMismatch) {
t.Fatalf("amount mismatch: %v", err)
}
}
func TestStateMachineThroughServices(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 2)
if _, err := f.orders.Fulfil(t.Context(), admin, o.ID); !errors.Is(err, domain.ErrInvalidTransition) {
t.Fatalf("fulfil unpaid: %v", err)
}
if _, err := f.orders.ApplyPayment(t.Context(), succeeded(o)); err != nil {
t.Fatal(err)
}
if _, err := f.orders.Cancel(t.Context(), alice, o.ID); !errors.Is(err, domain.ErrInvalidTransition) {
t.Fatalf("cancel paid: %v", err)
}
if _, err := f.orders.Fulfil(t.Context(), alice, o.ID); !errors.Is(err, domain.ErrForbidden) {
t.Fatalf("customer fulfil: %v", err)
}
got, err := f.orders.Fulfil(t.Context(), admin, o.ID)
if err != nil || got.Status != domain.OrderFulfilled {
t.Fatalf("fulfil: %s %v", got.Status, err)
}
if s := f.stock(t, pid); s.OnHand != 8 || s.Reserved != 0 {
t.Fatalf("after shipping: %+v", s)
}
}
func TestCustomersSeeOnlyTheirOrders(t *testing.T) {
f := newFixture(t)
o, _ := placed(t, f, alice, 1)
if _, err := f.orders.Get(t.Context(), bob, o.ID); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("bob reads alice's order: %v", err)
}
if _, err := f.orders.Cancel(t.Context(), bob, o.ID); !errors.Is(err, domain.ErrNotFound) {
t.Fatalf("bob cancels alice's order: %v", err)
}
if _, err := f.orders.Get(t.Context(), admin, o.ID); err != nil {
t.Fatalf("admin: %v", err)
}
}
func TestStockReleaseTimeout(t *testing.T) {
t.Run("expiry first, late capture asks for a refund", func(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 3)
f.clock.Add(16 * time.Minute)
for range 2 { // the job runs twice; stock is released once
if _, err := f.house.ReleaseExpired(t.Context()); err != nil {
t.Fatal(err)
}
}
if s := f.stock(t, pid); s.Reserved != 0 || s.OnHand != 10 {
t.Fatalf("stock %+v", s)
}
got, err := f.orders.ApplyPayment(t.Context(), succeeded(o))
if err != nil || got.Status != domain.OrderCancelled {
t.Fatalf("late capture: %s %v", got.Status, err)
}
if p := f.payment(t, o.ID); p.Status != domain.PaymentRefundPending {
t.Fatalf("payment %s", p.Status)
}
})
t.Run("capture first, expiry leaves the order alone", func(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 3)
if _, err := f.orders.ApplyPayment(t.Context(), succeeded(o)); err != nil {
t.Fatal(err)
}
f.clock.Add(16 * time.Minute)
if n, err := f.house.ReleaseExpired(t.Context()); err != nil || n != 0 {
t.Fatalf("released %d %v", n, err)
}
if s := f.stock(t, pid); s.Reserved != 3 {
t.Fatalf("stock %+v", s)
}
})
t.Run("concurrent: exactly one outcome", func(t *testing.T) {
f := newFixture(t)
o, pid := placed(t, f, alice, 3)
f.clock.Add(16 * time.Minute)
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); _, _ = f.house.ReleaseExpired(t.Context()) }()
go func() { defer wg.Done(); _, _ = f.orders.ApplyPayment(t.Context(), succeeded(o)) }()
wg.Wait()
got, _ := f.orders.Get(t.Context(), admin, o.ID)
s, p := f.stock(t, pid), f.payment(t, o.ID)
switch got.Status {
case domain.OrderPaid:
if s.Reserved != 3 || p.Status != domain.PaymentSucceeded {
t.Fatalf("paid but stock %+v payment %s", s, p.Status)
}
case domain.OrderCancelled:
if s.Reserved != 0 || p.Status != domain.PaymentRefundPending {
t.Fatalf("cancelled but stock %+v payment %s", s, p.Status)
}
default:
t.Fatalf("status %s", got.Status)
}
})
}
func TestAbandonedCartReminderOnce(t *testing.T) {
f := newFixture(t)
id := f.product(t, "BOOK", 1500, 5)
_, _ = f.carts.SetItem(t.Context(), Owner{Principal: alice}, id, 1)
_, _ = f.carts.SetItem(t.Context(), Owner{GuestID: ""}, id, 1) // guests have no e-mail: never reminded
f.clock.Add(25 * time.Hour)
for want := range []int{1, 0} {
n, err := f.house.RemindAbandoned(t.Context())
if err != nil || n != 1-want {
t.Fatalf("run %d: %d %v", want, n, err)
}
}
}package httpapi
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/memstore"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/service"
)
const secret = "whsec_test"
type harness struct {
srv *httptest.Server
store *memstore.Store
}
func newHarness(t *testing.T) *harness {
t.Helper()
var n atomic.Int64
s := memstore.New()
d := service.Deps{Store: s, Now: time.Now, Currency: "EUR",
NewID: func(p string) string { return fmt.Sprintf("%s_%d", p, n.Add(1)) },
TaxRates: pricing.TaxRates{"standard": 2000}}
api := &API{Catalog: service.Catalog{Deps: d}, Carts: service.Carts{Deps: d}, Checkout: service.Checkout{Deps: d},
Orders: service.Orders{Deps: d}, WebhookSecret: []byte(secret), Limiter: NewIPLimiter(1000, 1000),
Auth: StaticTokens{
"t-admin": {UserID: 1, Email: "admin@shop.example", Role: domain.RoleAdmin},
"t-alice": {UserID: 7, Email: "alice@example.com", Role: domain.RoleCustomer},
"t-bob": {UserID: 8, Email: "bob@example.com", Role: domain.RoleCustomer},
}}
srv := httptest.NewTLSServer(api.Handler()) // TLS so the Secure cart cookie round-trips
t.Cleanup(srv.Close)
return &harness{srv: srv, store: s}
}
type call struct {
method, path, token, body string
header map[string]string
}
func (h *harness) do(t *testing.T, c *http.Client, x call) (*http.Response, map[string]any) {
t.Helper()
req, _ := http.NewRequestWithContext(t.Context(), x.method, h.srv.URL+x.path, strings.NewReader(x.body))
if x.token != "" {
req.Header.Set("Authorization", "Bearer "+x.token)
}
for k, v := range x.header {
req.Header.Set(k, v)
}
if c == nil {
c = h.srv.Client()
}
res, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
var m map[string]any
_ = json.Unmarshal(raw, &m)
return res, m
}
func (h *harness) seedProduct(t *testing.T, stock int) string {
res, body := h.do(t, nil, call{method: "POST", path: "/v1/admin/products", token: "t-admin",
body: fmt.Sprintf(`{"sku":"MUG","name":"Mug","price":1000,"tax_class":"standard","stock":%d}`, stock)})
if res.StatusCode != 201 {
t.Fatalf("seed: %d %v", res.StatusCode, body)
}
return fmt.Sprint(body["id"])
}
func TestCheckoutEndToEnd(t *testing.T) {
h := newHarness(t)
pid := h.seedProduct(t, 3)
if res, _ := h.do(t, nil, call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-alice", body: `{"qty":2}`}); res.StatusCode != 200 {
t.Fatalf("cart: %d", res.StatusCode)
}
order := call{method: "POST", path: "/v1/orders", token: "t-alice", body: `{}`,
header: map[string]string{"Idempotency-Key": "4f1c9d1e-attempt"}}
res, body := h.do(t, nil, order)
if res.StatusCode != 201 || body["status"] != "created" || res.Header.Get("Location") == "" {
t.Fatalf("place: %d %v", res.StatusCode, body)
}
if total := body["total"].(map[string]any); total["amount"] != float64(2400) || body["payment_status"] != "requires_payment_method" {
t.Fatalf("total %v", body)
}
id := body["id"].(string)
// The client timed out and retries: same order, no second reservation.
res, again := h.do(t, nil, order)
if res.StatusCode != 201 || again["id"] != id || res.Header.Get("Idempotent-Replayed") != "true" {
t.Fatalf("replay: %d %v", res.StatusCode, again)
}
order.body = `{"discount_code":"OTHER"}`
if res, p := h.do(t, nil, order); res.StatusCode != 422 || p["type"] != problemBase+"idempotency-key-reused" {
t.Fatalf("reuse: %d %v", res.StatusCode, p)
}
// Bob may not see it; the answer does not even confirm it exists.
if res, _ := h.do(t, nil, call{method: "GET", path: "/v1/orders/" + id, token: "t-bob"}); res.StatusCode != 404 {
t.Fatalf("bob: %d", res.StatusCode)
}
// Signed webhook moves the order to paid; a forged one is rejected.
hook := fmt.Sprintf(`{"id":"evt_1","type":"payment_intent.succeeded","data":{"order_id":%q,"provider_ref":"pi_1","amount":2400,"currency":"eur"}}`, id)
if res, _ := h.do(t, nil, call{method: "POST", path: "/v1/webhooks/psp", body: hook,
header: map[string]string{"X-Signature": "sha256=00"}}); res.StatusCode != 400 {
t.Fatalf("forged: %d", res.StatusCode)
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(hook))
sig := map[string]string{"X-Signature": "sha256=" + hex.EncodeToString(mac.Sum(nil))}
for range 2 {
if res, _ := h.do(t, nil, call{method: "POST", path: "/v1/webhooks/psp", body: hook, header: sig}); res.StatusCode != 204 {
t.Fatalf("webhook: %d", res.StatusCode)
}
}
if _, o := h.do(t, nil, call{method: "GET", path: "/v1/orders/" + id, token: "t-alice"}); o["status"] != "paid" {
t.Fatalf("after webhook: %v", o)
}
if res, _ := h.do(t, nil, call{method: "POST", path: "/v1/orders/" + id + "/cancel", token: "t-alice"}); res.StatusCode != 409 {
t.Fatalf("cancel paid: %d", res.StatusCode)
}
if res, o := h.do(t, nil, call{method: "POST", path: "/v1/admin/orders/" + id + "/fulfil", token: "t-admin"}); res.StatusCode != 200 || o["status"] != "fulfilled" {
t.Fatalf("fulfil: %d %v", res.StatusCode, o)
}
var types []string
for _, e := range h.store.Unpublished() {
types = append(types, e.Type)
}
if strings.Join(types, ",") != "order.placed,payment.captured,order.fulfilled" {
t.Fatalf("outbox %v", types)
}
}
func TestErrorsAreProblemDetails(t *testing.T) {
h := newHarness(t)
pid := h.seedProduct(t, 1)
tests := []struct {
name string
c call
status int
ptype string
}{
{"no token", call{method: "POST", path: "/v1/orders"}, 401, "about:blank"},
{"customer on admin route", call{method: "POST", path: "/v1/admin/products", token: "t-alice", body: `{}`}, 403, "about:blank"},
{"missing key", call{method: "POST", path: "/v1/orders", token: "t-alice"}, 400, problemBase + "idempotency-key-missing"},
{"empty cart", call{method: "POST", path: "/v1/orders", token: "t-alice", header: map[string]string{"Idempotency-Key": "empty-cart-1"}}, 422, problemBase + "cart"},
{"unknown field", call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-alice", body: `{"qty":1,"price":1}`}, 422, problemBase + "validation"},
{"qty too big", call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-alice", body: `{"qty":11}`}, 422, problemBase + "validation"},
{"bad sort", call{method: "GET", path: "/v1/products?sort=hack"}, 422, problemBase + "validation"},
{"price without If-Match", call{method: "PUT", path: "/v1/admin/products/" + pid + "/price", token: "t-admin", body: `{"price":5}`}, 428, "about:blank"},
{"stale If-Match", call{method: "PUT", path: "/v1/admin/products/" + pid + "/price", token: "t-admin", body: `{"price":5}`,
header: map[string]string{"If-Match": `"7"`}}, 412, problemBase + "version-conflict"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res, p := h.do(t, nil, tt.c)
if res.StatusCode != tt.status || p["type"] != tt.ptype || res.Header.Get("Content-Type") != "application/problem+json" {
t.Fatalf("%d %v %s", res.StatusCode, p, res.Header.Get("Content-Type"))
}
if p["request_id"] == "" || res.Header.Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("missing request id or security headers: %v", res.Header)
}
})
}
// Out of stock carries the product and what is left.
h.do(t, nil, call{method: "PUT", path: "/v1/cart/items/" + pid, token: "t-bob", body: `{"qty":2}`})
res, p := h.do(t, nil, call{method: "POST", path: "/v1/orders", token: "t-bob", header: map[string]string{"Idempotency-Key": "bob-order-1"}})
if res.StatusCode != 409 || p["available"] != float64(1) {
t.Fatalf("oos: %d %v", res.StatusCode, p)
}
}
func TestGuestCartCookieAndMergeOnLogin(t *testing.T) {
h := newHarness(t)
pid := h.seedProduct(t, 10)
jar, _ := cookiejar.New(nil)
browser := h.srv.Client()
browser.Jar = jar
if res, _ := h.do(t, browser, call{method: "PUT", path: "/v1/cart/items/" + pid, body: `{"qty":3}`}); res.StatusCode != 200 ||
!strings.Contains(res.Header.Get("Set-Cookie"), "HttpOnly") {
t.Fatalf("guest add: %d %v", res.StatusCode, res.Header.Get("Set-Cookie"))
}
if _, c := h.do(t, browser, call{method: "GET", path: "/v1/cart"}); len(c["items"].([]any)) != 1 {
t.Fatalf("guest cart: %v", c)
}
_, merged := h.do(t, browser, call{method: "POST", path: "/v1/cart/merge", token: "t-alice"})
items := merged["items"].([]any)
if len(items) != 1 || items[0].(map[string]any)["qty"] != float64(3) {
t.Fatalf("merged %v", merged)
}
}
func TestKeysetLinkHeader(t *testing.T) {
h := newHarness(t)
for i := range 3 {
h.do(t, nil, call{method: "POST", path: "/v1/admin/products", token: "t-admin",
body: fmt.Sprintf(`{"sku":"S%d","name":"P%d","price":%d,"tax_class":"standard"}`, i, i, 100+i)})
}
res, page := h.do(t, nil, call{method: "GET", path: "/v1/products?sort=price&limit=2"})
link := res.Header.Get("Link")
if len(page["items"].([]any)) != 2 || !strings.Contains(link, `rel="next"`) || page["next_cursor"] == "" {
t.Fatalf("page 1: %v %s", page, link)
}
_, page2 := h.do(t, nil, call{method: "GET", path: "/v1/products?sort=price&limit=2&cursor=" + page["next_cursor"].(string)})
if len(page2["items"].([]any)) != 1 || page2["next_cursor"] != nil {
t.Fatalf("page 2: %v", page2)
}
}
func TestRateLimit(t *testing.T) {
h := newHarness(t)
srv := httptest.NewServer((&API{Limiter: NewIPLimiter(1, 2), Catalog: service.Catalog{Deps: service.Deps{Store: h.store}}}).Handler())
defer srv.Close()
codes := ""
for range 4 {
res, err := http.Get(srv.URL + "/healthz")
if err != nil {
t.Fatal(err)
}
res.Body.Close()
codes += fmt.Sprint(res.StatusCode, " ")
}
if codes != "204 204 429 429 " {
t.Fatalf("codes %s", codes)
}
}
// Spec drift: every route in the mux is documented in openapi.json.
func TestEveryRouteIsInTheOpenAPIDocument(t *testing.T) {
var spec struct {
OpenAPI string `json:"openapi"`
Paths map[string]map[string]any `json:"paths"`
}
if err := json.NewDecoder(bytes.NewReader(openapiJSON)).Decode(&spec); err != nil {
t.Fatal(err)
}
if spec.OpenAPI != "3.1.0" {
t.Fatalf("openapi %q", spec.OpenAPI)
}
for _, rt := range (&API{}).Routes() {
method, path, _ := strings.Cut(rt.Pattern, " ")
if _, ok := spec.Paths[path][strings.ToLower(method)]; !ok {
t.Errorf("%s is not documented", rt.Pattern)
}
}
}//go:build integration
// Run against a throwaway PostgreSQL:
//
// ECOM_TEST_DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable \
// go test -tags integration -race -count=1 ./pgstore/
package pgstore_test
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/pgstore"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/service"
)
func pool(t *testing.T) *pgxpool.Pool {
t.Helper()
dsn := os.Getenv("ECOM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("ECOM_TEST_DATABASE_URL not set")
}
ctx := t.Context()
schema := fmt.Sprintf("t%d", time.Now().UnixNano())
admin, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Fatal(err)
}
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = admin.Exec(context.Background(), "DROP SCHEMA "+schema+" CASCADE"); admin.Close() })
cfg, _ := pgxpool.ParseConfig(dsn)
cfg.ConnConfig.RuntimeParams["search_path"] = schema
cfg.MaxConns = 30
p, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
t.Cleanup(p.Close)
up, _ := fs.ReadFile(pgstore.Migrations, "migrations/0001_init.up.sql")
if _, err := p.Exec(ctx, string(up)); err != nil {
t.Fatal(err)
}
return p
}
func TestConcurrentCheckoutsNeverOversell(t *testing.T) {
p := pool(t)
ctx := t.Context()
var n atomic.Int64
d := service.Deps{Store: pgstore.New(p), Now: time.Now, Currency: "EUR",
NewID: func(pfx string) string { return fmt.Sprintf("%s_%d_%d", pfx, time.Now().UnixNano(), n.Add(1)) },
TaxRates: pricing.TaxRates{"standard": 2000}}
var pid int64
_ = p.QueryRow(ctx, `INSERT INTO products (sku, name, price_minor, currency, tax_class) VALUES ('LAST','Last one',500,'EUR','standard') RETURNING id`).Scan(&pid)
_, _ = p.Exec(ctx, `INSERT INTO inventory (product_id, on_hand) VALUES ($1, 5)`, pid)
var wg sync.WaitGroup
var ok, oos atomic.Int32
for i := range 20 {
var uid int64
_ = p.QueryRow(ctx, `INSERT INTO users (email) VALUES ($1) RETURNING id`, fmt.Sprintf("u%d@example.com", i)).Scan(&uid)
who := domain.Principal{UserID: uid, Email: fmt.Sprintf("u%d@example.com", i), Role: domain.RoleCustomer}
if _, err := (service.Carts{Deps: d}).SetItem(ctx, service.Owner{Principal: who}, pid, 1); err != nil {
t.Fatal(err)
}
wg.Add(1)
go func() {
defer wg.Done()
_, err := (service.Checkout{Deps: d}).PlaceOrder(ctx, service.PlaceOrderInput{Who: who, IdempotencyKey: fmt.Sprintf("checkout-%d", i)})
var e *domain.OutOfStockError
switch {
case err == nil:
ok.Add(1)
case errors.As(err, &e):
oos.Add(1)
default:
t.Error(err)
}
}()
}
wg.Wait()
var reserved int64
_ = p.QueryRow(ctx, `SELECT reserved FROM inventory WHERE product_id = $1`, pid).Scan(&reserved)
if ok.Load() != 5 || oos.Load() != 15 || reserved != 5 {
t.Fatalf("ok %d oos %d reserved %d", ok.Load(), oos.Load(), reserved)
}
}
func TestSameIdempotencyKeyConcurrentlyCreatesOneOrder(t *testing.T) {
// Stock 1 on purpose: if the duplicate did the work instead of waiting on
// the key, it would answer 409 out of stock although the order exists.
p := pool(t)
ctx := t.Context()
s := pgstore.New(p)
d := service.Deps{Store: s, Now: time.Now, Currency: "EUR", NewID: service.RandomID, TaxRates: pricing.TaxRates{"standard": 2000}}
var pid, uid int64
_ = p.QueryRow(ctx, `INSERT INTO products (sku, name, price_minor, currency, tax_class) VALUES ('MUG','Mug',1000,'EUR','standard') RETURNING id`).Scan(&pid)
_, _ = p.Exec(ctx, `INSERT INTO inventory (product_id, on_hand) VALUES ($1, 1)`, pid)
_ = p.QueryRow(ctx, `INSERT INTO users (email) VALUES ('alice@example.com') RETURNING id`).Scan(&uid)
who := domain.Principal{UserID: uid, Email: "alice@example.com", Role: domain.RoleCustomer}
_, _ = (service.Carts{Deps: d}).SetItem(ctx, service.Owner{Principal: who}, pid, 1)
var wg sync.WaitGroup
ids := make([]string, 2)
for i := range 2 {
wg.Add(1)
go func() {
defer wg.Done()
r, err := (service.Checkout{Deps: d}).PlaceOrder(ctx, service.PlaceOrderInput{Who: who, IdempotencyKey: "double-click-1", Fingerprint: "fp"})
if err != nil {
t.Error(err) // neither 409 out of stock nor 422 empty cart is acceptable
}
ids[i] = r.Order.ID
}()
}
wg.Wait()
var orders int
_ = p.QueryRow(ctx, `SELECT count(*) FROM orders`).Scan(&orders)
if orders != 1 || ids[0] == "" || ids[0] != ids[1] {
t.Fatalf("%d orders, ids %v", orders, ids)
}
}
// Two tabs add different products to one cart at the same time; with the
// version check (and the retry in SetItem) neither item is lost.
func TestConcurrentCartUpdatesLoseNothing(t *testing.T) {
p := pool(t)
ctx := t.Context()
d := service.Deps{Store: pgstore.New(p), Now: time.Now, Currency: "EUR", NewID: service.RandomID, TaxRates: pricing.TaxRates{"standard": 2000}}
var uid int64
_ = p.QueryRow(ctx, `INSERT INTO users (email) VALUES ('tabs@example.com') RETURNING id`).Scan(&uid)
who := domain.Principal{UserID: uid, Email: "tabs@example.com", Role: domain.RoleCustomer}
ids := make([]int64, 10)
for i := range ids {
_ = p.QueryRow(ctx, `INSERT INTO products (sku, name, price_minor, currency, tax_class) VALUES ($1,'P',100,'EUR','standard') RETURNING id`, fmt.Sprintf("P%d", i)).Scan(&ids[i])
}
var wg sync.WaitGroup
for _, id := range ids {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := (service.Carts{Deps: d}).SetItem(ctx, service.Owner{Principal: who}, id, 1); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
var n int
_ = p.QueryRow(ctx, `SELECT count(*) FROM cart_items i JOIN carts c ON c.id = i.cart_id WHERE c.user_id = $1`, uid).Scan(&n)
if n != len(ids) {
t.Fatalf("%d of %d items survived", n, len(ids))
}
}
func TestOnlyOneReplicaHoldsTheLeaderLease(t *testing.T) {
p := pool(t)
a, b := pgstore.Lease{Pool: p, Key: 99}, pgstore.Lease{Pool: p, Key: 99}
release, _, ok, err := a.TryAcquire(t.Context())
if err != nil || !ok {
t.Fatalf("a: %v %v", ok, err)
}
if _, _, ok, _ := b.TryAcquire(t.Context()); ok {
t.Fatal("b got the lease while a holds it")
}
release()
rb, _, ok, _ := b.TryAcquire(t.Context())
if !ok {
t.Fatal("b did not get the released lease")
}
rb()
}Observability: logs, metrics, traces for a shop Important
In plain words: when a customer says "I paid and got no mail", you must be able to follow that one order through the API, the database, the relay and the worker. Log with the request id and the order id, count the business events, and time the slow steps.
Common misunderstanding: "Request logs are enough." They show that POST /v1/orders returned 201, not that the mail was sent 40 seconds later on the second attempt. Business events (orders placed, payments captured, stock released, mails failed) need their own log lines and counters. Another: "Log the request body." It contains addresses and, in a careless payment flow, card data; log ids, never bodies.
Definition: logRequests writes one slog line per request (method, path, status, took, request_id); requestID accepts a client X-Request-ID up to 64 characters or creates one and returns it in the header and in every problem body; the worker logs job done with items and job failed with err; mailer.LogSender logs message_id. In production add: counters orders_placed_total, checkout_out_of_stock_total, outbox_unpublished (a gauge from SELECT count(*) ... WHERE published_at IS NULL, the single best health signal of the event pipeline), outbox_oldest_age_seconds, mail_send_failures_total; histograms for checkout latency and InTx attempts; OpenTelemetry spans around InTx, the relay publish and the SMTP send, with the event id carried in the RabbitMQ headers (the tracing part is shown in Event-Driven Go).
Time Component Line (JSON, abridged)
1 01:02:18 api {"msg":"http","method":"POST","path":"/v1/orders","status":201,"request_id":"ae25dc..."}
2 01:02:18 worker {"msg":"mail (not sent)","to":"alice@example.com","message_id":"order.placed:ord_1c36...:v1@shop.example"}
3 01:02:18 relay {"msg":"job done","job":"outbox-relay","items":2}
4 01:02:19 api {"msg":"stopped","err":null}
(real lines from a lab run; the mail is logged because ECOM_SMTP_HOST was empty)Real scenario: an alert when outbox_unpublished grows for five minutes (broker or SMTP down); a dashboard of out-of-stock answers per product during a launch; a support search by order id across API and worker logs; a trace showing that checkout latency is the FOR UPDATE wait on one hot SKU.
| Signal | Source | Alert when |
|---|---|---|
outbox_unpublished, oldest age | SQL gauge | growing for 5 min |
| checkout p99 latency | histogram around PlaceOrder | above the SLO |
InTx attempts > 1 | counter | sudden rise (contention, deadlocks) |
| out-of-stock rate per SKU | counter | spike during a sale (expected) vs normal day |
| mail failures (permanent) | counter | any |
| stock released by timeout | counter | many: checkout or PSP problem |
Fix / how to use it: logRequests, requestID and the recoverer are in the middleware file; the job logging is in worker.RunJobs.
Graceful shutdown, env config, deployment and Docker Must-know
In plain words: configuration comes from environment variables, read once and checked at start; the process stops by finishing what it is doing (requests in flight, the current job) and then exiting; it ships as a small container built in two stages; the database migrations run as their own step.
Common misunderstanding: "os.Exit on SIGTERM is fine, the load balancer retries." A checkout killed between BEGIN and COMMIT rolls back, which is safe, but a relay killed after publishing and before marking republishes, and a mail worker killed mid-SMTP resends. Graceful shutdown keeps those windows small. Another: "Shutdown cancels the requests in flight." It does not: it closes the listeners, closes idle connections and waits "indefinitely for connections to return to idle"; you bound it with a context. A detail that bit this project's own test: a connection that never sent a request is treated as busy until "we haven't read the first request's header in over 5 seconds", so tests should close their idle client connections before shutting down.
Definition: config.Load(getenv) reads ECOM_* variables (ECOM_ADDR, ECOM_DATABASE_URL, ECOM_AMQP_URL, ECOM_SMTP_HOST/PORT/USER/PASSWORD, ECOM_MAIL_FROM, ECOM_WEBHOOK_SECRET, ECOM_CURRENCY, ECOM_STOCK_HOLD, ECOM_ABANDONED_AFTER, ECOM_SHUTDOWN_TIMEOUT, ECOM_RATE_RPS, ECOM_RATE_BURST), joins every error, and in ECOM_ENV=production requires the database, SMTP and webhook secret; the twelve-factor rule is "Store config in the environment". cmd/api uses signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM); app.Serve runs the http.Server (with ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout) and the jobs, and on cancel calls Shutdown with ShutdownTimeout (20 s), then cancels the jobs and waits for their current run. /healthz answers liveness, /readyz pings the database (503 when it cannot). Docker: a multi-stage build ("With multi-stage builds, you use multiple FROM statements in your Dockerfile") compiles a static binary and copies it into a distroless image. Layout, Makefile and multi-binary builds are in Project Layout, golangci-lint, Makefile & Docker; signals in OS Processes, Signals & Graceful Shutdown.
# syntax=docker/dockerfile:1
FROM golang:1.24 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/api ./cmd/api
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/api /api
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/api"] t Kubernetes / process App
1 0 s pod marked Terminating, removed from still serving in-flight requests
Service endpoints; SIGTERM sent
2 0 s NotifyContext cancels ctx; Shutdown: listener closed
3 0.4 s last checkout commits, response written
4 0.4 s jobs cancelled; relay finishes its batch, worker its mail
5 0.6 s log "stopped", exit 0 (before terminationGracePeriodSeconds 30)Real scenario: a rolling deploy during a sale; a pod evicted while sending a mail; a missing ECOM_WEBHOOK_SECRET in production caught at start instead of at the first webhook; a migration that must run once before the new version starts (a Kubernetes Job or a CI step with migrate -path pgstore/migrations -database "$ECOM_DATABASE_URL" up).
| Concern | This project | Production addition |
|---|---|---|
| Config | ECOM_* env, fail fast | secrets from a secret store, not the image |
| Migrations | embedded SQL, golang-migrate naming | separate deploy step, expand/contract |
| Shutdown | NotifyContext, Shutdown(20s), jobs drained | preStop sleep so the LB stops sending first |
| Health | /healthz, /readyz (DB ping) | readiness also checks the outbox lag |
| Image | multi-stage, distroless, non-root | SBOM, image signing |
| Replicas | APP_ROLE=api replicas take traffic; APP_ROLE=worker replicas run relay and jobs only while holding the advisory-lock lease | lease loss alert, worker replicas outside the LB pool |
Fix / how to use it: configuration, wiring and the entry point.
// Package config reads the twelve-factor environment once, at start-up, and
// fails fast with every problem listed.
package config
import (
"errors"
"fmt"
"strconv"
"time"
)
// Config is everything the process needs.
type Config struct {
Env string // "development" | "production"
Role string // APP_ROLE: "api" (HTTP only), "worker" (HTTP + relay and jobs under a lease), "all"
Addr string
DatabaseURL string // empty: in-memory store (development only)
AMQPURL string // empty: in-process bus only
SMTPHost string // empty: log mails instead of sending
SMTPPort int
SMTPUser string
SMTPPassword string
MailFrom string
WebhookSecret string
Currency string
StockHold time.Duration
AbandonedAfter time.Duration
ShutdownTimeout time.Duration
RateRPS float64
RateBurst int
}
// Load reads ECOM_* variables through getenv (os.Getenv in main, a map in tests).
func Load(getenv func(string) string) (Config, error) {
var errs []error
str := func(k, def string) string {
if v := getenv(k); v != "" {
return v
}
return def
}
dur := func(k string, def time.Duration) time.Duration {
v := getenv(k)
if v == "" {
return def
}
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
errs = append(errs, fmt.Errorf("%s: %q is not a positive duration", k, v))
}
return d
}
num := func(k string, def int) int {
v := getenv(k)
if v == "" {
return def
}
n, err := strconv.Atoi(v)
if err != nil || n <= 0 {
errs = append(errs, fmt.Errorf("%s: %q is not a positive integer", k, v))
}
return n
}
c := Config{
Env: str("ECOM_ENV", "development"),
Role: str("APP_ROLE", "all"),
Addr: str("ECOM_ADDR", ":8080"),
DatabaseURL: getenv("ECOM_DATABASE_URL"),
AMQPURL: getenv("ECOM_AMQP_URL"),
SMTPHost: getenv("ECOM_SMTP_HOST"),
SMTPPort: num("ECOM_SMTP_PORT", 587),
SMTPUser: getenv("ECOM_SMTP_USER"),
SMTPPassword: getenv("ECOM_SMTP_PASSWORD"),
MailFrom: str("ECOM_MAIL_FROM", "Shop <orders@shop.example>"),
WebhookSecret: getenv("ECOM_WEBHOOK_SECRET"),
Currency: str("ECOM_CURRENCY", "EUR"),
StockHold: dur("ECOM_STOCK_HOLD", 15*time.Minute),
AbandonedAfter: dur("ECOM_ABANDONED_AFTER", 24*time.Hour),
ShutdownTimeout: dur("ECOM_SHUTDOWN_TIMEOUT", 20*time.Second),
RateBurst: num("ECOM_RATE_BURST", 40),
}
c.RateRPS = float64(num("ECOM_RATE_RPS", 20))
if c.Role != "api" && c.Role != "worker" && c.Role != "all" {
errs = append(errs, fmt.Errorf("APP_ROLE: %q is not api, worker or all", c.Role))
}
if c.Env == "production" {
for k, v := range map[string]string{"ECOM_DATABASE_URL": c.DatabaseURL, "ECOM_SMTP_HOST": c.SMTPHost, "ECOM_WEBHOOK_SECRET": c.WebhookSecret} {
if v == "" {
errs = append(errs, fmt.Errorf("%s is required in production", k))
}
}
}
return c, errors.Join(errs...)
}// Package app wires the modular monolith: one process serving HTTP and
// running the outbox relay and the background jobs, all stopped by one
// context with a graceful shutdown.
package app
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"sync"
"time"
"academy/ecommerce-api-project/bus"
"academy/ecommerce-api-project/config"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/httpapi"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/money"
"academy/ecommerce-api-project/outbox"
"academy/ecommerce-api-project/pricing"
"academy/ecommerce-api-project/service"
"academy/ecommerce-api-project/store"
"academy/ecommerce-api-project/worker"
)
// Deps are the adapters chosen by main (PostgreSQL or memory, SMTP or log,
// RabbitMQ or nothing). Tests pass in-memory ones.
type Deps struct {
Store store.Store
Inbox store.Inbox
Sender mailer.Sender
External outbox.Publisher // optional: RabbitMQ for other services
Auth httpapi.Authenticator
Ready func() error
Lease worker.Lease // leader lease for the relay and jobs; default: in-process
Log *slog.Logger
RelayTick time.Duration // default 1s
JobTick time.Duration // default 1m
}
// App is the assembled process.
type App struct {
cfg config.Config
deps Deps
Handler http.Handler
relay *outbox.Relay
house service.Housekeeping
}
// New assembles services, the HTTP API, the bus and the relay.
func New(cfg config.Config, d Deps) *App {
sd := service.Deps{Store: d.Store, Now: time.Now, NewID: service.RandomID, Currency: money.Currency(cfg.Currency),
TaxRates: pricing.TaxRates{"standard": 2000, "reduced": 700, "zero": 0}, StockHold: cfg.StockHold,
Discounts: func(code string) (pricing.Discount, bool) {
d, ok := map[string]pricing.Discount{"WELCOME10": {Code: "WELCOME10", Kind: pricing.PercentOff, BasisPoints: 1000}}[code]
return d, ok
}}
orders := service.Orders{Deps: sd}
b := bus.New()
mail := worker.OrderMail{Inbox: d.Inbox, Sender: d.Sender, Domain: "shop.example", Log: d.Log,
Backoff: worker.Backoff{Base: 200 * time.Millisecond, Max: 5 * time.Second, Attempts: 3},
LoadOrder: func(ctx context.Context, id string) (domain.Order, error) {
return orders.Get(ctx, domain.Principal{Role: domain.RoleAdmin}, id) // system principal
}}
b.Subscribe(domain.EvOrderPlaced, "order-confirmation-mail", mail.Handle)
var pub outbox.Publisher = b
if d.External != nil {
pub = outbox.Fanout{b, d.External}
}
api := &httpapi.API{Catalog: service.Catalog{Deps: sd}, Carts: service.Carts{Deps: sd},
Checkout: service.Checkout{Deps: sd}, Orders: orders, Auth: d.Auth, Ready: d.Ready, Log: d.Log,
Limiter: httpapi.NewIPLimiter(cfg.RateRPS, cfg.RateBurst), WebhookSecret: []byte(cfg.WebhookSecret)}
return &App{cfg: cfg, deps: d, Handler: api.Handler(),
relay: &outbox.Relay{Store: d.Store, Pub: pub, Now: time.Now, Batch: 100},
house: service.Housekeeping{Deps: sd, AbandonedAfter: cfg.AbandonedAfter}}
}
// Serve runs until ctx is cancelled (SIGINT/SIGTERM in main). Every role
// serves HTTP (API traffic, or only /healthz and /readyz on workers). Only
// APP_ROLE=worker or all starts the relay and the jobs, and only while this
// replica holds the lease, so many replicas still mean one relay. On cancel:
// 1. stops accepting connections and waits for in-flight requests
// (http.Server.Shutdown, bounded by ShutdownTimeout),
// 2. stops the relay and the jobs and waits for their current run.
func (a *App) Serve(ctx context.Context, ln net.Listener) error {
srv := &http.Server{Handler: a.Handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second,
BaseContext: func(net.Listener) context.Context { return context.WithoutCancel(ctx) }}
bg, stopBG := context.WithCancel(context.WithoutCancel(ctx))
var wg sync.WaitGroup
if a.cfg.Role != "api" {
lease := a.deps.Lease
if lease == nil {
lease = worker.NewMemLease()
}
wg.Add(1)
go func() {
defer wg.Done()
worker.RunWithLease(bg, lease, 5*time.Second, a.deps.Log,
worker.Job{Name: "outbox-relay", Every: or(a.deps.RelayTick, time.Second), Run: a.relay.RunOnce},
worker.Job{Name: "release-expired-orders", Every: or(a.deps.JobTick, time.Minute), Run: a.house.ReleaseExpired},
worker.Job{Name: "abandoned-cart-reminders", Every: or(a.deps.JobTick, time.Minute), Run: a.house.RemindAbandoned})
}()
}
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
var err error
select {
case err = <-errc: // listener failed
case <-ctx.Done():
sctx, cancel := context.WithTimeout(context.Background(), a.cfg.ShutdownTimeout)
err = srv.Shutdown(sctx)
cancel()
}
stopBG()
wg.Wait()
if errors.Is(err, http.ErrServerClosed) {
err = nil
}
return err
}
func or(d, def time.Duration) time.Duration {
if d > 0 {
return d
}
return def
}// Command api runs the shop: HTTP API, outbox relay and background jobs in
// one process. Adapters are chosen from the environment: PostgreSQL or
// memory, SMTP or log, RabbitMQ or in-process only.
package main
import (
"context"
"fmt"
"io"
"log/slog"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"academy/ecommerce-api-project/app"
"academy/ecommerce-api-project/config"
"academy/ecommerce-api-project/domain"
"academy/ecommerce-api-project/httpapi"
"academy/ecommerce-api-project/mailer"
"academy/ecommerce-api-project/memstore"
"academy/ecommerce-api-project/pgstore"
"academy/ecommerce-api-project/rabbit"
)
func main() {
if err := run(context.Background(), os.Getenv, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context, getenv func(string) string, stdout io.Writer) error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
cfg, err := config.Load(getenv)
if err != nil {
return err
}
log := slog.New(slog.NewJSONHandler(stdout, nil))
// Swap in the JWT or session authenticator of the authentication chapter.
// Development gets two fixed tokens so the API can be tried with curl.
auth := httpapi.StaticTokens{}
if cfg.Env == "development" {
auth["dev-admin"] = domain.Principal{UserID: 1, Email: "admin@shop.example", Role: domain.RoleAdmin}
auth["dev-alice"] = domain.Principal{UserID: 7, Email: "alice@example.com", Role: domain.RoleCustomer}
}
d := app.Deps{Log: log, Auth: auth}
if cfg.DatabaseURL != "" {
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil {
return err
}
defer pool.Close()
d.Store, d.Inbox = pgstore.New(pool), pgstore.Inbox{DB: pool}
d.Lease = pgstore.Lease{Pool: pool, Key: 7_340_001} // one relay per database, across replicas
d.Ready = func() error {
c, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
return pool.Ping(c)
}
} else {
log.Warn("ECOM_DATABASE_URL not set: in-memory store, data is lost on exit")
d.Store, d.Inbox = memstore.New(), memstore.NewInbox()
}
if cfg.SMTPHost != "" {
s, err := mailer.NewSMTP(mailer.SMTPConfig{Host: cfg.SMTPHost, Port: cfg.SMTPPort,
Username: cfg.SMTPUser, Password: cfg.SMTPPassword, From: cfg.MailFrom})
if err != nil {
return err
}
d.Sender = s
} else {
d.Sender = mailer.LogSender{Log: log}
}
if cfg.AMQPURL != "" {
p, err := rabbit.New(cfg.AMQPURL, "shop.events") // redials by itself after a broker restart
if err != nil {
return err
}
defer p.Close()
d.External = p
}
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return err
}
log.Info("listening", "addr", ln.Addr().String())
err = app.New(cfg, d).Serve(ctx, ln)
log.Info("stopped", "err", err)
return err
}Mechanics
The request pipeline, in order Important
app.Handler is chain(mux, requestID, logRequests, recoverer, securityHeaders, rateLimit, authenticate), outermost first, so every response, including 429 and a recovered panic, carries a request id, a log line and the security headers.
| Order | Step | Can answer | Notes |
|---|---|---|---|
| 1 | requestID | client id kept if ≤ 64 chars | |
| 2 | logRequests | wraps the writer to capture the status | |
| 3 | recoverer | 500 | re-panics http.ErrAbortHandler |
| 4 | securityHeaders | set before the handler writes | |
| 5 | rateLimit | 429 | per IP token bucket |
| 6 | authenticate | puts Principal in the context, never rejects | |
| 7 | ServeMux | 404, 405 | Go 1.22 patterns |
| 8 | customer / admin | 401, 403 | per route |
| 9 | handler: decode, MaxBytesReader | 400, 422 | DisallowUnknownFields |
| 10 | service: validate, authorize object, InTx | 404, 409, 412, 422 | typed errors |
| 11 | fail | problem+json | one mapping table |
Error codes and texts you will see Must-know
| Source | Code / text | Meaning here |
|---|---|---|
| PostgreSQL | 40001 could not serialize access due to concurrent update | REPEATABLE READ/SERIALIZABLE conflict, InTx re-runs |
| PostgreSQL | 40P01 deadlock_detected | lock order violated somewhere, re-run |
| PostgreSQL | 23505 unique_violation | duplicate order id, payment, event, or idempotency race |
| PostgreSQL | 23514 check_violation inventory_no_oversell | a write tried reserved > on_hand |
| PostgreSQL | 55P03 lock_not_available | waited longer than lock_timeout |
| pgx | pgx.ErrNoRows | mapped to domain.ErrNotFound |
| go-mail | *mail.SendError, ErrorCode() | 4xx and 0 (network) retry, 5xx permanent |
| amqp091-go | DeferredConfirmation.WaitContext → false | broker nack, relay retries |
| net/http | http: request body too large | MaxBytesReader hit, 422 body |
| Go | context canceled | client went away during InTx |
Exact responses (real run) Important
From a run of the lab order request with curl -si, against go run ./cmd/api with the memory store (Date, ids and times vary per run):
$ curl -si -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" -H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{"discount_code":"WELCOME10"}'
HTTP/1.1 201 Created
Cache-Control: no-store
Content-Security-Policy: frame-ancestors 'none'
Content-Type: application/json
Location: /v1/orders/ord_1c3600516daf2ad2f578716a9aac72cf
Referrer-Policy: no-referrer
Strict-Transport-Security: max-age=63072000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Request-Id: ae25dc86f3914501
{"id":"ord_1c3600516daf2ad2f578716a9aac72cf","status":"created","items":[{"product_id":1,"sku":"GOBOOK","name":"The Go book","qty":2,"unit_price":{"amount":3999,"currency":"EUR"},"line_total":{"amount":7702,"currency":"EUR"}}],"subtotal":{"amount":7998,"currency":"EUR"},"discount":{"amount":800,"currency":"EUR"},"tax":{"amount":504,"currency":"EUR"},"total":{"amount":7702,"currency":"EUR"},"payment_status":"requires_payment_method","pay_before":"2026-11-29T01:17:18.119928+03:30","created_at":"2026-11-29T01:02:18.119928+03:30"}Knobs Good to know
| Knob | Default | Where | Effect |
|---|---|---|---|
ECOM_STOCK_HOLD | 15m | Deps.StockHold | how long an unpaid order keeps stock |
ECOM_ABANDONED_AFTER | 24h | Housekeeping | idle time before a reminder |
MaxAttempts | 3 | pgstore.Store | re-runs on 40001/40P01/23505 |
LockTimeout | 5s | pgstore.Store | lock_timeout per transaction, then 55P03 → 409 |
FullText | false | pgstore.Store | tsvector instead of ILIKE |
| relay tick / batch | 1 s / 100 | app | event latency vs load |
| mail backoff | 200 ms base, 5 s cap, 3 attempts | app | per delivery, then the relay backs off |
| relay backoff | 2^n s, cap 10 min | outbox.Relay | per failed event |
ECOM_RATE_RPS / ECOM_RATE_BURST | 20 / 40 | IPLimiter | 429 threshold |
ECOM_SHUTDOWN_TIMEOUT | 20s | http.Server.Shutdown | keep below the orchestrator's grace period |
APP_ROLE | all | config, app.Serve | api: HTTP only; worker: HTTP plus relay and jobs while holding the lease |
MaxQtyPerLine | 10 | domain | per-line cap, also a DB CHECK |
The SQL that the stock and listing code run, for reading in psql:
-- Reserve (pessimistic): lock the order's stock rows in id order, then add.
BEGIN;
SELECT set_config('lock_timeout', '5s', true);
SELECT product_id, on_hand - reserved FROM inventory
WHERE product_id = ANY('{3,9}'::bigint[]) ORDER BY product_id FOR UPDATE;
UPDATE inventory SET reserved = reserved + 2, updated_at = now() WHERE product_id = 3;
UPDATE inventory SET reserved = reserved + 1, updated_at = now() WHERE product_id = 9;
COMMIT;
-- Reserve (single line, atomic conditional update): 0 rows = not enough stock.
UPDATE inventory SET reserved = reserved + 2
WHERE product_id = 3 AND on_hand - reserved >= 2;
-- Optimistic edit of a product: 0 rows = someone else changed it (412).
UPDATE products SET price_minor = 4299, version = version + 1 WHERE id = 3 AND version = 4;
-- Keyset page 2, price ascending, with the index products_price (price_minor, id) WHERE active.
SELECT id, sku, name, price_minor FROM products
WHERE active AND (price_minor, id) > (1999, 42)
ORDER BY price_minor, id LIMIT 21;
-- Search: substring now, full text later.
SELECT id, name FROM products WHERE active AND (name ILIKE '%go book%' OR sku ILIKE '%go book%');
SELECT id, name, ts_rank(search, q) AS rank
FROM products, websearch_to_tsquery('simple', 'go book') AS q
WHERE active AND search @@ q ORDER BY rank DESC LIMIT 20;
-- The two background scans, each on a partial index.
SELECT id FROM orders WHERE status = 'created' AND expires_at < now() ORDER BY expires_at LIMIT 100;
SELECT count(*), min(occurred_at) FROM outbox WHERE published_at IS NULL;Solving the classic problems
| Problem | Solution | How | Advantage | Cost |
|---|---|---|---|---|
| Oversell in a flash sale | locked reservation + CHECK | FOR UPDATE in id order, all-or-nothing | correct under any concurrency | buyers of one SKU queue for ms |
| Double order on retry | Idempotency-Key in the checkout tx | scoped key, fingerprint, replay | client can retry blindly | one table, 24 h retention |
| Price tampering | server-side pricing | cart has no prices; Quote from the catalogue | nothing to tamper with | none |
| Lost confirmation mail | outbox + worker | event in the tx, at-least-once relay, inbox | survives crashes | eventual (seconds) |
| Duplicate mail | inbox + deterministic ids | Has/Mark per consumer | effect once | one table |
| Stock held by unpaid orders | stock release timeout | expires_at, job with version check | stock returns | a job to run |
| Payment after the timeout | refund_pending | state machine has no cancelled → paid | no resurrected order | a refund flow |
| Reading another customer's order | per-object check | CanSee, 404 | BOLA closed | discipline in every use case |
| Admin edits overwrite each other | optimistic lock | If-Match + version | no locks held | 412, reload |
| Page drift in the catalogue | keyset pagination | (sort, id) cursor | stable, fast | no "jump to page 57" |
| Spec drift | spec test | routes vs openapi.json | docs stay true | one test |
| Deadlock between checkouts | lock ordering + retry | SortReservations, 40P01 re-run | rare and self-healing | none |
Oversell
Use the locked reservation for multi-line carts and the conditional UPDATE for single-line hot paths; keep CHECK (reserved <= on_hand) as the net that turns a bug into an error. If one SKU is so hot that even millisecond locks queue (a ticket drop), move the counter to Redis (DECRBY with a Lua check) or pre-split stock into buckets, and reconcile into PostgreSQL.
Double order and the unknown outcome
The client creates one key per checkout attempt (a UUIDv4 or ULID) and keeps it until it gets a definitive answer. The server stores the record in the checkout transaction. Towards the PSP, a different, derived key (ord_x:attempt:1) protects the charge; see API Idempotency.
Late webhook after the stock release
Do not reopen the order: the stock may already be sold to someone else. Record refund_pending and emit payment.refund_requested; the payments system refunds with its own derived key. For slow payment methods (bank debits "can take up to a few days to process"), set a longer hold or reserve only after processing.
Mail that never arrives
Look at outbox_unpublished first (relay or broker down), then the worker's mail send errors (SMTP), then the provider's bounce webhooks. A permanent 5xx is marked done and alerted; it must not block the queue behind it.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| A few hundred orders a day | this monolith, one PostgreSQL | in-process bus, SMTP via a provider | simplest correct design |
| Flash sales on few SKUs | locked reservation + short transactions | lock_timeout, queue in front of checkout | contention is on one row |
| Mostly single-item orders | conditional UPDATE ... WHERE on_hand - reserved >= n | RowsAffected check | one statement, no explicit lock |
| Long-running admin edits | optimistic version + If-Match | 412 and reload | no lock held for minutes |
| Several services consume orders | outbox → RabbitMQ topic exchange | confirms, inbox per consumer | at-least-once across processes |
| Replay and high volume | outbox → Kafka keyed by order id | CDC instead of polling | per-order ordering, retention |
| Search is a product feature | tsvector then a search engine | outbox feeds the index | ranking, typos, facets |
| Web storefront login | cookie sessions | CSRF protection | revocable, simple |
| Mobile app | short JWT + refresh | rotation, revocation list | no cookies |
| Spec consumed by other teams | spec-first (oapi-codegen) | generated client | contract before code |
| Small team, Go-first | code-first (swag) or hand spec + drift test | publish Swagger UI | fastest to start |
In architecture: from a single process to a distributed system
Monolith: one process, one database
This project as it is: one binary serving HTTP, running the relay and the jobs, one PostgreSQL. Every guarantee above comes from one database transaction: stock, order, payment intent and event are consistent by construction. The in-process bus is enough for the mail worker. The simplest correct deployment is two APP_ROLE=api replicas behind a load balancer (HTTP only, no relay, no jobs) plus two APP_ROLE=worker replicas that contend for a leader lease (pg_try_advisory_lock on a held connection, pgstore.Lease): only the holder runs the relay and the jobs, the other is a hot standby that takes over when the holder's session ends, all on the same database. TestAPIRoleRunsNoBackgroundJobs and TestOnlyOneWorkerHoldsTheLease prove both halves.
Modular monolith and multiple databases
Split by module without the network: catalog, cart, ordering, inventory, payments, notifications, each owning its tables (a schema per module) and talking through Go interfaces and events on the in-process bus. The rule that keeps the transaction: checkout may write inventory, orders, payments and outbox in one transaction only while they share a database; the moment inventory gets its own database, the reservation becomes a step of a saga. Keep cross-module reads through the owning module's API (no joins across schemas), so the later split is mechanical.
Microservices
Catalogue, Cart, Order, Inventory, Payment and Notification services. The checkout becomes an orchestrated saga: Order creates PENDING and emits OrderPlaced through its outbox; Inventory reserves and emits StockReserved (or StockRejected); Payment authorises with the derived key and emits PaymentCaptured (or PaymentFailed); Order moves to paid or compensates (ReleaseStock, VoidPayment). Every step is idempotent by event id, every service has an outbox and an inbox, and the stock release timeout becomes the saga's timeout. What does not survive: the single transaction, read-your-writes across services (the order page may show pending for a second), and simple joins (the order service keeps a copy of names and prices, which it already does as order items). The saga shapes are in Payment Processing Architecture and the consumers in Event-Driven Go.
Order svc Inventory svc Payment svc Notification svc
1 tx: order PENDING + outbox
2 -> OrderPlaced
3 tx: reserve + outbox
4 -> StockReserved
5 PSP call, key ord_1:attempt:1
6 -> PaymentCaptured
7 tx: order paid + outbox <-
8 -> OrderPaid mail (inbox dedupe)
failure at 5: PaymentFailed -> Order emits ReleaseStock -> Inventory releases (compensation)Distributed data: replicas, caches, sharded databases, multi-region
Read replicas serve the catalogue (lag of a second is fine) but never the checkout or "my orders right after I paid" (read your writes from the primary, or by a version token). A CDN or Redis cache in front of GET /v1/products needs invalidation from product.updated events, not a TTL guess, when prices change. Stock is the hard part of sharding: shard orders by customer, but a hot SKU's stock is one row; split it into buckets or keep inventory unsharded. Multi-region shops usually keep one write region for inventory and payments and replicate the catalogue; active-active stock needs per-region allocations with reconciliation.
Scaling path: 1×, 10×, 100×
At 1× this monolith on one PostgreSQL with a pool of 20 connections is plenty. At 10×: more API replicas, pgxpool sized per replica so the total stays under max_connections (or PgBouncer in transaction mode, where pgx's statement cache must match the pooler's prepared-statement support; database/sql & pgx has the settings), catalogue on replicas and a cache, the relay batch larger, RabbitMQ for the consumers. At 100×: split checkout from catalogue, move search to a search engine fed by the outbox, put hot-SKU stock in Redis with periodic reconciliation, partition orders and outbox by time, and move to the saga design above where teams need to deploy independently.
Lab
All commands run from docs/snippets/go/ecommerce-api-project/go with Go 1.24 or later. Labs 1–4 were run for this chapter (Go 1.27.4, macOS, Apple M4 Pro) and the output is pasted; labs 5–7 need PostgreSQL, RabbitMQ, an SMTP catcher or code generators and are "expected, not run".
1. Run every test (real)
gofmt -l . && go vet ./... && go vet -tags integration ./... && go test -race -count=1 ./...
# ok academy/ecommerce-api-project/app 1.729s
# ok academy/ecommerce-api-project/before 1.465s
# ok academy/ecommerce-api-project/bus 1.440s
# ok academy/ecommerce-api-project/cmd/api 1.722s
# ok academy/ecommerce-api-project/config 1.432s
# ok academy/ecommerce-api-project/domain 1.445s
# ok academy/ecommerce-api-project/httpapi 1.532s
# ok academy/ecommerce-api-project/mailer 1.485s
# ok academy/ecommerce-api-project/memstore 1.472s
# ok academy/ecommerce-api-project/money 1.449s
# ok academy/ecommerce-api-project/outbox 1.485s
# ok academy/ecommerce-api-project/pgstore 1.551s
# ok academy/ecommerce-api-project/pricing 1.631s
# ok academy/ecommerce-api-project/rabbit 1.614s
# ok academy/ecommerce-api-project/service 1.548s
# ? academy/ecommerce-api-project/store [no test files]
# ok academy/ecommerce-api-project/worker 1.572s2. The concurrency and timing proofs (real)
go test -race -count=1 -v -run 'TestNoOversellUnderConcurrency|TestStockReleaseTimeout|TestPlaceOrderIsIdempotent' ./service
# --- PASS: TestPlaceOrderIsIdempotent (0.00s)
# --- PASS: TestNoOversellUnderConcurrency (0.00s) 50 buyers, 10 units: 10 orders, 40 x out of stock
# --- PASS: TestStockReleaseTimeout (0.00s)
# --- PASS: TestStockReleaseTimeout/expiry_first,_late_capture_asks_for_a_refund (0.00s)
# --- PASS: TestStockReleaseTimeout/capture_first,_expiry_leaves_the_order_alone (0.00s)
# --- PASS: TestStockReleaseTimeout/concurrent:_exactly_one_outcome (0.00s)
go test -count=1 -v -run 'TestRedelivered|TestRelayStops' ./worker ./outbox
# --- PASS: TestRedeliveredOrderPlacedSendsOneMail (0.00s) two 421s, three deliveries, one mail
# --- PASS: TestRelayStopsAtFirstFailureThenResumesInOrder (0.00s)
go test -count=1 -v -run TestWhatGoesWrong ./before
# --- PASS: TestWhatGoesWrong (0.00s) the fat handler: 500 with an order saved, double order, 0.1+0.2, client price3. Drive the API with curl (real)
ECOM_ADDR=127.0.0.1:18080 ECOM_WEBHOOK_SECRET=whsec_dev go run ./cmd/api &
B=http://127.0.0.1:18080
curl -s -X POST $B/v1/admin/products -H "Authorization: Bearer dev-admin" \
-d '{"sku":"GOBOOK","name":"The Go book","price":3999,"tax_class":"reduced","stock":2}'
# {"id":1,"sku":"GOBOOK","name":"The Go book","price":{"amount":3999,"currency":"EUR"},"version":1}
curl -s -X PUT $B/v1/cart/items/1 -H "Authorization: Bearer dev-alice" -d '{"qty":2}'
# {"id":"cart_b896c47aeb1dca45a0920a886b802442","items":[{"product_id":1,"qty":2}]}
ORDER=$(curl -s -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" \
-H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{"discount_code":"WELCOME10"}')
OID=$(printf '%s' "$ORDER" | grep -o '"id":"ord_[0-9a-f]*"' | cut -d'"' -f4)
echo "$OID"; printf '%s\n' "$ORDER" | grep -o '"total":{[^}]*}'
# ord_f0f14e5515640ec2fbd34d77c4c8bec2
# "total":{"amount":7702,"currency":"EUR"}
# 7702 = (7998 - 800 WELCOME10) + 504 tax at 7 % (full response in Mechanics)
curl -si -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" \
-H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{"discount_code":"WELCOME10"}' | grep -E 'HTTP/|Idempotent|Location'
# HTTP/1.1 201 Created
# Idempotent-Replayed: true
# Location: /v1/orders/ord_f0f14e5515640ec2fbd34d77c4c8bec2
curl -s -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" -H "Idempotency-Key: 6f9c1e0a-lab-0001" -d '{}'
# {"type":"https://shop.example/problems/idempotency-key-reused","title":"Idempotency-Key reused with another body","status":422,"instance":"/v1/orders","request_id":"ac2b5a08aefb5207"}
curl -s -X PUT $B/v1/cart/items/1 -H "Authorization: Bearer dev-alice" -d '{"qty":1}' >/dev/null
curl -s -X POST $B/v1/orders -H "Authorization: Bearer dev-alice" -H "Idempotency-Key: 6f9c1e0a-lab-0002"
# {"type":"https://shop.example/problems/out-of-stock","title":"Not enough stock","status":409,"detail":"product 1: wanted 1, available 0","instance":"/v1/orders","request_id":"8dcc1e4f2cf2deb1","product_id":1,"available":0}
BODY='{"id":"evt_lab_1","type":"payment_intent.succeeded","data":{"order_id":"'"$OID"'","provider_ref":"pi_lab","amount":7702,"currency":"eur"}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac whsec_dev -hex | sed 's/.*= //')
curl -s -o /dev/null -w "%{http_code}\n" -X POST $B/v1/webhooks/psp -H "X-Signature: sha256=$SIG" -d "$BODY"
curl -s -o /dev/null -w "%{http_code}\n" -X POST $B/v1/webhooks/psp -H "X-Signature: sha256=00" -d "$BODY"
# 204
# 400
curl -s "$B/v1/orders/$OID" -H "Authorization: Bearer dev-alice" | grep -o '"status":"[a-z]*"'
# "status":"paid"
curl -s "$B/v1/products?sort=hack&limit=1000"
# {"type":"https://shop.example/problems/validation","title":"Invalid input","status":422,"instance":"/v1/products","request_id":"f157852a49005f21","errors":[{"field":"sort","message":"one of newest, price, -price, name"},{"field":"limit","message":"integer between 1 and 100"}]}
curl -s -o /dev/null -w "%{http_code}\n" -X POST $B/v1/admin/products -H "Authorization: Bearer dev-alice" -d "{}"
# 4034. Watch the worker and the graceful shutdown (real)
# server log of lab 3 (JSON, abridged), then kill -TERM <pid>
# {"level":"WARN","msg":"ECOM_DATABASE_URL not set: in-memory store, data is lost on exit"}
# {"level":"INFO","msg":"listening","addr":"127.0.0.1:18080"}
# {"level":"INFO","msg":"lease acquired: running background jobs"} (APP_ROLE defaults to all)
# {"level":"INFO","msg":"http","method":"POST","path":"/v1/orders","status":201,"took":127625,"request_id":"f2dca24d56ff5690"}
# {"level":"INFO","msg":"mail (not sent)","to":"alice@example.com","subject":"Your order ord_f0f14e5515640ec2fbd34d77c4c8bec2","message_id":"order.placed:ord_f0f14e5515640ec2fbd34d77c4c8bec2:v1@shop.example"}
# {"level":"INFO","msg":"job done","job":"outbox-relay","items":2}
# {"level":"INFO","msg":"stopped","err":null}The mail line appears about half a second after the 201: the relay tick, not the request, sent it. The relay published two events in that batch, order.placed and the payment.captured written by the webhook.
5. The real-PostgreSQL tests (expected, not run)
# any PostgreSQL 14+; the test creates and drops its own schema
export ECOM_TEST_DATABASE_URL='postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable'
go test -tags integration -race -count=1 -v ./pgstore/
# --- PASS: TestConcurrentCheckoutsNeverOversell 20 checkouts, 5 units: ok 5, oos 15, reserved 5
# --- PASS: TestSameIdempotencyKeyConcurrentlyCreatesOneOrder 1 row in orders
# Then try it by hand in two psql sessions:
# A: BEGIN; SELECT * FROM inventory WHERE product_id = 1 FOR UPDATE;
# B: BEGIN; SELECT * FROM inventory WHERE product_id = 1 FOR UPDATE; -- waits
# A: UPDATE inventory SET reserved = reserved + 1 WHERE product_id = 1; COMMIT;
# B: (returns the committed row) ... SET lock_timeout = '1s' makes B fail with 55P03 instead6. RabbitMQ and a real SMTP catcher (expected, not run)
# Memory store (no ECOM_DATABASE_URL): with PostgreSQL you would first run the migration
# and insert users 1 and 7, because the dev tokens' user ids are foreign keys there.
# Mailpit listens for SMTP on 1025 and shows mails on http://localhost:8025; it offers
# neither STARTTLS nor AUTH by default, so for this local test change mailer.NewSMTP to
# mail.TLSOpportunistic and mail.WithSMTPAuth(mail.SMTPAuthNoAuth) (or start Mailpit with TLS and auth).
ECOM_AMQP_URL=amqp://guest:guest@localhost:5672/ \
ECOM_SMTP_HOST=localhost ECOM_SMTP_PORT=1025 ECOM_WEBHOOK_SECRET=whsec_dev go run ./cmd/api
# rabbitmqadmin list exchanges -> shop.events topic durable
# bind a queue to "order.*" and place an order:
# message: routing_key=order.placed, message_id=order.placed:ord_...:v1, delivery_mode=2
# Mailpit shows "Your order ord_..." with a text and an HTML part7. Generate docs or code from the contract (expected, not run)
go install github.com/swaggo/swag/cmd/swag@latest
swag init -g cmd/api/main.go -d .,./httpapi -o ./docs # Swagger 2.0 from the annotations
# docs/swagger.json lists /v1/orders post with the Idempotency-Key header parameter
go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest \
-generate types,std-http-server -package api httpapi/openapi.json > /tmp/api.gen.go
# ServerInterface with one method per operation; needs a Go version newer than this module's (see above)For PHP/Laravel developers
The Laravel e-commerce equivalent uses framework features for almost every block of this chapter; the concepts are the same, the defaults differ.
| Concern | This Go project | Laravel 13 |
|---|---|---|
| Models and relations | domain structs, repositories | Eloquent models, hasMany, belongsTo, belongsToMany |
| Stock lock | SELECT ... FOR UPDATE in pgstore | Product::whereKey($id)->lockForUpdate()->first() inside DB::transaction |
| Deadlock retry | InTx on 40001/40P01 | DB::transaction(fn, attempts: 5) (retries "when a deadlock occurs") |
| Money | money.Money int64 | integer columns, brick/money; Cashier stores Stripe amounts as integers |
| Payments | payment intent + webhook | Laravel Cashier ("an expressive, fluent interface to Stripe's subscription billing services") |
| Events after commit | outbox in the transaction | dispatch(...)->afterCommit() or after_commit on the queue connection |
| Confirmation mail | go-mail + worker | Mailable implements ShouldQueue |
| Retries | worker.Retry, relay backoff | $tries, backoff(), failed jobs table |
| Search | ILIKE / tsvector | Laravel Scout (database engine: "MySQL / PostgreSQL full-text indexes and LIKE clauses") |
| Validation | ValidationError, 422 problem | Form Requests, 422 JSON |
| Auth | Principal, customer/admin guards | Sanctum tokens or sessions, Gates and Policies (Gate::authorize('view', $order)) |
| Scheduler | RunJobs tickers | Schedule::job(...)->everyMinute() |
<?php
namespace App\Actions;
use App\Mail\OrderConfirmation;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
final class PlaceOrder
{
// Migration: idempotency_keys has a primary key (user_id, key), like the Go schema.
public function __invoke(Cart $cart, string $idempotencyKey, string $fingerprint): Order
{
return DB::transaction(function () use ($cart, $idempotencyKey, $fingerprint) {
// 1. Claim the key FIRST, before any other work. On PostgreSQL insertOrIgnore is
// INSERT ... ON CONFLICT DO NOTHING: a concurrent duplicate waits here on the
// primary key until the first request commits (or rolls back).
$orderId = (string) Str::ulid();
DB::table('idempotency_keys')->insertOrIgnore([
'user_id' => $cart->user_id, 'key' => $idempotencyKey,
'fingerprint' => $fingerprint, 'order_id' => $orderId, 'created_at' => now(),
]);
$claim = DB::table('idempotency_keys')
->where('user_id', $cart->user_id)->where('key', $idempotencyKey)->first();
if ($claim->order_id !== $orderId) { // someone else holds the key: replay
abort_if($claim->fingerprint !== $fingerprint, 422, 'Idempotency-Key reused with another body');
return Order::findOrFail($claim->order_id);
}
// 2. Lock stock rows in id order, then reserve, all or nothing.
$items = $cart->items()->orderBy('product_id')->get();
$products = Product::whereIn('id', $items->pluck('product_id'))
->orderBy('id')->lockForUpdate()->get()->keyBy('id'); // SELECT ... FOR UPDATE
$order = Order::create([
'id' => $orderId, 'user_id' => $cart->user_id, 'status' => 'created',
'expires_at' => now()->addMinutes(15),
]);
$total = 0;
foreach ($items as $item) {
$product = $products[$item->product_id];
// Throwing rolls everything back, the key claim included.
abort_if($product->stock_on_hand - $product->stock_reserved < $item->qty, 409, 'out of stock');
$product->increment('stock_reserved', $item->qty);
$order->items()->create([
'product_id' => $product->id, 'qty' => $item->qty,
'unit_minor' => $product->price_minor, 'name' => $product->name,
]);
$total += $product->price_minor * $item->qty;
}
$order->update(['total_minor' => $total]);
$cart->delete();
Mail::to($cart->user)->queue((new OrderConfirmation($order))->afterCommit());
return $order;
}, attempts: 3);
}
}The key is claimed first for the same reason as in the Go code: if it were checked at the top and inserted at the end (or stored on the order), two concurrent requests with one key would both see "no order", the second would wait on the stock lock and then either create a second order or, with a unique index, fail instead of replaying. insertOrIgnore ("will ignore errors while inserting records into the database") plus reading the row back tells the two cases apart without relying on its return value; abort_if "throws an HTTP exception if a given boolean expression evaluates to true".
The comparison in one paragraph: Laravel gives you lockForUpdate, deadlock retries, after-commit dispatch, queued mail and Scout out of the box, so a correct shop is less code; Go makes every one of those an explicit line you can read and test. Two traps carry over unchanged. afterCommit() waits for the commit but is not part of it: a crash after commit and before the job is pushed to Redis loses the mail, which is why high-value events still use an outbox table in Laravel too. And Cashier's convenience methods hide the PSP idempotency key; Payment Processing Architecture shows how to pass one explicitly.
Common misconceptions
| Belief | Reality |
|---|---|
| "A transaction stops overselling." | Only with a row lock, a conditional update, a version check or SERIALIZABLE + retry; READ COMMITTED alone lets two checkouts read the same stock. |
| "The cart should store prices to be fast." | The cart stores products and quantities; prices are read at checkout, inside the transaction. |
| "A unique constraint makes POST idempotent." | It makes the retry an error; idempotency returns the first result and refuses a reused key with another body (422). |
| "Publish the event right after commit." | A crash in between loses it; write it to the outbox in the same transaction. |
| "The outbox gives exactly-once delivery." | At-least-once delivery plus consumer dedupe (inbox, deterministic ids) gives an exactly-once effect; the window between SMTP success and Inbox.Mark can still resend, and the Message-ID set to the event id makes that resend recognisable. |
| "Charging the card inside the checkout transaction is safest." | It holds locks across a slow, non-rollbackable call with unknown outcomes; record the intent, pay outside, apply the verified event. |
| "Cancel and refund are the same transition." | Cancel is before payment (release stock); refund is after (money moved). The state machine has no paid → cancelled. |
| "A login check on the route protects the orders." | Per-object authorization is needed too; Bob must get 404 for Alice's order. |
| "The in-memory test store proves the locking." | It proves the business rules; its single mutex is stronger than PostgreSQL. The integration test proves the locks. |
| "swag produces OpenAPI 3." | swag produces Swagger 2.0; use a converter or a spec-first generator for 3.x. |
"Shutdown cancels in-flight requests." | It stops accepting and waits for them; bound it with a context shorter than the orchestrator's grace period. |
| "Retry the mail until it works." | Retry temporary failures (4xx and network errors, code 0) with capped backoff; stop on permanent (5xx) ones and alert. |
"ILIKE '%x%' uses my index." | Not a B-tree; use pg_trgm or tsvector with GIN when search matters. |
Cheat sheet
| Topic | Remember |
|---|---|
| Money | int64 minor units + ISO code; half-even; Allocate so parts sum to the whole |
| Pricing | pure function from lines, discounts, rates to totals; tax per line on net |
| Order items | snapshot SKU, name, price, discount, tax at purchase |
| Stock | on_hand, reserved; lock in product-id order; CHECK (reserved <= on_hand) |
| Checkout | one transaction: look up and claim the key first, then cart, price, reserve, order, payment intent, outbox, cart delete |
| Idempotency | key scoped per user and route, fingerprint body, claim before any work, 400 missing, 422 reuse, 409 busy after lock_timeout, 24 h |
| PSP key | derived: <order>:attempt:<n>, never a fresh UUID per call |
| State machine | created → paid → fulfilled, created → cancelled, paid/fulfilled → refunded; version per transition |
| Late capture | order stays cancelled, payment refund_pending |
| Outbox | row in the tx, one relay, stop at first failure, consumers dedupe by event id |
go-mail, STARTTLS mandatory, html/template, Message-ID = event id, retry 4xx and network failures (code 0), never 5xx | |
| Workers | re-read and re-check before acting; SKIP LOCKED for batch scans; drain on shutdown |
| Catalogue | keyset (sort, id), opaque cursor, whitelisted sort, ILIKE then tsvector |
| Auth | middleware sets Principal; route guard 401/403; object check 404 |
| Errors | RFC 9457 problem+json with request_id; one mapping function |
| Contract | OpenAPI 3.1 file + a test that every route is in it |
| Ops | env config fail-fast, /healthz /readyz, NotifyContext, multi-stage distroless image, migrations as a deploy step |
Self-check: questions & answers
- 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 cart not store prices, and where does the checkout get them? Must-know
Answer
Answer: A price in the cart is stale the moment the catalogue changes, and a price that travels through the client can be tampered with. The cart holds only product ids and quantities; PlaceOrder reads each product's current price inside the checkout transaction and computes totals with pricing.Quote, then copies the result into the order items as a snapshot. See Cart and Place order.
2 — Two customers buy the last unit at the same moment under PostgreSQL READ COMMITTED. What stops both from succeeding in this project, and what is the database's last line of defence? Must-know
Answer
Answer: Inventory().Reserve locks the stock rows with SELECT ... ORDER BY product_id FOR UPDATE; the second transaction waits on the row lock, then reads the committed row (available 0) and returns OutOfStockError (409). The net is CHECK (reserved <= on_hand), which turns any bug that would oversell into an error. Locking in product-id order prevents deadlocks between multi-item carts. See Stock.
3 — List what happens inside the checkout transaction, in order. Must-know
Answer
Answer: Look up the idempotency key (replay or 422) and, if it is new, claim it at once; read the cart and current prices; price it; reserve stock for all lines in id order; insert the order (created, version 1, expires_at) and its items; insert the payment intent with the derived PSP key; insert order.placed into the outbox; delete the cart; commit. Nothing is published and no mail is sent before the commit. See Place order.
4 — A client times out on POST /v1/orders and retries with the same Idempotency-Key while the first request is still committing. What does it get, and why not a 409? Important
Answer
Answer: The key is claimed as the first write of the checkout transaction, so the retry's INSERT into idempotency_keys waits on the primary key until the first commits; ON CONFLICT then updates nothing, the store reports ErrDuplicateKey, InTx re-runs the use case, and its lookup finds the record and replays the order with Idempotent-Replayed: true. If the key were claimed only at the end, the retry would wait on the stock row instead and could answer 409 out of stock for its own order. A 409 busy appears only if the wait exceeds lock_timeout (55P03). See Idempotency.
5 — Why is the order status not simply set from the latest webhook? Must-know
Answer
Answer: Webhooks are redelivered and arrive out of order. A state machine allows only created → paid | cancelled, paid → fulfilled | refunded, fulfilled → refunded; a duplicate or late event finds no edge and changes nothing, and each transition bumps a version that the repository checks, so two concurrent writers cannot both win. See Order state machine.
6 — The stock release timeout cancels an unpaid order, and one second later the PSP reports the payment succeeded. What does the system do? Important
Answer
Answer: It does not resurrect the order, because its stock may already be sold. ApplyPayment sees the order cancelled, sets the payment to refund_pending and writes payment.refund_requested to the outbox; the payments system refunds with its own derived key. If the capture had won the race instead, the job's re-read would see paid and skip it. See Background workers.
7 — Why write events to an outbox table instead of publishing to RabbitMQ after commit, and what does a consumer need? Must-know
Answer
Answer: A crash between commit and publish loses the event; publishing before commit announces orders that may roll back. The outbox row commits with the order, the relay publishes later and marks it, so delivery is at least once. Consumers must dedupe by the deterministic event id (an inbox such as processed_events), which turns at-least-once delivery into an exactly-once effect. See Events.
8 — How does the confirmation mail avoid being sent twice, or never? Important
Answer
Answer: It is triggered by order.placed from the outbox, so it cannot be lost by a crash in the request. The worker checks its inbox before sending and marks it after success (a crash in between resends rather than loses), retries temporary SMTP failures with capped exponential backoff and jitter, stops on permanent 5xx errors, and sets Message-ID to the event id. See SMTP mail.
9 — Bob is logged in and requests GET /v1/orders/ord_alice. Walk through the checks and the answer. Must-know
Answer
Answer: The middleware authenticates Bob and puts his Principal in the context; the customer guard passes; the service loads the order and CanSee(ownerID) fails, so it returns ErrNotFound and the API answers 404, not 403, so it does not confirm the order exists. This is the object-level check OWASP lists as API1:2023. See Authentication and authorization.
10 — Why keyset pagination for the catalogue, and what must the cursor contain? Important
Answer
Answer: OFFSET reads and discards rows and drifts when products are inserted between pages; keyset continues "after this row" using an index. The cursor carries the sort, the sort value and the id as a tie-breaker, encoded opaquely, and is refused for another sort order. See Catalogue listing.
11 — When do you choose SELECT ... FOR UPDATE and when an optimistic version column in this project? Important
Answer
Answer: Row locks for hot, short critical sections (stock during checkout), because optimistic writers would mostly lose and retry under contention. Versions for slow or rarely contended edits (an admin's price change via If-Match, order status changes by jobs and webhooks), because no lock is held while a human thinks. See Stock: locks vs versions.
12 — How are the services tested without a database, and what does that not prove? Good to know
Answer
Answer: Table-driven tests run the real services against memstore, a working fake of every repository with rollback and version checks, plus a fake clock; handlers are tested through httptest. The memory store serialises transactions with one mutex, so it proves the business rules but not PostgreSQL locking, ON CONFLICT or constraints; those are covered by the integration-tagged tests against a real database. See Testing.
13 — swag or oapi-codegen for this API, and how do you keep the contract true either way? Good to know
Answer
Answer: swag is code-first and emits Swagger 2.0 from annotations; oapi-codegen is spec-first and generates Go types and a server interface from OpenAPI 3.0/3.1 (its current runtime needs Go 1.26). Either way a test should fail on drift: here TestEveryRouteIsInTheOpenAPIDocument walks the routes table and checks each method and path exists in openapi.json. See Swagger/OpenAPI.
14 — What happens on SIGTERM, step by step? Good to know
Answer
Answer: signal.NotifyContext cancels the root context; app.Serve calls http.Server.Shutdown with ShutdownTimeout, which closes the listener, closes idle connections and waits for active requests; then it cancels the background context and waits for the relay and jobs to finish their current run, and the process logs "stopped" and exits. See Deployment.
Glossary
| Term | Meaning |
|---|---|
| Abandoned cart | A customer cart with items, idle longer than AbandonedAfter, not yet reminded |
| Aggregate | A cluster of objects changed together through one root (order + items) |
| Allocate | Splitting an amount by weights so the parts sum exactly to the whole |
| Basis point | 1/100 of a percent; 2000 bp = 20 % |
| Background worker | Code that runs outside requests: event handlers and periodic jobs |
| Catalogue | The products and categories customers browse |
| Compare-and-set (CAS) | UPDATE ... WHERE version = $n; zero rows means someone else won |
| Cursor | Opaque token holding the keyset position (sort, value, id) |
| Event id | Deterministic id <type>:<aggregate>:v<version> used for dedupe |
| Fingerprint | SHA-256 of the request body stored with an idempotency key |
| Fulfilment | Shipping a paid order; turns reserved stock into shipped stock |
| go-mail | github.com/wneessen/go-mail, an SMTP and MIME library for Go |
| Graceful shutdown | Stop accepting work, finish what is in flight, then exit |
| Idempotency-Key | HTTP header carrying a client key so retries return the first result |
| Inbox | Per-consumer record of processed event ids (processed_events) |
| In-process bus | bus.Bus: synchronous event routing inside one process |
| Inventory / stock | on_hand and reserved per product; available is the difference |
| Keyset pagination | Paging by (sort value, id) > (last seen) instead of OFFSET |
| Minor unit | The smallest unit of a currency (cent, yen, fils) |
| Optimistic locking | Detect conflicting writes with a version instead of holding a lock |
| Order item | Snapshot of a purchased product line (SKU, name, price, tax) |
| Outbox | Table of events written in the business transaction and published later |
| Payment intent | Local record of one attempt to collect an order's amount, mirroring the PSP |
| Pessimistic locking | SELECT ... FOR UPDATE: lock the row before deciding |
| Principal | The authenticated caller: user id, e-mail, role |
| Problem Details | RFC 9457 JSON error format, application/problem+json |
| PSP | Payment service provider (Stripe, Adyen) |
| Relay | The loop that reads the outbox, publishes and marks rows |
| Publisher confirms | RabbitMQ acks that tell the publisher the broker took the message |
| Reservation | Stock held for an unpaid order until payment or the stock release timeout |
| Server-side cart | Cart stored in the database, keyed by a cookie token or user id |
| Service layer | Use-case methods between handlers and repositories |
| Stock release timeout | The hold (expires_at) after which unpaid orders are cancelled |
| swag | swaggo/swag, generates Swagger 2.0 from Go comments |
| oapi-codegen | Generates Go types, servers and clients from OpenAPI 3.0/3.1 |
| Token bucket | Rate-limit algorithm: burst capacity refilled at a fixed rate |
tsvector | PostgreSQL full-text document type, indexed with GIN |
| BOLA | Broken Object Level Authorization: reading another user's object by id |
| SQLSTATE 40001 | serialization_failure: re-run the transaction |
| SQLSTATE 55P03 | lock_not_available: lock_timeout expired |
References
- PostgreSQL documentation, SELECT (locking clause, NOWAIT, SKIP LOCKED) — https://www.postgresql.org/docs/current/sql-select.html
- PostgreSQL documentation, Transaction Isolation — https://www.postgresql.org/docs/current/transaction-iso.html
- PostgreSQL documentation, Explicit Locking — https://www.postgresql.org/docs/current/explicit-locking.html
- PostgreSQL documentation, Constraints — https://www.postgresql.org/docs/current/ddl-constraints.html
- PostgreSQL documentation, Partial Indexes — https://www.postgresql.org/docs/current/indexes-partial.html
- PostgreSQL documentation, Generated Columns — https://www.postgresql.org/docs/current/ddl-generated-columns.html
- PostgreSQL documentation, Appendix A. Error Codes — https://www.postgresql.org/docs/current/errcodes-appendix.html
- PostgreSQL documentation, Text Search introduction and tables — https://www.postgresql.org/docs/current/textsearch-intro.html, https://www.postgresql.org/docs/current/textsearch-tables.html
- PostgreSQL documentation, Pattern Matching (
ILIKE) — https://www.postgresql.org/docs/current/functions-matching.html - PostgreSQL documentation, pg_trgm — https://www.postgresql.org/docs/current/pgtrgm.html
- PostgreSQL documentation, INSERT (
ON CONFLICT) — https://www.postgresql.org/docs/current/sql-insert.html - Stripe, The PaymentIntent lifecycle — https://docs.stripe.com/payments/paymentintents/lifecycle
- Stripe, Idempotent requests — https://docs.stripe.com/api/idempotent_requests
- Stripe, Webhooks — https://docs.stripe.com/webhooks
- Brandur Leach, "Designing robust and predictable APIs with idempotency", Stripe blog (2017) — https://stripe.com/blog/idempotency
- Shopify Engineering, "Building Resilient Payment Systems" (2022) — https://shopify.engineering/building-resilient-payment-systems
- IETF, The Idempotency-Key HTTP Header Field (draft) — https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header
- RFC 9457, Problem Details for HTTP APIs — https://www.rfc-editor.org/rfc/rfc9457.txt
- OpenAPI Specification 3.1.0 — https://spec.openapis.org/oas/v3.1.0.html
- swaggo/swag README — https://raw.githubusercontent.com/swaggo/swag/master/README.md
- swaggo/http-swagger README — https://raw.githubusercontent.com/swaggo/http-swagger/master/README.md
- oapi-codegen README — https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/main/README.md
- go-playground/validator README — https://raw.githubusercontent.com/go-playground/validator/master/README.md
- wneessen/go-mail README — https://raw.githubusercontent.com/wneessen/go-mail/main/README.md
- jackc/pgx README and
pgconn/errors.go— https://raw.githubusercontent.com/jackc/pgx/master/README.md, https://raw.githubusercontent.com/jackc/pgx/master/pgconn/errors.go - rabbitmq/amqp091-go README — https://raw.githubusercontent.com/rabbitmq/amqp091-go/main/README.md
- RabbitMQ, Go tutorials one and three — https://www.rabbitmq.com/tutorials/tutorial-one-go, https://www.rabbitmq.com/tutorials/tutorial-three-go
- RabbitMQ, Consumer Acknowledgements and Publisher Confirms — https://www.rabbitmq.com/docs/confirms
- golang-migrate README — https://raw.githubusercontent.com/golang-migrate/migrate/master/README.md
- pressly/goose README — https://raw.githubusercontent.com/pressly/goose/main/README.md
- Chris Richardson, Pattern: Transactional outbox — https://microservices.io/patterns/data/transactional-outbox.html
- Martin Fowler, Money — https://martinfowler.com/eaaCatalog/money.html
- Martin Fowler, Optimistic Offline Lock — https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html
- Markus Winand, "No Offset" — https://use-the-index-luke.com/no-offset
- OWASP REST Security Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
- OWASP HTTP Headers Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html
- OWASP API1:2023 Broken Object Level Authorization — https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/
- OWASP Input Validation Cheat Sheet — https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- golang.org/x/time/rate source — https://raw.githubusercontent.com/golang/time/master/rate/rate.go
- go-mail
go.modat v0.7.2 (go 1.24.0) and v0.7.3 (go 1.25.0) — https://proxy.golang.org/github.com/wneessen/go-mail/@v/v0.7.2.mod, https://proxy.golang.org/github.com/wneessen/go-mail/@v/v0.7.3.mod - go-mail v0.7.2 source (
WithTLSPortPolicy,SetMessageIDWithValue,SendError.IsTemp) — https://raw.githubusercontent.com/wneessen/go-mail/v0.7.2/client.go, https://raw.githubusercontent.com/wneessen/go-mail/v0.7.2/msg.go, https://raw.githubusercontent.com/wneessen/go-mail/v0.7.2/senderror.go - pgx
go.modat v5.8.0 (go 1.24.0) and v5.9.0 (go 1.25.0), and CHANGELOG (5.12.0 security fixes) — https://raw.githubusercontent.com/jackc/pgx/v5.8.0/go.mod, https://raw.githubusercontent.com/jackc/pgx/v5.9.0/go.mod, https://raw.githubusercontent.com/jackc/pgx/master/CHANGELOG.md - amqp091-go v1.17.0 source (
PublishWithDeferredConfirmWithContext,DeferredConfirmation.WaitContext,Connection.NotifyClose) — https://raw.githubusercontent.com/rabbitmq/amqp091-go/v1.17.0/channel.go, https://raw.githubusercontent.com/rabbitmq/amqp091-go/v1.17.0/confirms.go, https://raw.githubusercontent.com/rabbitmq/amqp091-go/v1.17.0/connection.go - Martin Fowler, Patterns of Enterprise Application Architecture (book page) and Repository — https://martinfowler.com/books/eaa.html, https://martinfowler.com/eaaCatalog/repository.html
- Go source,
net/http/server.go(Shutdown) — https://go.dev/src/net/http/server.go - Go source,
net/smtp/smtp.go— https://go.dev/src/net/smtp/smtp.go - Go 1.22, 1.23, 1.24 and 1.25 release notes — https://go.dev/doc/go1.22, https://go.dev/doc/go1.23, https://go.dev/doc/go1.24, https://go.dev/doc/go1.25
- Go blog, Routing Enhancements for Go 1.22 — https://go.dev/blog/routing-enhancements
- The Twelve-Factor App, Config — https://12factor.net/config
- Docker, Multi-stage builds — https://docs.docker.com/build/building/multi-stage/
- Laravel 13: Eloquent relationships, queries, database, queues, mail, events, scheduling, authorization, validation, Sanctum, Cashier (Stripe), Scout — https://laravel.com/docs/13.x/eloquent-relationships, https://laravel.com/docs/13.x/queries, https://laravel.com/docs/13.x/database, https://laravel.com/docs/13.x/queues, https://laravel.com/docs/13.x/mail, https://laravel.com/docs/13.x/events, https://laravel.com/docs/13.x/scheduling, https://laravel.com/docs/13.x/authorization, https://laravel.com/docs/13.x/validation, https://laravel.com/docs/13.x/sanctum, https://laravel.com/docs/13.x/billing, https://laravel.com/docs/13.x/scout, https://laravel.com/docs/13.x/helpers (
abort_if), https://laravel.com/docs/13.x/strings (Str::ulid), https://laravel.com/docs/13.x/eloquent