A shipper-side backend that receives carrier invoices from EDI 210 or API feeds, rejects duplicates, checks linehaul, fuel surcharge and accessorial charges against the contract and shipment events, approves within tolerance, short-pays with a dispute when a charge is not supported, and escalates disputes that stall.

Carrier invoices are mostly right, and the wrong ones cost money: detention with no dock times behind it, a liftgate nobody ordered, fuel at last month's diesel price, or one load billed twice. Checking them by hand takes an analyst per few thousand loads.
This guide builds the backend that audits every invoice and only sends exceptions to people.
An X12 210, the Motor Carrier Freight Details and Invoice, carries the carrier's invoice number, the bill of lading or shipment ID it bills, the shipment date, and line items for linehaul, fuel surcharge and accessorial charges, each with a charge code and amount, plus the total due. Carriers without EDI send the same content through an API or as a PDF. The EDI integration guide covers receiving and translating X12 files, and this guide starts from the normalized invoice.
The rules are a pure package: given a contract, the facts about the shipment and the invoice lines, it returns the approved total and a finding for every line it will not pay in full:
// audit/rules.go
package audit
import (
"fmt"
"math"
)
// Contract is the agreed pricing for one carrier on one lane.
type Contract struct {
LinehaulCents int64 // flat rate for the lane
Miles float64 // contracted lane miles
FuelBaseCents int64 // diesel price per gallon included in the linehaul
FuelMPG float64 // miles per gallon used in the fuel formula
Accessorials map[string]int64 // approved flat charges by code, for example "LFT"
DetentionFree float64 // free hours at the dock
DetentionCents int64 // per hour after the free time
}
type Line struct {
Code string `json:"code"` // "LH" linehaul, "FUE" fuel, "LFT", "DET" ...
Description string `json:"description"`
BilledCents int64 `json:"billed_cents"`
}
type Shipment struct {
DieselCents int64 // published weekly diesel price for the pickup week
DockHours float64 // from check-in and check-out events, 0 if unknown
HadLiftgate bool // from the booking or proof of delivery
}
type Finding struct {
Code string
BilledCents int64
ExpectedCents int64
Reason string
}
// Tolerance per line: the larger of $5 or 1 percent of the expected amount.
func withinTolerance(billed, expected int64) bool {
tol := max(int64(500), expected/100)
return billed <= expected+tol
}
// Expected returns the contract amount for a line, or false if the charge is not allowed.
func Expected(c Contract, s Shipment, code string) (int64, string, bool) {
switch code {
case "LH":
return c.LinehaulCents, "", true
case "FUE":
over := s.DieselCents - c.FuelBaseCents
if over <= 0 || c.FuelMPG <= 0 {
return 0, "diesel at or below the contract base price", true
}
return int64(math.Round(c.Miles / c.FuelMPG * float64(over))), "", true
case "DET":
if s.DockHours == 0 {
return 0, "no dock times recorded for this shipment", false
}
billable := math.Max(0, s.DockHours-c.DetentionFree)
return int64(math.Round(billable * float64(c.DetentionCents))), "", true
case "LFT":
if !s.HadLiftgate {
return 0, "liftgate not requested on the booking", false
}
}
amount, ok := c.Accessorials[code]
if !ok {
return 0, "charge code not in the contract", false
}
return amount, "", true
}
// Audit compares every line against the contract and returns the approved
// total and the lines that should be disputed.
func Audit(c Contract, s Shipment, lines []Line) (approvedCents int64, findings []Finding) {
seen := map[string]bool{}
for _, l := range lines {
if seen[l.Code] && l.Code != "MSC" {
findings = append(findings, Finding{l.Code, l.BilledCents, 0, "charge billed twice on one invoice"})
continue
}
seen[l.Code] = true
expected, why, allowed := Expected(c, s, l.Code)
switch {
case !allowed:
findings = append(findings, Finding{l.Code, l.BilledCents, 0, why})
case withinTolerance(l.BilledCents, expected):
approvedCents += l.BilledCents
default:
if why == "" {
why = fmt.Sprintf("billed %d cents over the contract amount", l.BilledCents-expected)
}
findings = append(findings, Finding{l.Code, l.BilledCents, expected, why})
approvedCents += expected
}
}
return approvedCents, findings
}
On a 600-mile lane with a $1.20 fuel base, 6 miles per gallon and $3.90 diesel, the expected fuel surcharge is $270, so a $273 line passes on tolerance. Detention billed for 3.5 hours with 2 free hours at $60 an hour is approved at $90 instead of $120, and the liftgate and an unlisted residential charge are disputed. The package uses the min and max builtins, which need Go 1.21 or newer.
Encore is a backend framework with built-in infrastructure, and the audit service declares its Postgres database, a Pub/Sub topic that runs the audit for each new invoice and a cron job for stalled disputes in its own code, and Encore provisions them in your own AWS or GCP account. How Pallet built an event-driven AI logistics platform on GCP without touching Terraform.

Run in your terminal to get started locally.
Contracts, shipment facts, diesel prices and invoices each get a table:
-- audit/migrations/1_audit.up.sql
CREATE TABLE contracts (
carrier_scac TEXT NOT NULL,
lane TEXT NOT NULL, -- for example "CHI-DAL"
linehaul_cents BIGINT NOT NULL,
miles DOUBLE PRECISION NOT NULL,
fuel_base_cents BIGINT NOT NULL,
fuel_mpg DOUBLE PRECISION NOT NULL,
accessorials JSONB NOT NULL DEFAULT '{}',
detention_free DOUBLE PRECISION NOT NULL DEFAULT 2,
detention_cents BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (carrier_scac, lane)
);
CREATE TABLE shipments (
bol_number TEXT PRIMARY KEY,
lane TEXT NOT NULL,
pickup_date DATE NOT NULL,
dock_hours DOUBLE PRECISION NOT NULL DEFAULT 0,
had_liftgate BOOLEAN NOT NULL DEFAULT false
);
CREATE TABLE diesel_prices (
week_of DATE PRIMARY KEY, -- Monday of the published week
price_cents BIGINT NOT NULL
);
CREATE TABLE invoices (
id BIGSERIAL PRIMARY KEY,
carrier_scac TEXT NOT NULL,
invoice_number TEXT NOT NULL,
bol_number TEXT NOT NULL,
billed_cents BIGINT NOT NULL,
approved_cents BIGINT,
status TEXT NOT NULL DEFAULT 'received', -- received, approved, disputed, held
findings JSONB NOT NULL DEFAULT '[]',
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
decided_at TIMESTAMPTZ,
UNIQUE (carrier_scac, invoice_number)
);
-- At most one approved invoice per load, even when two audits run at once.
CREATE UNIQUE INDEX invoices_one_approved_per_bol ON invoices (bol_number) WHERE status = 'approved';
CREATE TABLE invoice_lines (
invoice_id BIGINT NOT NULL REFERENCES invoices(id),
code TEXT NOT NULL,
description TEXT NOT NULL,
billed_cents BIGINT NOT NULL
);
// audit/invoices.go
package audit
import (
"context"
"errors"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("audit", sqldb.DatabaseConfig{Migrations: "./migrations"})
type InvoiceReceived struct {
InvoiceID int64 `json:"invoice_id"`
}
var Received = pubsub.NewTopic[*InvoiceReceived]("invoice-received", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type InvoiceParams struct {
CarrierSCAC string `json:"carrier_scac"`
InvoiceNumber string `json:"invoice_number"`
BOLNumber string `json:"bol_number"`
BilledCents int64 `json:"billed_cents"`
Lines []Line `json:"lines"`
}
type InvoiceResponse struct {
InvoiceID int64 `json:"invoice_id"`
Duplicate bool `json:"duplicate"`
}
// ReceiveInvoice is called by the EDI translator or carrier API integration.
//
//encore:api private method=POST path=/invoices
func ReceiveInvoice(ctx context.Context, p *InvoiceParams) (*InvoiceResponse, error) {
tx, err := db.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
var id int64
err = tx.QueryRow(ctx, `
INSERT INTO invoices (carrier_scac, invoice_number, bol_number, billed_cents)
VALUES ($1, $2, $3, $4)
ON CONFLICT (carrier_scac, invoice_number) DO NOTHING
RETURNING id
`, p.CarrierSCAC, p.InvoiceNumber, p.BOLNumber, p.BilledCents).Scan(&id)
if errors.Is(err, sqldb.ErrNoRows) {
return &InvoiceResponse{Duplicate: true}, nil
} else if err != nil {
return nil, err
}
for _, l := range p.Lines {
if _, err := tx.Exec(ctx, `
INSERT INTO invoice_lines (invoice_id, code, description, billed_cents) VALUES ($1, $2, $3, $4)
`, id, l.Code, l.Description, l.BilledCents); err != nil {
return nil, err
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
if _, err := Received.Publish(ctx, &InvoiceReceived{InvoiceID: id}); err != nil {
return nil, err
}
return &InvoiceResponse{InvoiceID: id}, nil
}
The unique constraint on carrier and invoice number turns a resent 210 into a no-op. A failed publish returns an error, and the carrier integration's retry hits the duplicate path, so an invoice stuck in received is what the escalation job below looks for.
// audit/worker.go
package audit
import (
"context"
"encoding/json"
"errors"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
var _ = pubsub.NewSubscription(Received, "audit-invoice", pubsub.SubscriptionConfig[*InvoiceReceived]{
Handler: auditInvoice,
})
func auditInvoice(ctx context.Context, msg *InvoiceReceived) error {
var carrier, bol, status string
err := db.QueryRow(ctx, `SELECT carrier_scac, bol_number, status FROM invoices WHERE id = $1`,
msg.InvoiceID).Scan(&carrier, &bol, &status)
if err != nil || status != "received" {
return err // nil when already audited on an earlier delivery
}
hold := func(reason string) error {
f, _ := json.Marshal([]Finding{{Reason: reason}})
_, err := db.Exec(ctx, `
UPDATE invoices SET status = 'held', findings = $2, decided_at = now()
WHERE id = $1 AND status = 'received'
`, msg.InvoiceID, f)
return err
}
// A second invoice for a load that was already approved. If two audits race past
// this check, the unique index fails the second approval, and its retry lands here.
var paidElsewhere bool
if err := db.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM invoices WHERE bol_number = $1 AND id <> $2 AND status = 'approved')
`, bol, msg.InvoiceID).Scan(&paidElsewhere); err != nil {
return err
}
if paidElsewhere {
return hold("bill of lading already paid on another invoice")
}
var c Contract
var s Shipment
var acc []byte
err = db.QueryRow(ctx, `
SELECT c.linehaul_cents, c.miles, c.fuel_base_cents, c.fuel_mpg, c.accessorials,
c.detention_free, c.detention_cents, s.dock_hours, s.had_liftgate,
COALESCE(d.price_cents, 0)
FROM shipments s
JOIN contracts c ON c.carrier_scac = $1 AND c.lane = s.lane
LEFT JOIN diesel_prices d ON d.week_of = date_trunc('week', s.pickup_date)::date
WHERE s.bol_number = $2
`, carrier, bol).Scan(&c.LinehaulCents, &c.Miles, &c.FuelBaseCents, &c.FuelMPG, &acc,
&c.DetentionFree, &c.DetentionCents, &s.DockHours, &s.HadLiftgate, &s.DieselCents)
if errors.Is(err, sqldb.ErrNoRows) {
return hold("no shipment or contract found for this bill of lading")
} else if err != nil {
return err
}
if s.DieselCents == 0 {
return hold("no diesel price loaded for the pickup week")
}
if err := json.Unmarshal(acc, &c.Accessorials); err != nil {
return err
}
var lines []Line
rows, err := db.Query(ctx, `SELECT code, description, billed_cents FROM invoice_lines WHERE invoice_id = $1`, msg.InvoiceID)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var l Line
if err := rows.Scan(&l.Code, &l.Description, &l.BilledCents); err != nil {
return err
}
lines = append(lines, l)
}
if err := rows.Err(); err != nil {
return err
}
approved, findings := Audit(c, s, lines)
decision := "approved"
if len(findings) > 0 {
decision = "disputed"
}
f, _ := json.Marshal(findings)
_, err = db.Exec(ctx, `
UPDATE invoices SET status = $2, approved_cents = $3, findings = $4, decided_at = now()
WHERE id = $1 AND status = 'received'
`, msg.InvoiceID, decision, approved, f)
rlog.Info("invoice audited", "invoice_id", msg.InvoiceID, "status", decision, "findings", len(findings))
return err
}
var _ = cron.NewJob("stalled-invoices", cron.JobConfig{
Title: "Escalate stalled and disputed invoices",
Schedule: "0 7 * * 1-5",
Endpoint: EscalateStalled,
})
//encore:api private
func EscalateStalled(ctx context.Context) error {
rows, err := db.Query(ctx, `
SELECT id, carrier_scac, invoice_number, status FROM invoices
WHERE (status = 'received' AND received_at < now() - interval '1 day')
OR (status IN ('disputed', 'held') AND decided_at < now() - interval '14 days')
`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var id int64
var carrier, number, status string
if err := rows.Scan(&id, &carrier, &number, &status); err != nil {
return err
}
rlog.Warn("invoice needs attention", "invoice_id", id, "carrier", carrier, "invoice_number", number, "status", status)
}
return rows.Err()
}
Every status change is conditional on status = 'received', so a redelivered message cannot overwrite a decision. Disputed invoices store the approved amount, which is what accounts payable short-pays while the carrier responds, and the findings JSON is what goes back to the carrier as the dispute reason. Replace the escalation log line with a ticket or a message to the transportation team.
encore run starts Postgres, applies the migration and runs the audit subscription, so loading a contract, a shipment and a diesel price and then posting an invoice shows the findings in the local dashboard trace. The escalation job is an Encore platform Managed cron job that runs in deployed environments, not locally or in preview environments, so call EscalateStalled from the local dashboard to test it.
A coding agent adding a new accessorial rule, for example requiring an appointment record before paying a redelivery charge, adds a case to Expected, a test for it and runs an invoice through locally in one change.
Best fit: Shippers, brokers and 3PLs that want invoice intake, contract checks and disputes in one service in their own AWS or GCP account, next to the shipment events the checks depend on.
Freight audit is checking each carrier invoice against what was agreed and what happened before paying it. The linehaul should match the contracted lane rate, the fuel surcharge should follow the contract formula for that week's diesel price, and each accessorial such as detention or liftgate should be on the contract and backed by an event on the shipment.
The X12 210 is the Motor Carrier Freight Details and Invoice transaction. A carrier sends it to bill a shipment, with the invoice number, the bill of lading or shipment ID, line items for linehaul, fuel and accessorials, and the total due.
Most contracts use a per-mile formula: the weekly diesel price minus a base price already included in the linehaul, divided by an assumed fuel efficiency, times the lane miles. The weekly price usually comes from the US Energy Information Administration on-highway diesel series.
Yes. Encore deploys the audit service, its Postgres database, the audit queue and the escalation cron job to your own AWS or GCP account, next to the shipment data the checks depend on.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.