From Copper Heat to Shipping: DDD, Hexagonal Architecture, and Atomic Transactions in Go 1.27 for a Cable Plant
A real cable manufacturing case: copper, drawing, insulation, section serialization, DDD, hexagonal architecture, Postgres, and atomicity in Go 1.27.
Table of Contents
It is 7:40 a.m. at a cable plant in Monterrey. The quality manager walks into the meeting room with a printed sheet: an automotive customer reported that a 2.5 mm² cable section has out-of-spec resistance. The cable left the plant six weeks ago. The work order is WO-2026-1842, the drum is DR-MX-2026-000123, and the customer says the problem is in section S03.
The uncomfortable question is not “what happened?” It is this: can we prove what happened, with which copper, on which machine, with which operator, with which parameters, and to which shipments it went?
In many plants, that answer lives in four different places: a shift supervisor’s spreadsheet, the MES database, a folder of CSV files, and the memory of an operator who has already retired. The goal of this post is to build the system that answers that question in seconds, not three days.
We are not building a cable CRUD. We are designing the manufacturing backend of a cable plant: domain, phases, section serialization, backward and forward traceability, DDD, hexagonal architecture, transactions, atomicity, idempotency, and real operations. All with Go 1.27, PostgreSQL, and decisions you can defend in an audit.
The business: from copper heat to cable drum
Before writing a line of Go, you need to understand the process. A cable is not “manufactured”: it is transformed. Copper enters as 8 mm rod and leaves as a cable drum with dozens or thousands of meters, with a history that should be reconstructable.
The phases, in plant language
| Phase | Input | Output | Why it matters for software |
|---|---|---|---|
| Raw material receiving | Copper rod coils of ~5 tons | Copper lot with heat number | It is the origin of all backward traceability |
| Wire drawing | 8 mm rod | Smaller-gauge wire | Geometry changes; record machine, die, emulsion, and speed |
| Annealing | Work-hardened wire | Soft wire | Temperature and time affect ductility and resistance |
| Bunching / stranding | Many fine wires | Copper conductor | Defines IEC 60228 class (1, 2, 5, or 6) and DC resistance |
| Insulation | Bare conductor | Insulated conductor (PVC, XLPE, etc.) | Wall thickness and concentricity are critical |
| Core cabling | Several insulated conductors | Cable core | Pairs or triads are born here |
| Shielding | Core | Tape or braid shielded core | Coverage, continuity, and shield resistance |
| Jacketing | Shielded core | Finished cable | Thickness, outer diameter, and marking |
| Testing | Finished cable | Pass/fail result | Resistance, continuity, insulation, high voltage |
| Packing and shipping | Approved drum | Drum with GS1 label and packing list | Closes forward traceability |
flowchart LR
A["Copper heat<br/>8 mm rod"] --> B["Wire drawing"]
B --> C["Annealing"]
C --> D["Bunching / stranding"]
D --> E["Insulation"]
E --> F["Core cabling"]
F --> G["Shielding"]
G --> H["Jacketing"]
H --> I["Electrical and dimensional tests"]
I --> J["Serialized drum"]
J --> K["Shipping"]
The key design insight is this: each phase consumes a serialized unit and produces another. If the software only stores “the order was completed,” you lose the chain. If it stores every transformation with its inputs and outputs, you can answer the customer’s question.
What “section serialization” means
The plant uses two levels of identity:
- The drum: the logistics unit that gets shipped. It has a unique serial, for example
DR-MX-2026-000123. - The section (tramo): a contiguous length interval inside the drum, for example 0 to 2,500 m, then 2,500 to 5,000 m. It is identified as
DR-MX-2026-000123-S01,-S02, etc.
Why separate them? Because a drum is not always produced in a single run. It may have:
- cuts at shift or machine changes;
- splices allowed by specification;
- lab samples per section;
- rework on a specific section;
- partial lengths shipped to different customers.
The section is the atomic unit of quality and traceability. The drum is the unit of inventory and shipping. If you mix both, you end up with a model that cannot support reality.
The standards auditors will ask about
You do not need to be certified to write the software, but the model must support what an audit will look for.
| Standard | What it governs | What it implies in code |
|---|---|---|
| IEC 60228 | Conductor classes: 1 solid, 2 stranded, 5 flexible, 6 extra-flexible; maximum DC resistance at 20 °C | ConductorClass as a value object; not a free-form string |
| IEC 60502 / IEC 60227 | Power cables and PVC-insulated cables | Product attributes: voltage, insulation, temperature |
| IPC/WHMA-A-620 | Acceptance of cable and wire harness assemblies; classes 1, 2, and 3 | If you also build harnesses, test criteria change by class |
| ISO 9001 | Quality management system | Records, audits, corrective actions |
| IATF 16949 | Automotive quality; lot or serial traceability, PPAP, APQP, SPC, FMEA, MSA | Backward and forward traceability, record retention |
| ISA-95 / IEC 62264 | Levels 0 to 4: process, sensors, control, MES, ERP | The backend lives at level 3 (MES) and talks to level 4 (ERP) |
| GS1 | GTIN (AI 01), lot (AI 10), serial (AI 21), SSCC (AI 00) | DataMatrix/GS1-128 labels and identifier validation |
| IEC 62443 | Industrial control systems cybersecurity | Segmentation, mTLS, roles, auditing |
Careful: no standard tells you how to model the domain. They tell you what evidence must exist. The job of DDD is to turn that evidence into invariants the code can enforce.
The case: reconstructing a drum’s history
Back to drum DR-MX-2026-000123. The customer reports section S03. In four hours you need to answer:
- Which copper was used? Heat, supplier, lot, receiving date.
- Which machines processed it? Drawing, annealing, bunching, insulation, jacketing.
- With which parameters? Temperature, speed, pressure, die, operator, shift.
- Which tests were performed? Resistance, insulation, continuity, high voltage, dimensional.
- Which other sections or drums share the same copper lot? To bound the recall.
- Which shipments did it reach? Customer, packing list, SSCC, date.
That is the real functional requirement. Everything else — endpoints, tables, queues — is infrastructure to answer it.
The non-functional requirements that are not in the ticket
- Atomicity: if a section is recorded, the drum cannot be updated without the section, nor the section without the event.
- Idempotency: the MES and PLC retry. A timeout does not mean the operation did not happen.
- Concurrency: two stations can scan the same drum at the same time.
- Auditability: who changed what, when, and from which device.
- Plant availability: the internal network fails; the system must fail safe, not invent data.
- Backward and forward traceability: knowing where it came from is not enough; you must know where it went.
Business boundaries: bounded contexts
The classic mistake is a giant model with Cable, Order, Lot, Test, Shipment, and User all pointing at each other. That works in a demo and breaks in the first audit.
Separate by language and responsibility:
flowchart LR
MAT["Materials<br/>heats, lots, suppliers"] --> PROD["Production<br/>work orders, drums, sections"]
PROD --> QUAL["Quality<br/>tests, holds"]
PROD --> TRACE["Traceability<br/>genealogy"]
QUAL --> TRACE
PROD --> SHIP["Shipping<br/>SSCC, packing lists"]
TRACE --> SHIP
PROD <--> INT["Integration<br/>MES, ERP, OPC UA"]
| Context | Responsibility | Question it answers |
|---|---|---|
| Materials | Receiving, lots, heats, suppliers | Where did this copper come from? |
| Production | Orders, drums, sections, operations | What was made and how? |
| Quality | Tests, holds, non-conformities | Does it conform or not? |
| Traceability | Genealogy and cross-queries | What is connected to what? |
| Shipping | Packing, SSCC, packing lists, customers | Where did it go? |
| Integration | MES, ERP, OPC UA, labels | How do we talk to the rest? |
The core domain is Production + Traceability. Materials, Quality, and Shipping are supporting domains. Integration is generic: do not over-design it.
Ubiquitous language: the plant dictionary
| Spanish | English | Definition |
|---|---|---|
| Colada | Heat | Supplier’s molten copper lot identifier |
| Alambrón | Rod | 8 mm copper that enters the plant |
| Trefilado | Wire drawing | Diameter reduction through dies |
| Recocido | Annealing | Heat treatment to restore ductility |
| Agrupado | Bunching | Joining fine wires into a conductor |
| Cableado | Stranding | Twisting conductors into a construction |
| Carrete | Drum / reel | Logistics unit of cable |
| Tramo | Section | Contiguous length interval inside the drum |
| Retención | Hold | Quality block that prevents release or shipping |
| Merma | Scrap | Non-conforming material that is discarded |
| Orden de trabajo | Work order | Authorization to make a product and quantity |
If your code says CableEntity and your plant says “drum,” you have already lost. Ubiquitous language is not decoration: it is the contract between the business and the software.
Setting up the project
Go 1.27 is the stable version at the time of writing. It brings packages we use: uuid in the standard library and improvements in encoding/json. You do not need frameworks.
mkdir cableops && cd cableops
go mod init cableops
go get github.com/jackc/pgx/v5@latest
go install github.com/pressly/goose/v3/cmd/goose@latest
go version
What each command does:
go mod init: creates the module.go get pgx/v5: installs the PostgreSQL driver and pool.go install goose: installs the migration tool.go version: confirms you are on Go 1.27 or later.
For the local lab, start PostgreSQL 17 in Docker:
docker run --name cableops-pg \
-e POSTGRES_PASSWORD=cableops \
-e POSTGRES_DB=cableops \
-p 5432:5432 \
-d postgres:17-alpine
The connection string looks like this:
export DATABASE_URL="postgres://postgres:cableops@localhost:5432/cableops?sslmode=disable"
Do not use sslmode=disable or shell credentials in production. Use a managed secret and TLS.
Tactical model: value objects that prevent expensive mistakes
Start with the small types. A string for a serial, a float64 for a length, and an int for a conductor class are time bombs.
Lengths in integer millimeters
package production
import "fmt"
// LengthMM is a length in millimeters. Never use float64 for lengths:
// 0.1 + 0.2 is not 0.3, and a drum cannot have -3 meters.
type LengthMM int64
func (l LengthMM) String() string {
return fmt.Sprintf("%d mm", int64(l))
}
func (l LengthMM) Meters() float64 {
return float64(l) / 1000
}
Why integers: floats accumulate error and cannot represent decimal fractions well. In manufacturing, length is measured in millimeters or meters with decimals; store the smallest unit and convert only at the interface. The same applies to weight (grams), money (cents), and temperature (thousandths of a degree if you need precision).
Serials with format and validation
package production
import (
"fmt"
"strings"
)
type Serial string
func NewSerial(raw string) (Serial, error) {
raw = strings.TrimSpace(raw)
if len(raw) < 8 || len(raw) > 40 {
return "", fmt.Errorf("%w: length %d", ErrInvalidSerial, len(raw))
}
for _, r := range raw {
switch {
case r >= 'A' && r <= 'Z':
case r >= '0' && r <= '9':
case r == '-':
default:
return "", fmt.Errorf("%w: character %q", ErrInvalidSerial, r)
}
}
return Serial(raw), nil
}
The drum serial follows a readable format: DR-{plant}-{year}-{sequence}. The section serial adds -S{nn}. Operators read them aloud, scanners read them from DataMatrix, and auditors search for them in a spreadsheet. If you generate a UUID as the visible serial, nobody will be able to dictate it over the phone.
Conductor class per IEC 60228
package production
import "fmt"
type ConductorClass uint8
const (
ClassSolid ConductorClass = 1
ClassStranded ConductorClass = 2
ClassFlexible ConductorClass = 5
ClassExtraFlexible ConductorClass = 6
)
func ParseConductorClass(v uint8) (ConductorClass, error) {
switch ConductorClass(v) {
case ClassSolid, ClassStranded, ClassFlexible, ClassExtraFlexible:
return ConductorClass(v), nil
default:
return 0, fmt.Errorf("%w: %d", ErrInvalidConductorClass, v)
}
}
The class is not a quality grade: it is a construction. Class 5 is not “better” than class 2; it is more flexible and has a different maximum resistance. If your model treats it as a string, someone will write “class 3” (which does not exist in IEC 60228) and nobody will notice until the audit.
The rest of the value objects
| Value object | Representation | Invariant |
|---|---|---|
Serial |
validated string | Format, length, allowed characters |
LengthMM |
int64 | ≥ 0; positive when required |
WeightG |
int64 | > 0 |
ConductorClass |
uint8 | 1, 2, 5, or 6 |
CopperGrade |
string | Cu-ETP, Cu-OF, etc. |
ProductCode |
string | Catalog, not free text |
MachineID |
string | Registered asset |
OperatorID |
string | Authorized person |
HoldReason |
string | Reason catalog, not free comment |
Value objects are not “classes with getters.” They are types that cannot exist in an invalid state. If a Serial is constructed, it is valid. If a LengthMM is negative, the compiler will not save you, but the constructor will.
The Drum aggregate: the consistency boundary
An aggregate is a transactional boundary. Everything inside is saved together or not saved. Drum is the root aggregate of Production because all critical invariants depend on it:
- Sections do not overlap.
- Sections are contiguous.
- Produced length does not exceed capacity.
- A section is not tested twice.
- A drum is not released with pending or failed sections.
- A drum is not shipped unless it is released.
package production
import (
"fmt"
"slices"
"time"
)
type Status string
const (
StatusCreated Status = "created"
StatusInProcess Status = "in_process"
StatusAwaitingTest Status = "awaiting_test"
StatusReleased Status = "released"
StatusShipped Status = "shipped"
StatusScrapped Status = "scrapped"
)
func (s Status) CanAddSection() bool {
return s == StatusCreated || s == StatusInProcess
}
type Drum struct {
serial Serial
workOrderID string
productCode string
capacityMM LengthMM
producedMM LengthMM
status Status
sections []Section
version int64
events []DomainEvent
}
Constructor and rehydration
func NewDrum(serial Serial, workOrderID, productCode string, capacityMM LengthMM) (*Drum, error) {
if workOrderID == "" {
return nil, fmt.Errorf("work order id is required")
}
if productCode == "" {
return nil, fmt.Errorf("product code is required")
}
if capacityMM <= 0 {
return nil, fmt.Errorf("%w: capacity must be positive", ErrInvalidLength)
}
d := &Drum{
serial: serial,
workOrderID: workOrderID,
productCode: productCode,
capacityMM: capacityMM,
status: StatusCreated,
}
d.record(DrumCreated{
DrumSerial: serial,
WorkOrderID: workOrderID,
ProductCode: productCode,
CapacityMM: capacityMM,
})
return d, nil
}
// RehydrateDrum is only used by the persistence adapter.
// It does not validate business rules: it rebuilds state that already existed.
func RehydrateDrum(
serial Serial,
workOrderID, productCode string,
capacityMM, producedMM LengthMM,
status Status,
sections []Section,
version int64,
) *Drum {
return &Drum{
serial: serial,
workOrderID: workOrderID,
productCode: productCode,
capacityMM: capacityMM,
producedMM: producedMM,
status: status,
sections: sections,
version: version,
}
}
Recording a section
func (d *Drum) AddSection(endMM LengthMM) (Section, error) {
if !d.status.CanAddSection() {
return Section{}, fmt.Errorf("%w: %s -> add section", ErrInvalidTransition, d.status)
}
if endMM <= d.producedMM {
return Section{}, fmt.Errorf(
"%w: end %d must be greater than produced %d",
ErrInvalidLength, endMM, d.producedMM,
)
}
if endMM > d.capacityMM {
return Section{}, fmt.Errorf(
"%w: end %d > capacity %d",
ErrCapacityExceeded, endMM, d.capacityMM,
)
}
start := d.producedMM
number := len(d.sections) + 1
d.sections = append(d.sections, Section{
number: number,
startMM: start,
endMM: endMM,
status: SectionPending,
})
d.producedMM = endMM
if d.status == StatusCreated {
d.status = StatusInProcess
}
d.record(SectionAdded{
DrumSerial: d.serial,
SectionNumber: number,
StartMM: start,
EndMM: endMM,
})
return d.sections[len(d.sections)-1], nil
}
What it does: validates the transition, computes the start from what has already been produced, creates the section, updates the total, and emits the event. Why: the caller cannot “invent” a start that does not match the previous end. Contiguity is an aggregate invariant, not a database convention.
Attaching a test
type TestOutcome struct {
TestID string // UUID from quality.tests
Status SectionStatus
MeasuredAt time.Time
}
func (d *Drum) AttachTest(sectionNumber int, outcome TestOutcome) error {
idx := slices.IndexFunc(d.sections, func(s Section) bool {
return s.number == sectionNumber
})
if idx < 0 {
return fmt.Errorf("%w: %d", ErrSectionNotFound, sectionNumber)
}
s := &d.sections[idx]
if s.status != SectionPending {
return fmt.Errorf("%w: section %d is %s", ErrSectionAlreadyTested, sectionNumber, s.status)
}
if outcome.Status != SectionPassed && outcome.Status != SectionFailed {
return fmt.Errorf("%w: invalid result %q", ErrInvalidTransition, outcome.Status)
}
s.status = outcome.Status
s.testID = outcome.TestID
d.record(TestAttached{
DrumSerial: d.serial,
SectionNumber: sectionNumber,
TestID: outcome.TestID,
Result: outcome.Status,
MeasuredAt: outcome.MeasuredAt,
})
return nil
}
Rework: this model treats a failed section as immutable evidence. If the plant allows reworking and retesting the same section, add a ReopenForRework(reason, authorizedBy) method that records the event and returns the section to pending; the attempt history lives in quality.tests. I do not include it to keep the example small, but the design supports it: the section is an entity and tests are another aggregate.
Completing production and releasing
func (d *Drum) CompleteProduction() error {
if d.status != StatusInProcess {
return fmt.Errorf("%w: %s -> complete", ErrInvalidTransition, d.status)
}
if len(d.sections) == 0 {
return ErrNoSections
}
d.status = StatusAwaitingTest
d.record(ProductionCompleted{DrumSerial: d.serial, ProducedMM: d.producedMM})
return nil
}
func (d *Drum) Release(hasOpenHold bool) error {
if d.status != StatusAwaitingTest {
return fmt.Errorf("%w: %s -> release", ErrInvalidTransition, d.status)
}
if hasOpenHold {
return ErrOpenHold
}
for _, s := range d.sections {
if s.status != SectionPassed {
return fmt.Errorf("%w: section %d is %s", ErrSectionsNotPassed, s.number, s.status)
}
}
d.status = StatusReleased
d.record(DrumReleased{DrumSerial: d.serial, ProducedMM: d.producedMM})
return nil
}
func (d *Drum) Ship(hasOpenHold bool) error {
if d.status != StatusReleased {
return fmt.Errorf("%w: %s -> ship", ErrInvalidTransition, d.status)
}
if hasOpenHold {
return ErrOpenHold
}
d.status = StatusShipped
d.record(DrumShipped{DrumSerial: d.serial})
return nil
}
func (d *Drum) Scrap(reason string) error {
if d.status == StatusShipped {
return fmt.Errorf("%w: shipped -> scrap", ErrInvalidTransition)
}
if d.status == StatusScrapped {
return nil
}
d.status = StatusScrapped
d.record(DrumScrapped{DrumSerial: d.serial, Reason: reason})
return nil
}
Errors, events, and accessors
The domain needs typed errors so the HTTP layer can choose a status code without parsing strings, and events so the application can persist them in the outbox.
// errors.go
package production
import "errors"
var (
ErrNotFound = errors.New("drum not found")
ErrInvalidSerial = errors.New("invalid drum serial")
ErrInvalidLength = errors.New("invalid length")
ErrInvalidConductorClass = errors.New("invalid conductor class")
ErrInvalidTransition = errors.New("invalid status transition")
ErrCapacityExceeded = errors.New("drum capacity exceeded")
ErrSectionNotFound = errors.New("section not found")
ErrSectionAlreadyTested = errors.New("section already tested")
ErrSectionsNotPassed = errors.New("not all sections passed")
ErrOpenHold = errors.New("drum has an open quality hold")
ErrNoSections = errors.New("drum has no sections")
ErrConcurrencyConflict = errors.New("concurrency conflict")
ErrDuplicate = errors.New("duplicate request")
ErrIdempotencyKeyReuse = errors.New("idempotency key reused with different payload")
)
// events.go
package production
import "time"
type DomainEvent interface {
EventName() string
AggregateID() string
}
type DrumCreated struct {
DrumSerial Serial
WorkOrderID string
ProductCode string
CapacityMM LengthMM
}
func (e DrumCreated) EventName() string { return "production.drum_created.v1" }
func (e DrumCreated) AggregateID() string { return string(e.DrumSerial) }
type SectionAdded struct {
DrumSerial Serial
SectionNumber int
StartMM LengthMM
EndMM LengthMM
}
func (e SectionAdded) EventName() string { return "production.section_added.v1" }
func (e SectionAdded) AggregateID() string { return string(e.DrumSerial) }
type TestAttached struct {
DrumSerial Serial
SectionNumber int
TestID string
Result SectionStatus
MeasuredAt time.Time
}
func (e TestAttached) EventName() string { return "production.test_attached.v1" }
func (e TestAttached) AggregateID() string { return string(e.DrumSerial) }
type ProductionCompleted struct {
DrumSerial Serial
ProducedMM LengthMM
}
func (e ProductionCompleted) EventName() string { return "production.completed.v1" }
func (e ProductionCompleted) AggregateID() string { return string(e.DrumSerial) }
type DrumReleased struct {
DrumSerial Serial
ProducedMM LengthMM
}
func (e DrumReleased) EventName() string { return "production.drum_released.v1" }
func (e DrumReleased) AggregateID() string { return string(e.DrumSerial) }
type DrumShipped struct {
DrumSerial Serial
}
func (e DrumShipped) EventName() string { return "production.drum_shipped.v1" }
func (e DrumShipped) AggregateID() string { return string(e.DrumSerial) }
type DrumScrapped struct {
DrumSerial Serial
Reason string
}
func (e DrumScrapped) EventName() string { return "production.drum_scrapped.v1" }
func (e DrumScrapped) AggregateID() string { return string(e.DrumSerial) }
// drum.go: accessors and persistence
func (d *Drum) Serial() Serial { return d.serial }
func (d *Drum) Status() Status { return d.status }
func (d *Drum) ProducedMM() LengthMM { return d.producedMM }
func (d *Drum) Version() int64 { return d.version }
func (d *Drum) Sections() []Section { return slices.Clone(d.sections) }
// MarkPersisted is called by the repository after the UPDATE.
// It is not business logic: it keeps version in memory for the next save.
func (d *Drum) MarkPersisted(version int64) { d.version = version }
func (d *Drum) PullEvents() []DomainEvent {
events := d.events
d.events = nil
return events
}
func (d *Drum) record(ev DomainEvent) {
d.events = append(d.events, ev)
}
Why PullEvents clears the list: the use case saves the aggregate and then sends the events to the outbox. If it does not clear them, a second Save on the same instance would reinsert the same events. It is a small detail that prevents duplicates in production.
The state machine
stateDiagram-v2
[*] --> Created
Created --> InProcess: first section
InProcess --> AwaitingTest: production complete
AwaitingTest --> Released: all sections pass + no hold
Released --> Shipped: packing list / shipment
Created --> Scrapped
InProcess --> Scrapped
AwaitingTest --> Scrapped
Released --> Scrapped
Important decision: a quality hold is not a drum state. It is a separate aggregate in the Quality context. If you make it StatusOnHold, you lose the previous state and cannot answer “was it in production or waiting for test when it was held?” The drum has a production lifecycle; the hold is an external constraint that blocks release and shipping. That separation lets Quality evolve without rewriting Production.
Section as an entity inside the aggregate
type SectionStatus string
const (
SectionPending SectionStatus = "pending"
SectionPassed SectionStatus = "passed"
SectionFailed SectionStatus = "failed"
)
type Section struct {
number int
startMM LengthMM
endMM LengthMM
status SectionStatus
testID string
}
func (s Section) Number() int { return s.number }
func (s Section) StartMM() LengthMM { return s.startMM }
func (s Section) EndMM() LengthMM { return s.endMM }
func (s Section) LengthMM() LengthMM { return s.endMM - s.startMM }
func (s Section) Status() SectionStatus { return s.status }
func (s Section) TestID() string { return s.testID }
// RehydrateSection is only used by the persistence adapter.
func RehydrateSection(
number int,
startMM, endMM LengthMM,
status SectionStatus,
testID string,
) Section {
return Section{
number: number,
startMM: startMM,
endMM: endMM,
status: status,
testID: testID,
}
}
The section has no repository of its own. It is not loaded or saved separately. It is accessed through the Drum. That avoids the classic mistake of two transactions: one for the section and one for the drum.
Ports and adapters: the domain does not know PostgreSQL exists
Hexagonal architecture is not a folder with domain, application, and infrastructure. It is a dependency direction: the domain imports nothing from outside; the application defines ports; adapters implement them.
flowchart TB
subgraph Driving["Driving adapters"]
HTTP["HTTP / REST"]
MES["MES / ERP"]
OPC["OPC UA / PLC"]
end
subgraph Core["Core"]
APP["Application<br/>use cases"]
DOM["Domain<br/>Drum, Section, Hold"]
PORTS["Ports<br/>repositories, UoW, outbox"]
end
subgraph Driven["Driven adapters"]
PG["PostgreSQL"]
BUS["Broker / Event bus"]
LABEL["Labels / printers"]
end
HTTP --> APP
MES --> APP
OPC --> APP
APP --> DOM
APP --> PORTS
PORTS -.-> PG
PORTS -.-> BUS
PORTS -.-> LABEL
Project layout
cableops/
├── cmd/
│ └── api/
│ └── main.go
├── internal/
│ ├── domain/
│ │ ├── production/
│ │ │ ├── drum.go
│ │ │ ├── section.go
│ │ │ ├── events.go
│ │ │ ├── errors.go
│ │ │ └── drum_test.go
│ │ └── quality/
│ │ └── hold.go
│ ├── app/
│ │ ├── ports.go
│ │ ├── record_section.go
│ │ ├── release_drum.go
│ │ └── record_test.go
│ ├── adapters/
│ │ ├── postgres/
│ │ │ ├── uow.go
│ │ │ ├── drum_repo.go
│ │ │ ├── outbox_repo.go
│ │ │ └── idempotency_repo.go
│ │ ├── httpapi/
│ │ │ └── server.go
│ │ └── opcua/
│ │ └── client.go
│ └── platform/
│ ├── clock.go
│ └── ids.go
├── migrations/
│ ├── 0001_schema.up.sql
│ └── 0001_schema.down.sql
├── go.mod
└── go.sum
Output ports
package app
import (
"context"
"time"
"cableops/internal/domain/production"
)
type Tx interface {
Drums() DrumRepository
Holds() HoldChecker
Outbox() OutboxRepository
Idempotency() IdempotencyRepository
}
type UnitOfWork interface {
WithinTx(ctx context.Context, fn func(context.Context, Tx) error) error
}
type DrumRepository interface {
Get(ctx context.Context, serial production.Serial) (*production.Drum, error)
GetForUpdate(ctx context.Context, serial production.Serial) (*production.Drum, error)
Save(ctx context.Context, d *production.Drum) error
}
type HoldChecker interface {
HasOpenHold(ctx context.Context, drumSerial string) (bool, error)
}
type OutboxRepository interface {
Append(ctx context.Context, events ...production.DomainEvent) error
}
type StoredResponse struct {
Code int
Body []byte
}
type IdempotencyRepository interface {
Reserve(ctx context.Context, key string, requestHash []byte) (StoredResponse, bool, error)
Store(ctx context.Context, key string, resp StoredResponse) error
}
type Clock interface {
Now() time.Time
}
Why Tx exposes repositories: the use case needs the read, the write, and the outbox insert to happen in the same transaction. If each repository opens its own connection, atomicity is lost. WithinTx takes a function and gives it a Tx bound to that transaction.
Alternative: inject a Querier through the context. It is more flexible but also more implicit. For a small team, the explicit Tx is easier to read and test.
The atomic use case: recording a section
This is the heart of the post. An endpoint receives the end of a section and must do the following in a single transaction:
- Check idempotency.
- Lock the drum.
- Validate and create the section.
- Update the drum.
- Insert the event into the outbox.
- Store the idempotent response.
package app
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"cableops/internal/domain/production"
)
type RecordSection struct {
UoW UnitOfWork
}
type RecordSectionCmd struct {
DrumSerial string
EndMM int64
IdempotencyKey string
}
type SectionDTO struct {
DrumSerial string `json:"drum_serial"`
Number int `json:"number"`
StartMM int64 `json:"start_mm"`
EndMM int64 `json:"end_mm"`
Status string `json:"status"`
}
func (uc *RecordSection) Execute(ctx context.Context, cmd RecordSectionCmd) (SectionDTO, error) {
serial, err := production.NewSerial(cmd.DrumSerial)
if err != nil {
return SectionDTO{}, err
}
if cmd.EndMM <= 0 {
return SectionDTO{}, fmt.Errorf("%w: end_mm must be positive", production.ErrInvalidLength)
}
if cmd.IdempotencyKey == "" {
return SectionDTO{}, fmt.Errorf("Idempotency-Key is required")
}
hash, err := hashRequest(cmd)
if err != nil {
return SectionDTO{}, err
}
var out SectionDTO
err = uc.UoW.WithinTx(ctx, func(ctx context.Context, tx Tx) error {
stored, reserved, err := tx.Idempotency().Reserve(ctx, cmd.IdempotencyKey, hash)
if err != nil {
return err
}
if !reserved {
if stored.Code == 0 {
return fmt.Errorf("%w: request in progress", production.ErrDuplicate)
}
return json.Unmarshal(stored.Body, &out)
}
d, err := tx.Drums().GetForUpdate(ctx, serial)
if err != nil {
return err
}
section, err := d.AddSection(production.LengthMM(cmd.EndMM))
if err != nil {
return err
}
if err := tx.Drums().Save(ctx, d); err != nil {
return err
}
if err := tx.Outbox().Append(ctx, d.PullEvents()...); err != nil {
return err
}
out = SectionDTO{
DrumSerial: string(d.Serial()),
Number: section.Number(),
StartMM: int64(section.StartMM()),
EndMM: int64(section.EndMM()),
Status: string(section.Status()),
}
body, err := json.Marshal(out)
if err != nil {
return err
}
return tx.Idempotency().Store(ctx, cmd.IdempotencyKey, StoredResponse{
Code: 201,
Body: body,
})
})
return out, err
}
func hashRequest(cmd RecordSectionCmd) ([]byte, error) {
b, err := json.Marshal(struct {
DrumSerial string `json:"drum_serial"`
EndMM int64 `json:"end_mm"`
}{cmd.DrumSerial, cmd.EndMM})
if err != nil {
return nil, err
}
sum := sha256.Sum256(b)
return sum[:], nil
}
Why GetForUpdate and not just optimistic locking
GetForUpdate runs SELECT ... FOR UPDATE and locks the drum row until commit. Two stations trying to append a section to the same drum serialize: the second waits, reads the updated produced_mm, and creates the correct section. Without the lock, both read the same produced_mm and one of them creates an overlapping section or an incorrect start.
The alternative is optimistic locking:
UPDATE production.drums
SET status = $1, produced_mm = $2, version = version + 1
WHERE serial = $3 AND version = $4;
If RowsAffected() == 0, someone changed the drum between the read and the write. The use case returns a conflict and the client retries. It is better for low-contention edits (for example, correcting a note), but for section appends the pessimistic lock is simpler and avoids retries that recompute the section.
| Scenario | Strategy | Why |
|---|---|---|
| Append section | SELECT ... FOR UPDATE |
Serializes the append and avoids gaps/overlaps |
| Attach test | SELECT ... FOR UPDATE |
The test depends on the section state |
| Edit attributes | Optimistic version |
Low contention; conflicts are exceptional |
| Reports | No lock | PostgreSQL uses MVCC; do not block reads |
| Global counters | Sequence / FOR UPDATE |
Avoids max(id)+1 races |
Idempotency: the MES retries, you do not duplicate
The MES, edge gateway, or PLC may retry a request after a timeout. If the server processed the operation but the response was lost, the retry must return the same response, not create another section.
CREATE TABLE integration.idempotency_keys (
key text PRIMARY KEY,
request_hash bytea NOT NULL,
response_code int NOT NULL DEFAULT 0,
response_body jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL
);
The flow is:
INSERT ... ON CONFLICT (key) DO NOTHING.- If it inserted, the request is new: process it and update
response_code/response_bodyat the end. - If it did not insert, read the row:
- same
request_hashand a completed response → return the stored response; - same hash but
response_code = 0→ the first request is still in progress; return409withRetry-After; - different hash → the client reused the key with another payload; return
422.
- same
Important detail: the idempotency row is inserted in the same transaction as the business change. If the transaction fails, the key is released and the retry can process again. If the transaction commits, the key and the effect are atomic.
Releasing a drum: the transaction that crosses contexts
Release is the use case where atomicity gets interesting: Production changes state, but Quality owns the hold. In the modular monolith, both reads share the same transaction.
type ReleaseDrum struct {
UoW UnitOfWork
}
type ReleaseDrumCmd struct {
DrumSerial string
IdempotencyKey string // same idempotency wrapper as RecordSection
}
func (uc *ReleaseDrum) Execute(ctx context.Context, cmd ReleaseDrumCmd) error {
serial, err := production.NewSerial(cmd.DrumSerial)
if err != nil {
return err
}
return uc.UoW.WithinTx(ctx, func(ctx context.Context, tx Tx) error {
d, err := tx.Drums().GetForUpdate(ctx, serial)
if err != nil {
return err
}
hasHold, err := tx.Holds().HasOpenHold(ctx, string(serial))
if err != nil {
return fmt.Errorf("hold check: %w", err)
}
if err := d.Release(hasHold); err != nil {
return err
}
if err := tx.Drums().Save(ctx, d); err != nil {
return err
}
return tx.Outbox().Append(ctx, d.PullEvents()...)
})
}
Why HoldChecker lives inside Tx: if it queried through the pool outside the transaction, it could read a different snapshot than the UPDATE. By sharing pgx.Tx, the check and the release see the same state. Idempotency is handled the same way as in RecordSection; it is omitted here to avoid repeating the pattern.
Why Release receives hasOpenHold instead of querying: the aggregate must not depend on a repository. The rule “do not release with an open hold” is expressed as a boolean parameter; the use case obtains the data and the domain decides. It is a simple way to keep the domain pure without inventing a domain service for a single query.
PostgreSQL: the schema that enforces the rules
The domain validates, but the database is the last line of defense. A bug in a use case, a manual migration, or an emergency script should not be able to leave a drum with overlapping sections.
Base schema
CREATE SCHEMA IF NOT EXISTS production;
CREATE SCHEMA IF NOT EXISTS quality;
CREATE SCHEMA IF NOT EXISTS integration;
CREATE TABLE production.work_orders (
id text PRIMARY KEY,
product_code text NOT NULL,
quantity_mm bigint NOT NULL CHECK (quantity_mm > 0),
due_date date NOT NULL,
status text NOT NULL CHECK (status IN ('planned','released','in_progress','done','cancelled')),
version bigint NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE production.drums (
serial text PRIMARY KEY,
work_order_id text NOT NULL REFERENCES production.work_orders(id),
product_code text NOT NULL,
capacity_mm bigint NOT NULL CHECK (capacity_mm > 0),
produced_mm bigint NOT NULL DEFAULT 0 CHECK (produced_mm >= 0),
status text NOT NULL CHECK (status IN ('created','in_process','awaiting_test','released','shipped','scrapped')),
version bigint NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CHECK (produced_mm <= capacity_mm)
);
CREATE TABLE production.drum_sections (
drum_serial text NOT NULL REFERENCES production.drums(serial) ON DELETE CASCADE,
number int NOT NULL CHECK (number > 0),
start_mm bigint NOT NULL CHECK (start_mm >= 0),
end_mm bigint NOT NULL,
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','passed','failed')),
test_id uuid,
PRIMARY KEY (drum_serial, number),
CHECK (end_mm > start_mm)
);
The constraint that prevents overlapping sections
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE production.drum_sections
ADD CONSTRAINT drum_sections_no_overlap
EXCLUDE USING gist (
drum_serial WITH =,
int8range(start_mm, end_mm, '[)') WITH &&
);
What it does: creates an exclusion constraint. For the same drum_serial, two ranges [start_mm, end_mm) cannot overlap. It is a database-level guarantee, not a convention.
Why btree_gist: the constraint combines equality (text) with overlap (int8range). btree_gist allows the B-tree equality operator to be used inside a GiST index.
What it does not cover: gaps. The application guarantees that start_mm equals the previous end_mm. A deferred trigger could validate it, but it adds complexity and locks. The reconciliation query at the end detects gaps.
Operations, tests, holds, and genealogy
CREATE TABLE production.operations (
id uuid PRIMARY KEY,
drum_serial text NOT NULL REFERENCES production.drums(serial),
section_number int,
operation_code text NOT NULL,
machine_id text NOT NULL,
operator_id text NOT NULL,
started_at timestamptz NOT NULL,
ended_at timestamptz,
parameters jsonb NOT NULL DEFAULT '{}'::jsonb,
request_id text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
FOREIGN KEY (drum_serial, section_number)
REFERENCES production.drum_sections(drum_serial, number)
);
CREATE TABLE quality.tests (
id uuid PRIMARY KEY,
drum_serial text NOT NULL,
section_number int NOT NULL,
test_type text NOT NULL,
result text NOT NULL CHECK (result IN ('pass','fail')),
value numeric,
unit text,
measured_at timestamptz NOT NULL,
instrument_id text NOT NULL,
UNIQUE (drum_serial, section_number, test_type, measured_at),
FOREIGN KEY (drum_serial, section_number)
REFERENCES production.drum_sections(drum_serial, number)
);
CREATE TABLE quality.holds (
id uuid PRIMARY KEY,
drum_serial text NOT NULL,
section_number int,
reason text NOT NULL,
status text NOT NULL CHECK (status IN ('open','released','scrapped')),
opened_at timestamptz NOT NULL DEFAULT now(),
opened_by text NOT NULL,
closed_at timestamptz,
closed_by text,
CHECK (status = 'open' OR closed_at IS NOT NULL)
);
CREATE UNIQUE INDEX holds_one_open_per_drum
ON quality.holds (drum_serial)
WHERE status = 'open';
CREATE TABLE production.genealogy_edges (
parent_kind text NOT NULL CHECK (parent_kind IN ('lot','drum','section')),
parent_id text NOT NULL,
child_kind text NOT NULL CHECK (child_kind IN ('drum','section')),
child_id text NOT NULL,
operation_code text NOT NULL,
qty_g bigint,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (parent_kind, parent_id, child_kind, child_id, operation_code)
);
CREATE INDEX genealogy_child_idx
ON production.genealogy_edges (child_kind, child_id);
CREATE INDEX genealogy_parent_idx
ON production.genealogy_edges (parent_kind, parent_id);
How it is populated: the use case that records an operation inserts the genealogy edge in the same transaction as the operation and the outbox. If the edge is not inserted, traceability is incomplete; that is why it is part of the transaction, not a later job.
About drum_sections.test_id: it is a soft reference to the current result in quality.tests. It is not an FK because quality.tests already references drum_sections; a bidirectional FK would create a circular dependency and complicate insertion order. The source of truth is quality.tests; test_id is a denormalization for fast reads.
Backward and forward traceability
The genealogy_edges table is a directed graph: each row says “this parent produced this child in this operation.” A recursive CTE can traverse it in both directions.
Backward from a drum (which copper and processes formed it?):
WITH RECURSIVE upstream AS (
SELECT parent_kind, parent_id, child_kind, child_id, operation_code, 1 AS depth
FROM production.genealogy_edges
WHERE child_kind = 'drum'
AND child_id = 'DR-MX-2026-000123'
UNION ALL
SELECT e.parent_kind, e.parent_id, e.child_kind, e.child_id, e.operation_code, u.depth + 1
FROM production.genealogy_edges e
JOIN upstream u
ON e.child_kind = u.parent_kind
AND e.child_id = u.parent_id
WHERE u.depth < 20
)
SELECT * FROM upstream ORDER BY depth;
Forward from a heat (which drums are affected and, from them, which shipments?):
WITH RECURSIVE downstream AS (
SELECT parent_kind, parent_id, child_kind, child_id, operation_code, 1 AS depth
FROM production.genealogy_edges
WHERE parent_kind = 'lot'
AND parent_id = 'LOT-CU-2026-0451'
UNION ALL
SELECT e.parent_kind, e.parent_id, e.child_kind, e.child_id, e.operation_code, d.depth + 1
FROM production.genealogy_edges e
JOIN downstream d
ON e.parent_kind = d.child_kind
AND e.parent_id = d.child_id
WHERE d.depth < 20
)
SELECT DISTINCT child_kind, child_id
FROM downstream
WHERE child_kind = 'drum';
From drum to shipment: the query returns drums. To reach shipments, join with your shipment table or add a drum -> shipment edge to the graph.
Why depth < 20: it prevents infinite loops if a manual load creates a circular edge. PostgreSQL 14+ supports CYCLE, but a depth limit is simple and sufficient for manufacturing chains. If your process has more than 20 transformations, raise it and document why.
Why DISTINCT in the forward query: a drum may appear through several paths (for example, if it shares a lot and a machine). DISTINCT removes duplicates; the edge table is already deduplicated by its PK.
About cross-schema FKs: in a modular monolith with a single database, an FK from quality.tests to production.drum_sections is acceptable and valuable. In microservices you cannot do it; there you would use IDs and eventual consistency. Decide consciously, not by accident.
Outbox and inbox
CREATE TABLE integration.outbox (
id uuid PRIMARY KEY,
aggregate_type text NOT NULL,
aggregate_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
occurred_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished_idx
ON integration.outbox (occurred_at)
WHERE published_at IS NULL;
CREATE TABLE integration.inbox (
message_id text PRIMARY KEY,
source text NOT NULL,
payload jsonb NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz
);
Indexes that matter
CREATE INDEX drums_open_idx
ON production.drums (status)
WHERE status IN ('in_process','awaiting_test');
CREATE INDEX sections_pending_idx
ON production.drum_sections (drum_serial)
WHERE status <> 'passed';
CREATE INDEX operations_drum_idx
ON production.operations (drum_serial, started_at DESC);
CREATE INDEX holds_open_idx
ON quality.holds (drum_serial)
WHERE status = 'open';
Do not index everything. Index the queries that exist: open drums, pending sections, operations by drum, and open holds. An index nobody uses is operational debt.
The PostgreSQL adapter
The UnitOfWork port is implemented with pgxpool. The key is that every operation in a transaction shares the same pgx.Tx.
package postgres
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"cableops/internal/app"
)
type DBTX interface {
Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
Query(context.Context, string, ...any) (pgx.Rows, error)
QueryRow(context.Context, string, ...any) pgx.Row
}
type UnitOfWork struct {
pool *pgxpool.Pool
}
func NewUnitOfWork(pool *pgxpool.Pool) *UnitOfWork {
return &UnitOfWork{pool: pool}
}
func (u *UnitOfWork) WithinTx(ctx context.Context, fn func(context.Context, app.Tx) error) error {
tx, err := u.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(ctx, newTx(tx)); err != nil {
return err
}
return tx.Commit(ctx)
}
type tx struct {
q pgx.Tx
}
func newTx(q pgx.Tx) *tx {
return &tx{q: q}
}
func (t *tx) Drums() app.DrumRepository { return &DrumRepo{q: t.q} }
func (t *tx) Holds() app.HoldChecker { return &HoldChecker{q: t.q} }
func (t *tx) Outbox() app.OutboxRepository { return &OutboxRepo{q: t.q} }
func (t *tx) Idempotency() app.IdempotencyRepository { return &IdempotencyRepo{q: t.q} }
// The outbox and idempotency repositories follow the same pattern:
// they receive a DBTX and run SQL inside the transaction.
type OutboxRepo struct{ q DBTX }
type IdempotencyRepo struct{ q DBTX }
Loading the aggregate (with and without a lock)
type DrumRepo struct {
q DBTX
}
func (r *DrumRepo) Get(ctx context.Context, serial production.Serial) (*production.Drum, error) {
return r.get(ctx, serial, false)
}
func (r *DrumRepo) GetForUpdate(ctx context.Context, serial production.Serial) (*production.Drum, error) {
return r.get(ctx, serial, true)
}
func (r *DrumRepo) get(ctx context.Context, serial production.Serial, forUpdate bool) (*production.Drum, error) {
query := `
SELECT work_order_id, product_code, capacity_mm, produced_mm, status, version
FROM production.drums
WHERE serial = $1`
if forUpdate {
query += ` FOR UPDATE`
}
var (
workOrderID, productCode string
capacityMM, producedMM int64
status string
version int64
)
err := r.q.QueryRow(ctx, query, string(serial)).Scan(
&workOrderID, &productCode, &capacityMM, &producedMM, &status, &version,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, production.ErrNotFound
}
if err != nil {
return nil, err
}
rows, err := r.q.Query(ctx, `
SELECT number, start_mm, end_mm, status, COALESCE(test_id::text, '')
FROM production.drum_sections
WHERE drum_serial = $1
ORDER BY number
`, string(serial))
if err != nil {
return nil, err
}
defer rows.Close()
var sections []production.Section
for rows.Next() {
var (
number int
start, end int64
st, testID string
)
if err := rows.Scan(&number, &start, &end, &st, &testID); err != nil {
return nil, err
}
sections = append(sections, production.RehydrateSection(
number,
production.LengthMM(start),
production.LengthMM(end),
production.SectionStatus(st),
testID,
))
}
if err := rows.Err(); err != nil {
return nil, err
}
return production.RehydrateDrum(
serial, workOrderID, productCode,
production.LengthMM(capacityMM),
production.LengthMM(producedMM),
production.Status(status),
sections,
version,
), nil
}
What FOR UPDATE does: it locks the drum row until the end of the transaction. Other stations that try to read with FOR UPDATE wait. Normal reads (Get) are not blocked thanks to MVCC.
Consistency note: Get performs two queries (header and sections). Under READ COMMITTED, another transaction could commit between them and return a slightly inconsistent view. For critical reads, use REPEATABLE READ, a single query with JSON aggregation, or GetForUpdate if you are going to write.
Saving the aggregate
func (r *DrumRepo) Save(ctx context.Context, d *production.Drum) error {
var newVersion int64
err := r.q.QueryRow(ctx, `
UPDATE production.drums
SET status = $1,
produced_mm = $2,
version = version + 1,
updated_at = now()
WHERE serial = $3 AND version = $4
RETURNING version
`,
string(d.Status()),
int64(d.ProducedMM()),
string(d.Serial()),
d.Version(),
).Scan(&newVersion)
if errors.Is(err, pgx.ErrNoRows) {
return production.ErrConcurrencyConflict
}
if err != nil {
return err
}
d.MarkPersisted(newVersion)
for _, s := range d.Sections() {
_, err := r.q.Exec(ctx, `
INSERT INTO production.drum_sections
(drum_serial, number, start_mm, end_mm, status, test_id)
VALUES ($1, $2, $3, $4, $5, NULLIF($6, '')::uuid)
ON CONFLICT (drum_serial, number)
DO UPDATE SET status = EXCLUDED.status, test_id = EXCLUDED.test_id
`,
string(d.Serial()),
s.Number(),
int64(s.StartMM()),
int64(s.EndMM()),
string(s.Status()),
s.TestID(),
)
if err != nil {
return err
}
}
return nil
}
Why upsert instead of delete/reinsert: sections have FKs from operations and quality.tests. Deleting them would break integrity or require cascading deletes of evidence. The upsert updates state and test_id without touching identity.
Why WHERE version = $4: although GetForUpdate already locks, the version condition protects against calls that use Get (no lock) and against changes made by another process. If nobody updated, the UPDATE returns the new version; if someone did, it returns zero rows and the use case decides whether to retry or conflict.
Checking the hold in the same transaction
type HoldChecker struct {
q DBTX
}
func (c *HoldChecker) HasOpenHold(ctx context.Context, drumSerial string) (bool, error) {
var exists bool
err := c.q.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1
FROM quality.holds
WHERE drum_serial = $1
AND status = 'open'
)
`, drumSerial).Scan(&exists)
return exists, err
}
In a modular monolith, this query shares the transaction and snapshot with the drum UPDATE. In microservices, HoldChecker would be an HTTP client or a local projection with fail-closed behavior. The interface does not change; the adapter does.
Migrations
Use a tool, not a manual ALTER TABLE in production:
go install github.com/pressly/goose/v3/cmd/goose@latest
goose -dir migrations postgres "$DATABASE_URL" up
Rule: migrations run as a separate job, not when the application starts. If you have three replicas and all of them migrate at the same time, you will have a race.
Real atomicity: outbox, sagas, and consistency
Atomicity inside one aggregate is easy: one transaction, one COMMIT. Atomicity across aggregates and services is another story.
The double-write problem
If you do this:
// WRONG: two writes, two systems, no atomicity
if err := drums.Save(ctx, d); err != nil { return err }
if err := bus.Publish(ctx, DrumReleased{...}); err != nil { return err }
you can save the drum and fail to publish the event. Production says “released,” but Quality and Shipping never find out. Or the reverse: you publish the event and the save fails; the rest of the world believes the drum is released and it is not.
The solution: transactional outbox
- In the same transaction, save the state and insert the event into
integration.outbox. - A publisher reads unpublished events, sends them to the broker, and marks them.
- If the publisher fails, it retries. If it publishes twice, the consumer deduplicates.
func (r *OutboxRepo) Append(ctx context.Context, events ...production.DomainEvent) error {
for _, ev := range events {
payload, err := json.Marshal(ev)
if err != nil {
return err
}
_, err = r.q.Exec(ctx, `
INSERT INTO integration.outbox
(id, aggregate_type, aggregate_id, event_type, payload)
VALUES ($1::uuid, $2, $3, $4, $5::jsonb)
`, uuid.NewV7().String(), "drum", ev.AggregateID(), ev.EventName(), string(payload))
if err != nil {
return err
}
}
return nil
}
Why uuid.NewV7(): Go 1.27’s new standard-library uuid package generates time-ordered UUIDs. That improves index locality and makes events sortable by ID if the clock behaves.
The publisher with SKIP LOCKED
type OutboxEvent struct {
ID string
Type string
Payload []byte
}
type EventBus interface {
Publish(ctx context.Context, ev OutboxEvent) error
}
type Publisher struct {
pool *pgxpool.Pool
bus EventBus
}
func (p *Publisher) publishBatch(ctx context.Context) (int, error) {
tx, err := p.pool.Begin(ctx)
if err != nil {
return 0, err
}
defer func() { _ = tx.Rollback(ctx) }()
rows, err := tx.Query(ctx, `
SELECT id, event_type, payload
FROM integration.outbox
WHERE published_at IS NULL
ORDER BY occurred_at
LIMIT 100
FOR UPDATE SKIP LOCKED
`)
if err != nil {
return 0, err
}
defer rows.Close()
var events []OutboxEvent
for rows.Next() {
var ev OutboxEvent
if err := rows.Scan(&ev.ID, &ev.Type, &ev.Payload); err != nil {
return 0, err
}
events = append(events, ev)
}
if err := rows.Err(); err != nil {
return 0, err
}
for _, ev := range events {
if err := p.bus.Publish(ctx, ev); err != nil {
return 0, fmt.Errorf("publish %s: %w", ev.ID, err)
}
}
if len(events) > 0 {
ids := make([]string, len(events))
for i, ev := range events {
ids[i] = ev.ID
}
if _, err := tx.Exec(ctx, `
UPDATE integration.outbox
SET published_at = now()
WHERE id = ANY($1::uuid[])
`, ids); err != nil {
return 0, err
}
}
return len(events), tx.Commit(ctx)
}
What FOR UPDATE SKIP LOCKED does: several publishers can run in parallel without stepping on each other. Each one takes a batch of unlocked rows; the others skip them. It is the basis of a simple queue on PostgreSQL.
Trade-off: publishing inside the transaction holds the lock while the broker responds. If the broker is slow, the batch takes longer. For high throughput, use a lease_until column, claim the batch, publish outside the transaction, and mark; if the publisher dies, the lease expires and another one picks it up. Start simple; scale when it hurts.
Idempotent consumers
The outbox guarantees at-least-once, not exactly-once. The consumer must deduplicate:
INSERT INTO integration.inbox (message_id, source, payload)
VALUES ($1, $2, $3::jsonb)
ON CONFLICT (message_id) DO NOTHING;
If RowsAffected() == 0, the message was already processed. If it is new, process it and mark processed_at in the same transaction. Inbox + outbox = reliable messaging without distributed transactions.
Sagas: when the operation crosses aggregates
Not every operation fits in one aggregate. Real examples:
- Quality hold: Quality opens a hold; Production must block release and shipping. In the monolith, the check is synchronous inside the same transaction; the saga appears when Quality is a separate service or when other systems must be notified.
- Drum split: close the parent drum, create the child, and transfer genealogy.
- Shipping: release the drum, create the shipment, print the label, and confirm the packing list.
For those cases, use a saga or process manager: a persistent state machine that listens to events and executes idempotent commands.
CREATE TABLE integration.sagas (
id uuid PRIMARY KEY,
kind text NOT NULL,
step text NOT NULL,
status text NOT NULL CHECK (status IN ('running','completed','failed','compensating')),
payload jsonb NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
Golden rule: every step must be idempotent and observable. If step 3 fails, the saga knows which step it is on and can retry or compensate. There is no magic: there is persisted state.
What you should not do
- 2PC/XA across microservices: distributed locks, a fragile coordinator, and clouds that do not support it well. Avoid it.
- Call the broker inside the domain transaction: the domain should not know a broker exists. The outbox solves it.
- Read OPC UA inside a database transaction: a 200 ms read with the row locked kills throughput. Read first, transact after.
- Rely on
SERIALIZABLEfor everything: it works, but conflicts and retries will force you to design idempotency anyway.
Isolation and concurrency: what PostgreSQL guarantees
PostgreSQL uses MVCC. By default, READ COMMITTED: each statement sees a snapshot of what was committed when the statement started. That does not prevent two transactions from reading the same value and then writing over it.
| Level | What it gives you | When to use it |
|---|---|---|
READ COMMITTED |
Each statement sees what is committed | Use cases with explicit locks (FOR UPDATE) |
REPEATABLE READ |
Stable snapshot for the transaction | Multiple consistent reads |
SERIALIZABLE |
Serial-equivalent; detects anomalies | Complex cross-row invariants; retry on 40001 |
For RecordSection, READ COMMITTED + SELECT ... FOR UPDATE is enough: the drum row serializes the append. For ReleaseDrum, use the same lock and check the hold in the same transaction. For long reports, use a read replica or REPEATABLE READ so all queries see the same snapshot.
The hold: reading the Quality context without breaking atomicity
ReleaseDrum needs to know whether there is an open hold. In a modular monolith with one database, you can query quality.holds inside the same transaction:
SELECT EXISTS (
SELECT 1
FROM quality.holds
WHERE drum_serial = $1
AND status = 'open'
);
That preserves the snapshot and avoids an inconsistency window. It is a cross-context read, not a write; it is a conscious compromise of the modular monolith.
If you split Quality into a microservice, you cannot do that query. Options:
- Local projection: Production keeps
drum_holdsupdated by events. If the projection is lagging, fail closed (block release) and alert. - Synchronous call:
HoldCheckercalls the Quality API with a timeout. If it fails, fail closed. Never release because of a missing response. - Saga: Quality opens the hold, emits an event, Production blocks. Release waits for confirmation. It is slower but decoupled.
Rule: when in doubt, do not release. A drum held for a day is a problem; a defective drum shipped is a crisis.
The API: HTTP for the MES, OPC UA for the machine
Endpoints
| Method | Path | Who | What it does |
|---|---|---|---|
POST |
/v1/drums |
MES / supervisor | Creates a drum from a work order |
POST |
/v1/drums/{serial}/sections |
MES / station | Records a section |
POST |
/v1/drums/{serial}/tests |
Quality / lab | Attaches a test |
POST |
/v1/drums/{serial}/complete |
MES | Completes production |
POST |
/v1/drums/{serial}/release |
Quality / supervisor | Releases the drum |
POST |
/v1/drums/{serial}/ship |
Shipping | Marks it as shipped |
POST |
/v1/drums/{serial}/holds |
Quality | Opens a hold |
POST |
/v1/holds/{id}/release |
Quality | Releases a hold |
GET |
/v1/drums/{serial}/trace |
Quality / audit | Returns genealogy |
GET |
/healthz, /readyz |
Infrastructure | Liveness and readiness |
HTTP handler
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"cableops/internal/app"
"cableops/internal/domain/production"
)
type Server struct {
recordSection *app.RecordSection
releaseDrum *app.ReleaseDrum
}
func (s *Server) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/drums/{serial}/sections", s.handleRecordSection)
mux.HandleFunc("POST /v1/drums/{serial}/release", s.handleRelease)
return mux
}
func (s *Server) handleRecordSection(w http.ResponseWriter, r *http.Request) {
var req struct {
EndMM int64 `json:"end_mm"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "INVALID_JSON", "invalid body")
return
}
key := r.Header.Get("Idempotency-Key")
if key == "" {
writeError(w, http.StatusBadRequest, "MISSING_IDEMPOTENCY_KEY", "missing Idempotency-Key")
return
}
out, err := s.recordSection.Execute(r.Context(), app.RecordSectionCmd{
DrumSerial: r.PathValue("serial"),
EndMM: req.EndMM,
IdempotencyKey: key,
})
if err != nil {
switch {
case errors.Is(err, production.ErrNotFound):
writeError(w, http.StatusNotFound, "NOT_FOUND", "drum not found")
case errors.Is(err, production.ErrConcurrencyConflict),
errors.Is(err, production.ErrOpenHold),
errors.Is(err, production.ErrDuplicate):
writeError(w, http.StatusConflict, "CONFLICT", err.Error())
case errors.Is(err, production.ErrCapacityExceeded),
errors.Is(err, production.ErrInvalidLength):
writeError(w, http.StatusUnprocessableEntity, "INVALID_SECTION", err.Error())
default:
writeError(w, http.StatusInternalServerError, "INTERNAL", "internal error")
}
return
}
writeJSON(w, http.StatusCreated, out)
}
Headers that matter
Idempotency-Key: required on all state-changingPOSTs.X-Correlation-ID: follows an operation across MES, API, outbox, and consumers.X-Request-ID: generated by the server if absent; logged in logs and traces.If-Match/ETag: an alternative toversionfor HTTP clients that want concurrency control.
Uniform error response
{
"error": {
"code": "CONFLICT",
"message": "drum has an open quality hold",
"request_id": "019b1f3e-7c2a-7d4e-9a11-3f6c2b8d9e01"
}
}
Do not return stack traces or SQL. The operator needs an actionable message; the auditor needs the request_id to find the details.
OPC UA: read the machine, not the database
The PLC does not speak JSON and does not know your aggregate. The OPC UA adapter reads tags and translates them into an application command:
type MachineReader interface {
ReadTags(ctx context.Context, machineID string, tags []string) (map[string]float64, error)
}
readings, err := machines.ReadTags(ctx, cmd.MachineID, []string{
"LineSpeed",
"AnnealingTemperature",
"Diameter",
})
if err != nil {
return fmt.Errorf("OPC UA %s: %w", cmd.MachineID, err)
}
// Only after reading, open the transaction and record the operation.
return uc.recordOperation.Execute(ctx, app.RecordOperationCmd{
DrumSerial: cmd.DrumSerial,
MachineID: cmd.MachineID,
Parameters: readings,
})
Why outside the transaction: an OPC UA read can take hundreds of milliseconds or fail. If you do it with the drum row locked, you block every station. Read, validate, then transact.
If the machine is disconnected: the edge gateway should buffer locally (SQLite + outbox) and forward when the network returns. Each message carries a unique message_id so the server can deduplicate.
MES and ERP: ISA-95 in practice
- Level 4 (ERP): production orders, BOM, routings, customers. It speaks in documents (B2MML/XML, REST, files).
- Level 3 (MES): this backend. It executes, decomposes, records, validates.
- Level 2 (SCADA/PLC): OPC UA, tags, alarms.
- Level 1/0: sensors and the physical process.
Do not put the ERP in the critical path of a station. If the ERP does not respond, the plant cannot stop producing. Synchronize orders and master data asynchronously; the station works with a local copy and reconciles later.
Security and auditing
- mTLS between the edge, the MES, and the API; do not trust the internal network alone.
- RBAC: the operator records sections; quality opens and releases holds; the supervisor releases drums; shipping dispatches. The same endpoint should not serve everyone.
- Append-only audit: who, what, when, previous and new value. Do not allow
UPDATEorDELETEon the audit table. - Secrets in a manager (Vault, KMS, orchestrator variables), never in the repository.
- Rate limiting per machine or API key so a runaway PLC cannot take down the API.
- OPC UA with signing and encryption; segment the OT/IT network per IEC 62443.
Testing: domain, integration, and concurrency
Domain tests
func TestDrumAddSection(t *testing.T) {
serial, _ := production.NewSerial("DR-MX-2026-000123")
d, _ := production.NewDrum(serial, "WO-2026-1842", "CABLE-2.5", 10_000)
if _, err := d.AddSection(2_500); err != nil {
t.Fatalf("first section: %v", err)
}
if _, err := d.AddSection(2_500); !errors.Is(err, production.ErrInvalidLength) {
t.Fatalf("non-increasing section: got %v", err)
}
if _, err := d.AddSection(12_000); !errors.Is(err, production.ErrCapacityExceeded) {
t.Fatalf("capacity: got %v", err)
}
}
Domain tests need no database, mocks, or server. They are fast and tell you whether the business rules are right.
Integration tests with a real PostgreSQL
Do not mock PostgreSQL to test transactions, locks, or constraints. Use a container:
func TestRecordSectionIdempotent(t *testing.T) {
ctx := context.Background()
pool := startPostgres(t, ctx) // testcontainers-go + migrations
uow := postgres.NewUnitOfWork(pool)
uc := &app.RecordSection{UoW: uow}
cmd := app.RecordSectionCmd{
DrumSerial: "DR-MX-2026-000123",
EndMM: 2_500,
IdempotencyKey: "req-001",
}
first, err := uc.Execute(ctx, cmd)
if err != nil {
t.Fatal(err)
}
second, err := uc.Execute(ctx, cmd)
if err != nil {
t.Fatal(err)
}
if first != second {
t.Fatalf("different responses: %+v vs %+v", first, second)
}
var count int
if err := pool.QueryRow(ctx, `
SELECT count(*) FROM production.drum_sections
WHERE drum_serial = $1
`, cmd.DrumSerial).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 1 {
t.Fatalf("sections = %d, want 1", count)
}
}
Concurrency test
func TestConcurrentSections(t *testing.T) {
// Two goroutines try to append sections to the same drum.
// With FOR UPDATE, both serialize and the result is 0-2500 and 2500-5000.
// With optimistic locking, one gets ErrConcurrencyConflict and retries.
}
That test separates a toy system from a plant system. If you do not test concurrency, you do not know whether your produced_mm is correct under load.
Test checklist
- Section end less than or equal to produced → error.
- Section exceeding capacity → error.
- Two overlapping sections → domain error and DB constraint.
- Duplicate test on the same section → error.
- Release with a pending section → error.
- Release with an open hold → error.
- Same idempotency key, same payload → same response, one effect.
- Same idempotency key, different payload →
422. - Two concurrent requests to the same drum → one waits or conflicts, no overlap.
- Outbox contains the event in the same transaction.
- Consumer processes the same message twice → one effect.
Operations: observability, reconciliation, and runbook
Metrics that matter
| Metric | What it detects |
|---|---|
cableops_sections_total{status} |
Production rate and failure ratio |
cableops_release_blocked_total{reason} |
Holds, pending tests, conflicts |
cableops_outbox_unpublished |
Stuck events |
cableops_outbox_lag_seconds |
Delay between fact and publication |
cableops_db_conflicts_total |
Real contention in the database |
cableops_opcua_read_errors_total |
Unstable machines or network |
cableops_hold_open_total |
Holds nobody closes |
cableops_request_duration_seconds |
Latency per endpoint |
Structured logs
logger.InfoContext(ctx, "section_recorded",
"request_id", requestID,
"drum_serial", serial,
"section_number", section.Number(),
"start_mm", section.StartMM(),
"end_mm", section.EndMM(),
"operator_id", operatorID,
"machine_id", machineID,
"duration_ms", time.Since(start).Milliseconds(),
)
Never log the full payload with personal data. Log IDs, lengths, error codes, and duration.
Reconciliation queries
-- Drums with production but no sections (transaction bug)
WITH drums_with_sections AS (
SELECT DISTINCT drum_serial
FROM production.drum_sections
)
SELECT d.serial, d.produced_mm
FROM production.drums d
LEFT JOIN drums_with_sections s ON s.drum_serial = d.serial
WHERE d.produced_mm > 0
AND s.drum_serial IS NULL;
-- Gaps between sections
WITH ordered AS (
SELECT drum_serial, number, start_mm, end_mm,
lag(end_mm) OVER (PARTITION BY drum_serial ORDER BY number) AS prev_end
FROM production.drum_sections
)
SELECT *
FROM ordered
WHERE start_mm <> COALESCE(prev_end, 0);
-- Drums waiting for test too long
SELECT serial, updated_at
FROM production.drums
WHERE status = 'awaiting_test'
AND updated_at < now() - interval '24 hours';
-- Stuck outbox
SELECT count(*) AS pending, min(occurred_at) AS oldest
FROM integration.outbox
WHERE published_at IS NULL;
-- Holds open too long
SELECT drum_serial, id, opened_at
FROM quality.holds
WHERE status = 'open'
AND opened_at < now() - interval '24 hours';
Runbook for the customer complaint
- Identify the drum and section from the label or report.
- Query backward genealogy: heat, lot, operations, machines, parameters, tests.
- Query forward genealogy: every drum that shares the copper lot or machine.
- Check the tests: did it pass? With which instrument? Was it calibrated?
- Check the holds: was a hold released? By whom and with what justification?
- Check changes: state audit, version, and events.
- Document the finding with a reproducible query, not a screenshot.
That last point connects to the data forensics posts: when the system does not exist or has already failed, files and databases become the crime scene. You can read the Linux forensics case with DuckDB and Polars and the Windows forensics case with SMB and SQL Server.
Architecture decisions you can defend
1. Modular monolith before microservices
A cable plant does not need ten microservices on day one. A modular monolith with well-separated contexts gives you local transactions, simple deployment, and low latency. When a context needs to scale independently, extract it with the outbox already in place.
2. The Drum aggregate is the transactional boundary
Do not create a transaction that spans three drums and a work order. If you need that consistency, it is a sign that the boundary is wrong. A drum is modified in one transaction; processes that cross drums are sagas.
3. Events are facts, not commands
SectionAdded describes something that happened. AddSection is a command. Do not mix both in the same type. Events are persisted in the outbox; commands are validated in the aggregate.
4. A hold is a Quality aggregate
It is not a drum state. It is an external constraint with its own lifecycle, owner, reason, and evidence. Production queries it; Quality governs it.
5. Traceability is a read model, not a giant JSON
Do not store the entire history in a history jsonb column on the drum. Store normalized facts (operations, tests, genealogy) and build the traceability view with queries. That way you can audit, index, and query backward and forward.
6. The database is not the domain, but it protects it
The domain validates the rules. The database reinforces them with CHECK, UNIQUE, FOREIGN KEY, and EXCLUDE. If you trust only the code, an emergency script breaks consistency. If you trust only the database, the domain becomes a set of cryptic errors.
7. State + outbox before event sourcing
The current state lives in tables; events are facts for integration and auditing. Event sourcing is useful when you need to rebuild state from the log, but it adds projections, event versioning, and snapshots. For a plant that must operate tomorrow, start with state + outbox and evolve if the business demands it.
Common mistakes (and how to avoid them)
- Using
float64for lengths, weights, or money. Use integers in the smallest unit. - Generating serials with
max(serial)+1. Use a sequence; gaps do not matter, uniqueness does. - Saving the drum and the section in separate transactions. A partial
COMMITleaves orphan data. - Forgetting idempotency. The MES retries; your API duplicates.
- Reading OPC UA inside the transaction. You block the row while waiting for the machine.
- Making the hold a drum state. You lose the previous state and mix contexts.
- Not testing concurrency. The bug appears on the night shift, with two stations and a production spike.
- Using
SERIALIZABLEeverywhere. You will spend your life retrying. - Not measuring the outbox. Events pile up and nobody notices until the customer asks.
- Not documenting audit queries. A screenshot is not reproducible evidence.
- Confusing lot with serial. The lot groups; the serial identifies one unit. You need both.
- Not planning data retention. In automotive, the customer may ask for records from years ago; design archiving from day one.
Final checklist
- The domain imports no HTTP, SQL, or OPC UA.
- Value objects prevent invalid states.
- The
Drumaggregate protects contiguity, capacity, and tests. - Each use case opens one transaction and saves state + outbox.
-
SELECT ... FOR UPDATEorversionas appropriate. - Idempotency key on every state-changing
POST. - Constraints:
CHECK,UNIQUE,FOREIGN KEY,EXCLUDE. - Outbox published with
SKIP LOCKEDand idempotent consumers. - Quality hold as a separate aggregate.
- Backward and forward traceability with genealogy.
- Domain, integration, concurrency, and idempotency tests.
- Metrics for outbox, conflicts, holds, and latency.
- Runbook and reconciliation queries documented.
- Migrations as a separate job, with backups and rollback plan.
- GS1/DataMatrix labels and human-readable serials.
Further reading
- If you want the foundations of DDD and hexagonal architecture in Go: Domain-Driven Design in Go: from zero to expert.
- If you want the enterprise DDD/hexagonal playbook: DDD, Hexagonal Architecture, BDD & TDD for Agile Teams.
- If you want a complete Go 1.27 API with Gin and SQLite: Go 1.27, Gin & SQLite: Notes API with Hexagonal Architecture.
- If the problem already happened and you only have files: Linux data forensics with DuckDB and Polars and Windows data forensics with SMB and SQL Server.
- If you want data contracts and quality: Data contracts, Great Expectations, and Soda.
- If you want to analyze the plant with a columnar format: Parquet deep dive and DuckDB hands-on.
A cable plant does not fail for lack of software. It fails when the software cannot prove what happened. The difference between an MES that records and a traceability system that serves is the same as the difference between writing in a notebook and having a domain with invariants, atomic transactions, and reproducible evidence. Copper is transformed; trust is too.
Related articles
By relevance
Go Notes API: BDD, TDD, DDD, Hexagonal Architecture with Gin, gRPC, Redis & PostgreSQL
Build a production-ready Notes API in Go 1.24+ using BDD, TDD, DDD, Hexagonal Architecture, Gin, gRPC, Redis, PostgreSQL, JWT auth, Docker, FX, and Zap. Step by step.
DDD, Hexagonal Architecture, BDD & TDD for Agile Teams: The Enterprise Playbook
Master Domain Driven Design, Hexagonal Architecture, BDD, and TDD in Agile Scrum teams. Real enterprise case studies, Go, React, and Flutter implementations with practical tools and workflows.
Go 1.27, Gin & SQLite: Notes API with Hexagonal Architecture
A step-by-step guide to building a REST notes API in Go 1.27 with Gin, SQLite and Hexagonal Architecture + DDD. Clean code, tests and Docker included.
Go 1.26 Full-Stack Notes App: SolidJS, Auth, Hexagonal Architecture & DDD from Zero
Build a full-stack notes app in Go 1.26 with SolidJS, JWT auth, and Hexagonal Architecture. Step-by-step from zero to production with DDD, TDD, and BDD.