Skip to content

Serial Traceability From Customs Intake to Dispatch: A Stage Model and Reverse Lookup

When a dispatched unit comes back, you need to know what's inside it, where those parts came from and who handled them. Here's a stage model, a component-linking design and a recursive query, shown on a synthetic dataset.

Six labelled production stations sit on a conveyor; a backwards orange arc traces the dispatched unit toward intake.
Synthetic finished serial FG-24-00017 links to an assembly, an enclosure without stage events and one screw lot. The assembly also links to two imported components and the same lot.
Synthetic example — not client data • serial boxes and the labelled lot are different inputs

Text equivalent. Serial traceability Teaching diagram • Stage events and shared inputs FG-24-00017 Finished serial ASM-0091 Sub-assembly serial ENC-5520 No stage events PCB-77310 Import IMP-2026-0388 SNS-11902 Import IMP-2026-0391 LOT-SCR-0412 Shared screw lot x6 x4 One lot, two incoming links. Shared input is not a cycle. Synthetic example — not client data • serial boxes and the labelled lot are different inputs

Full-size diagram

A customer calls about a unit you shipped two months ago. Quality wants to know which control board is inside it, which import shipment that board came from, and which other units used parts from the same delivery. If the answer lives in three spreadsheets and someone's memory, it may require reconstructing several records. If it lives in a linked record, it's one query.

This article sets out the record design behind that query. It covers a six-stage model from customs intake to dispatch, what each stage should record, how components link to finished serial numbers, and a recursive lookup that walks from a finished unit back to its inputs. It also covers the edge cases that break a naive design: shared lots, duplicate links and cycles.

About the examples. The six stages match a production-tracking system I built for an industrial import and manufacturing client (case study). That system records personnel at every stage and supports reverse lookup by finished serial. Every table, part number and query below is a synthetic, illustrative example written for this article. None of it is the client's data, schema or code. The SQL was exercised in PGlite 0.5.15, an in-process WebAssembly build that reports itself as PostgreSQL 18.6. An assertion suite of 10 checks passed. It covers the exact reverse and forward lookup rows, one accepted valid link, five rejected invalid inserts by error code, and a cycle edge that the constraints accept and the query flags. Against a deliberately weakened schema, 3 of the 10 checks failed, as intended. That is not a conventional PostgreSQL server deployment test or a concurrency test. The snippets below are partial: the full sample data isn't reproduced.

If you're still deciding whether you need a custom system at all, start with what to automate first, and when a custom ERP is worth it. This article assumes you've decided traceability is the problem to solve.

The stage model

Traceability is a chain of records. Every physical handoff creates one, so the first design step is naming the handoffs:

Customs intake → Warehouse → Production → Rule-based assembly → Finished goods → Dispatch

StageWhat physically happensRecord it createsFields that matter later
Customs intakeImported goods are received and counted against the declarationOne unit or lot record per item received; an intake eventSerial or lot code, part number, import/declaration reference, supplier, received by, time
WarehouseGoods are put away, moved, issuedStage events (put-away, issue)Location, issued to, by whom, when
ProductionParts are prepared or worked onStage eventsWork order, station, operator, time
Rule-based assemblyComponents are built into an assembly against a ruleConsumption links (child → parent) plus an assembly eventParent serial, child serial or lot, quantity, station, operator, time
Finished goodsThe finished unit passes final checks and enters stockStage event; the finished serial becomes sellableChecked by, time, result
DispatchThe unit leaves for a customerStage event linked to the sales documentCustomer/order reference, shipped by, time

Two principles hold the model together:

  1. Every record answers who, what and when. "What" is the unit and the action. "Who" is a person or a station login, never "system", unless a machine really did it. "When" is a timestamp in a stated time zone.
  2. In this model, only assembly creates links. The other stages add history to a unit. Assembly is where units become part of other units, so it's where most traceability is won or lost. Real products may also need lineage changes for rework, replacement or packaging; this toy model doesn't cover them.

Serial or lot, and history versus status

Two distinctions decide how much the lookup can tell you.

Serial versus lot. A serial identifies one physical item. A lot (or batch) identifies a group received or made together, such as a box of screws or a reel of cable.

Track by serial when…Track by lot when…
A single item may be recalled, repaired or warrantiedItems are interchangeable consumables
The item is valuable or safety-relevantLabelling each item is impractical
The customer or regulator asks "which exact one?""Which delivery did it come from?" is enough

The tradeoff is scope. Lot tracking tells you a finished unit contains screws from lot X, not which screws. A problem with lot X therefore implicates every unit that drew from it. That may be acceptable. Decide it on purpose, per part number.

Event history versus current status. Store what happened as a list of events, and treat that history as the record. In this model, "latest stage" is derived from the latest event. A materialized status column is also legitimate for speed, as long as the event history is preserved. What goes wrong is a status field people overwrite instead of keeping history: it loses who changed it and when. Corrections should be new events (for example a reversal with a reason), not edits.

sql
create table stage_events (                   -- intended append-only (not enforced in this sample)
  event_id    bigint generated always as identity primary key,
  unit_id     text not null references units,
  stage       text not null check (stage in
               ('intake', 'warehouse', 'production', 'assembly', 'finished_goods', 'dispatch')),
  actor       text not null,                  -- person or station login
  occurred_at timestamptz not null,
  detail      jsonb
);

create view unit_current_stage as             -- a unit's own latest event
select distinct on (unit_id) unit_id, stage, actor, occurred_at
from stage_events
order by unit_id, occurred_at desc, event_id desc;

Linking components to finished serials

The core table records "this child was built into this parent":

sql
create table units (
  unit_id    text primary key,                -- serial number, or lot code
  tracking   text not null check (tracking in ('serial', 'lot')),
  part_no    text not null,
  intake_ref text,                            -- import/declaration reference, if received from outside
  unique (unit_id, tracking)
);

create table consumption (                    -- "child was built into parent"
  parent_id       text not null,
  parent_tracking text not null default 'serial' check (parent_tracking = 'serial'),
  child_id        text not null,
  child_tracking  text not null,
  qty             numeric not null default 1 check (qty > 0),
  linked_by       text not null,
  linked_at       timestamptz not null,
  primary key (parent_id, child_id),          -- no duplicate edges
  check (parent_id <> child_id),              -- no trivial self-loop
  foreign key (parent_id, parent_tracking) references units (unit_id, tracking),
  foreign key (child_id,  child_tracking)  references units (unit_id, tracking)
);

-- A serial can be built into only one parent; a lot can feed many.
create unique index one_parent_per_serial
  on consumption (child_id) where child_tracking = 'serial';

Each constraint blocks a real mistake. In the sample run, inserts of each of these kinds were rejected:

MistakeWhat stops it
Scanning the same board into the same assembly twicePrimary key on (parent, child)
Scanning a board already used in assembly A into assembly BPartial unique index on serial children
Treating a lot code as if it were a serialComposite foreign key on (id, tracking)
Recording a lot as the parent of somethingparent_tracking must be serial

"Rule-based assembly" means the link is checked before it's saved. A rule might say a CTRL-ASSY takes exactly one CTRL-BOARD, one PRESS-SENSOR and four M4-SCREW. That's an illustrative rule. Real rules come from the bill of materials and the people who build the product. The station rejects the scan if the part number doesn't belong, if the serial is already used, or if the count is already met. Database constraints catch structural errors. Business rules belong in the application layer, where the operator sees a clear message.

Reverse lookup: from a finished serial back to its inputs

The full structure is a directed graph rather than a strict tree, because lots are shared between parents. The recursive output below is a path expansion from one finished unit, and you don't know its depth in advance. A finished unit contains assemblies, those contain components, and some components are lots. That's what recursive queries are for. In the PostgreSQL documentation's words, "Using RECURSIVE, a WITH query can refer to its own output."

sql
with recursive tree (unit_id, parent_id, qty, depth) as (
    select 'FG-24-00017'::text, null::text, 1::numeric, 0
  union all
    select c.child_id, c.parent_id, c.qty, t.depth + 1
    from consumption c
    join tree t on c.parent_id = t.unit_id
) cycle unit_id set is_cycle using path
select t.depth, t.unit_id, t.parent_id, u.tracking, u.part_no, t.qty,
       u.intake_ref, s.stage as current_stage, t.is_cycle
from tree t
join units u using (unit_id)
left join unit_current_stage s using (unit_id)   -- latest event per unit
order by t.path;

Result on the synthetic dataset (is_cycle is false for every row in this clean case, so the column is omitted):

depthunitbuilt intotrackingpartqtyintake reflatest stage
0FG-24-00017(none)serialPUMP-UNIT-A1(none)dispatch
1ASM-0091FG-24-00017serialCTRL-ASSY1(none)assembly
2LOT-SCR-0412ASM-0091lotM4-SCREW4IMP-2026-0402warehouse
2PCB-77310ASM-0091serialCTRL-BOARD1IMP-2026-0388production
2SNS-11902ASM-0091serialPRESS-SENSOR1IMP-2026-0391warehouse
1ENC-5520FG-24-00017serialENCLOSURE1(none)no events
1LOT-SCR-0412FG-24-00017lotM4-SCREW6IMP-2026-0402warehouse

This result answers the customer's question: the unit contains board PCB-77310, received under import reference IMP-2026-0388. It also shows three things a design has to handle.

  1. A lot can appear twice without a cycle. LOT-SCR-0412 was used in the sub-assembly and again at final assembly. That's two paths to one shared input, and the quantities belong to each path. Don't de-duplicate by unit, or you'll lose quantities and the route.
  2. "Latest stage" for a consumed part is its own latest event, not where it is. The board's last own event is "production", but it now sits inside a dispatched unit. Physical location, a unit's own latest event and its membership in a parent are different facts. A consumed serial's effective location may follow its parent chain. A shared lot can't inherit one parent's status, because it feeds several. Derive these from the consumption table rather than expecting operators to update every child.
  3. Gaps are visible in this report. The enclosure has no stage events at all, and the lookup shows it as a row that says something wasn't scanned. A spreadsheet can flag missing values too, if it's built to.

Cycles: constraints aren't enough

The constraints above prevent duplicates and serial reuse. They can't prevent every loop. If a bad import records the finished unit as a child of its own board, each serial still has only one parent, and the insert succeeds. Without protection, the recursive query would follow that loop forever. PostgreSQL's docs warn that the recursive part must "eventually return no tuples, or else the query will loop indefinitely."

The CYCLE clause (PostgreSQL 14+) tracks the path and flags a repeated unit. With the bad edge added to the sample data, the query stops and marks the repeated FG-24-00017 row with is_cycle = true rather than hanging. That's a query-level safety net. The CYCLE clause doesn't enforce acyclic writes. At write time, validate ancestry (the new parent mustn't already be a descendant of the child) and use a concurrency-safe write strategy. A read-before-insert check inside a transaction is not enough on its own when writers run concurrently. This sample doesn't implement or test that write-time check.

Forward lookup: "where did this lot go?"

Recalls run the other way: start from a suspect input and find every finished unit it reached. It's the same recursion with the join reversed (c.child_id = up.unit_id, selecting c.parent_id). On the sample data, lot LOT-SCR-0412 resolves to two finished units, one already dispatched and one still in finished-goods stock. Those are the two lists a recall needs: units to contact customers about, and units to hold.

Performance note: the primary key covers lookups by parent. Add an index on consumption (child_id) for the forward direction, because the partial unique index only covers serial children, not lots.

What this sample model doesn't do

So nobody mistakes it for a production schema:

  • Permanent consumption. The unique serial-parent index models a serial as permanently built in. Disassembly and reuse would need an end-dated link or a reversal event.
  • qty is per edge, not a cumulative bill-of-materials quantity. Serial quantity isn't constrained to one.
  • Not implemented: lot inventory balances, BOM completeness checks, enforced append-only history, quantity roll-ups and the write-time cycle check.

Where a flat, overwritten sheet falls short

Spreadsheets are fine for a single-level list of what's in stock. The problem isn't "spreadsheets" in general. It's the flat sheet modelled here, where each row's values are overwritten, lacking three things this lookup needs:

  • History. In an overwritten sheet a cell holds the current value. When someone types over "warehouse" with "production", the who and when are gone unless the sheet keeps disciplined change logs.
  • Enforced links. Without validation rules, nothing stops the same serial being typed into two assembly rows, or a typo creating a serial that never existed. The constraints in the table above do that structurally.
  • Unknown depth. Walking finished unit → assembly → component → lot takes one lookup per level, written by hand. A recursive query doesn't care how deep the tree goes.

If your products are single-level (no sub-assemblies) and low-volume, a disciplined sheet with a change log may be enough. Once units contain units, linked records start to pay for themselves. If the status itself still lives in a sheet rather than a stage ledger, outgrowing the production spreadsheet covers a status-event model to start from.

What leadership and customers actually need from it

The output most people need is one page per serial: the path-expanded lineage above, plus the dated stage history with names. That's what a customer audit or a warranty claim asks for. Recurring reporting is a different job, built from the same stage records. Keep the two separate so the traceability record never gets reshaped to fit a report.

Turning the same stage records into the recurring Excel report leadership already reads is covered in automating a recurring Excel report from production data.

Rolling it out alongside existing tools

You don't need to replace accounting or inventory software to start. A practical sequence:

  1. Start where links are created. Put scanning at assembly first. Without consumption links there's no genealogy, however good the other stages are.
  2. Open with what's on hand. Load current stock as intake records flagged as an opening balance, so the history is honest about where it begins.
  3. Add stages outward. Intake (for import references) and dispatch (for customer references) come next, because they bound the chain. Warehouse and production events fill in the middle.
  4. Keep finance where it is. Accounting stays in the existing system. Share identifiers (part numbers, order references) instead of duplicating ledgers.
  5. Run in parallel for a defined period. Keep the old sheet while stations learn the scans, and compare a sample of lookups against reality before retiring it.

Decide early: who scans at each station, what happens when a station is offline, how labels are printed and re-printed, and who may record a correction.

Limits to state plainly. Traceability records what people and stations scanned. It doesn't prove a part was good. A missed scan is a hole in the record, and lot-level tracking is only as fine-grained as the lot. Design the stations so the correct scan is the easiest action.


Map a production traceability workflow. If parts come in under import paperwork and leave inside finished serials, I can help you map the stages, decide what to track by serial versus lot, and design the lookup before anything is built. This is the Ops & Traceability work; start here.


Sources

Put the thinking to work

What could this change for you?

Tell me what you’re building — I’ll tell you honestly where I’d start.

Start a project with me