Nov 20, 202613 min read

Logistics EDI Backend: 204 Load Tenders, 990 Responses and 214 Status Updates

Design the carrier side of EDI with shippers: receive X12 204 load tenders through an AS2 or SFTP gateway, acknowledge with 997s, answer with 990s, send 214 shipment status updates, and keep control numbers and duplicates straight, then build it in Go with Encore.

Illustration for Logistics EDI Backend: 204 Load Tenders, 990 Responses and 214 Status Updates

Carriers that haul for large shippers get most loads as X12 EDI: a 204 tender, a 990 to accept or decline, then 214 status updates, all with strict partners.

A missing 997 brings a resend and a duplicate load, and a reused control number gets a whole interchange rejected. This guide designs the carrier side so those cases are handled, then builds it in Go with Encore.

The carrier EDI backend at a glance

JobDocumentPattern
Receive tenders204 inGateway posts each interchange to one endpoint
Acknowledge receipt997 outReturned synchronously for every interchange
DuplicatesAnyUnique on sender ID and ISA13
Accept or decline990 outOnly from a pending tender
Changes and cancellations204 with B2A 04 or 01Update the stored tender, ask dispatch again
Status updates214 outAT7 codes from driver and dispatch events
Control numbersAll outboundIncrement per partner in the database
ArchiveAllEvery document unchanged in a private bucket

What is in a 204?

An interchange starts with a fixed-width ISA header, then a GS functional group, then one or more transaction sets between ST and SE. A small tender looks like this:

ISA*00* *00* *ZZ*SHIPPERCO *ZZ*ACMETRUCKING *261120*0830*U*00401*000000123*0*P*>~ GS*SM*SHIPPERCO*ACMETRUCKING*20261120*0830*123*X*004010~ ST*204*0001~ B2**ACMT**LD48213**PP~ B2A*00~ S5*1*LD~ G62*10*20261121~ N1*SH*Shipper Co*93*SHIP01~ S5*2*UL~ G62*68*20261122~ N1*CN*Consignee Inc*93*CONS07~ SE*10*0001~ GE*1*123~ IEA*1*000000123~

B2-04 is the shipment ID you will quote back in every 990 and 214, B2A-01 says whether this is an original (00), a cancellation (01) or a change (04), and each S5 loop is a stop with its G62 dates and N1 parties. The X12 204 reference lists every segment, but the standard is only half the story. Each shipper publishes an implementation guide that narrows it: one carrier's 204 spec uses CU, LD and UL stop reasons, and date qualifiers differ from one shipper to the next, so the parser has to be configurable per partner.

How do the documents reach you?

Large shippers usually send over AS2, the HTTP-based protocol in RFC 4130 with signed and encrypted messages and signed receipts, or drop files on SFTP, or route through a VAN. Each of those carries certificates, partner profiles and polling that have nothing to do with tenders.

Terminate the transport in a gateway, a managed EDI provider or a small self-hosted AS2 or SFTP service, and have it POST each interchange to one HTTP endpoint and accept outbound documents the same way. The application then deals only with X12, and adding a partner on a different transport is gateway configuration.

Acknowledgments and duplicates

Answer every interchange with a 997 that echoes the group control number (AK1) and each transaction set (AK2, AK5). The 997 only says the document arrived and parsed. Dispatch has not decided anything yet.

Partners that miss the 997 resend the whole interchange with the same ISA13. Store interchanges under the sender ID and ISA13, skip tender processing for a repeat and still return a 997, so the partner stops resending.

Control numbers on outbound documents

Every interchange you send needs an ISA13 that the partner has not seen from you before, and partners reject duplicates. Allocate them per partner from a row in the database with an atomic increment rather than from timestamps or an in-memory counter, which repeat after a restart or across instances.

Tenders, changes and the 990

A new tender lands as pending until dispatch accepts or declines it, and the 990's B1 segment carries your SCAC, the shipment ID, the date and A or D. Changes (04) replace the stops and put the tender back to pending, because the load you accepted may not be the load you are now offered. A cancellation (01) closes it. Shippers expect the 990 within a window set in their guide, and an unanswered tender usually goes to the next carrier.

214 status updates

Each status is an AT7 segment with a shipment status code, a reason and a timestamp. The common codes are X3 arrived at pickup, AF departed pickup, X1 arrived at delivery and D1 completed unloading, with NS for normal status, as the X12 AT7 reference lists. Drive them from the same driver app events your own tracking uses, and only for tenders you accepted.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and the EDI service declares its database, a private object storage bucket for the archive and the gateway credentials as secrets in Go, and Encore provisions them in your AWS or GCP account. Quiqup built a scalable logistics platform using the Encore platform to automate 95% of DevOps tasks, and Pallet built an event-driven AI logistics platform on GCP without touching Terraform.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create carrier-edi --example=hello-world$ cd carrier-edi && mkdir -p edi/x12 edi/migrations$ encore secret set --type prod,dev,local,pr GatewayToken$ encore secret set --type prod,dev,local,pr GatewayURL
-- edi/migrations/1_create_tables.up.sql CREATE TABLE interchanges ( sender_id TEXT NOT NULL, -- ISA06 control_number TEXT NOT NULL, -- ISA13 raw_key TEXT NOT NULL, received_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (sender_id, control_number) ); CREATE TABLE tenders ( shipper_id TEXT NOT NULL, -- ISA06 of the shipper shipment_id TEXT NOT NULL, -- B2-04 purpose TEXT NOT NULL, -- B2A-01: 00 original, 01 cancel, 04 change status TEXT NOT NULL DEFAULT 'pending', -- pending | accepted | declined | cancelled stops JSONB NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (shipper_id, shipment_id) ); -- Outbound control numbers must be unique per trading partner. CREATE TABLE control_numbers ( partner_id TEXT PRIMARY KEY, last_used BIGINT NOT NULL );

Reading and writing X12

The x12 package reads the delimiters from the ISA header, splits transaction sets and builds envelopes with a padded ISA and correct SE counts. It is plain Go with its own tests that run under go test ./edi/x12:

// edi/x12/x12.go: just enough X12 to read 204s and write 997, 990 and 214. package x12 import ( "errors" "fmt" "strings" "time" ) type Interchange struct { SenderID string // ISA06, trimmed ReceiverID string // ISA08, trimmed ControlNumber string // ISA13 Segments [][]string // every segment, split into elements } // Parse reads the delimiters from the fixed-width ISA segment: the element // separator is character 4 and the segment terminator follows ISA16. func Parse(raw string) (*Interchange, error) { raw = strings.TrimLeft(raw, " \r\n") if len(raw) < 106 || !strings.HasPrefix(raw, "ISA") { return nil, errors.New("not an X12 interchange") } elem, term := string(raw[3]), string(raw[105]) ic := &Interchange{} for _, s := range strings.Split(raw, term) { s = strings.Trim(s, "\r\n ") if s != "" { ic.Segments = append(ic.Segments, strings.Split(s, elem)) } } isa := ic.Segments[0] if len(isa) < 17 { return nil, errors.New("short ISA segment") } ic.SenderID = strings.TrimSpace(isa[6]) ic.ReceiverID = strings.TrimSpace(isa[8]) ic.ControlNumber = isa[13] return ic, nil } // TransactionSets returns the segments between each ST and SE, inclusive. func (ic *Interchange) TransactionSets(id string) [][][]string { var out [][][]string var cur [][]string for _, seg := range ic.Segments { switch { case seg[0] == "ST" && len(seg) > 1 && seg[1] == id: cur = [][]string{seg} case cur != nil && seg[0] == "SE": out = append(out, append(cur, seg)) cur = nil case cur != nil: cur = append(cur, seg) } } return out } // GroupControl returns GS01 and GS06 of the first functional group. func (ic *Interchange) GroupControl() (code, number string) { for _, seg := range ic.Segments { if seg[0] == "GS" && len(seg) > 6 { return seg[1], seg[6] } } return "", "" } // Wrap puts transaction set bodies (segments without ST/SE) into one // interchange with one functional group, using ctrl for ISA13, GS06 and ST02. func Wrap(from, to, gsCode, setID string, ctrl int64, bodies [][]string, now time.Time) string { n := fmt.Sprintf("%09d", ctrl) segs := []string{ fmt.Sprintf("ISA*00*%-10s*00*%-10s*ZZ*%-15s*ZZ*%-15s*%s*%s*U*00401*%s*0*P*>", "", "", from, to, now.Format("060102"), now.Format("1504"), n), fmt.Sprintf("GS*%s*%s*%s*%s*%s*%d*X*004010", gsCode, from, to, now.Format("20060102"), now.Format("1504"), ctrl), } for i, body := range bodies { st := fmt.Sprintf("%04d", i+1) segs = append(segs, "ST*"+setID+"*"+st) segs = append(segs, body...) segs = append(segs, fmt.Sprintf("SE*%d*%s", len(body)+2, st)) } segs = append(segs, fmt.Sprintf("GE*%d*%d", len(bodies), ctrl), "IEA*1*"+n) return strings.Join(segs, "~\n") + "~\n" }

The EDI service

The raw endpoint archives, deduplicates and acknowledges inbound interchanges. Respond and ReportStatus are called by your dispatch tools and driver app, and they need an auth handler in the app because they are declared with auth:

// edi/edi.go package edi import ( "context" "crypto/subtle" "encoding/json" "fmt" "io" "net/http" "strings" "time" "encore.app/edi/x12" "encore.dev/beta/errs" "encore.dev/rlog" "encore.dev/storage/objects" "encore.dev/storage/sqldb" ) const ourID, ourSCAC = "ACMETRUCKING", "ACMT" var secrets struct { GatewayToken string // shared with the AS2/SFTP gateway in both directions GatewayURL string // where outbound documents are posted } var db = sqldb.NewDatabase("edi", sqldb.DatabaseConfig{Migrations: "./migrations"}) // Every inbound and outbound document, unchanged. Private bucket. var Archive = objects.NewBucket("edi-archive", objects.BucketConfig{}) type Stop struct { Seq string `json:"seq"` // S5-01 Reason string `json:"reason"` // S5-02: LD load, UL unload Date string `json:"date"` // first G62-02 in the stop loop Party string `json:"party"` // N1-02 } // Receive takes one interchange from the gateway and returns a 997. // //encore:api public raw method=POST path=/edi/inbound func Receive(w http.ResponseWriter, req *http.Request) { got := []byte(req.Header.Get("Authorization")) if subtle.ConstantTimeCompare(got, []byte("Bearer "+secrets.GatewayToken)) != 1 { http.Error(w, "unauthorized", http.StatusUnauthorized) return } body, err := io.ReadAll(io.LimitReader(req.Body, 5<<20)) if err != nil { http.Error(w, "read error", http.StatusBadRequest) return } ic, err := x12.Parse(string(body)) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } ctx := req.Context() key := fmt.Sprintf("inbound/%s/%s.edi", ic.SenderID, ic.ControlNumber) if err := archive(ctx, key, body); err != nil { http.Error(w, "storage error", http.StatusServiceUnavailable) return } // A partner that resends an interchange reuses its ISA13. res, err := db.Exec(ctx, `INSERT INTO interchanges (sender_id, control_number, raw_key) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, ic.SenderID, ic.ControlNumber, key) if err != nil { http.Error(w, "db error", http.StatusServiceUnavailable) return } sets := ic.TransactionSets("204") if res.RowsAffected() == 1 { for _, set := range sets { if err := saveTender(ctx, ic.SenderID, set); err != nil { rlog.Error("saving tender", "sender", ic.SenderID, "isa13", ic.ControlNumber, "err", err) http.Error(w, "db error", http.StatusServiceUnavailable) return } } } // 997: acknowledge the group and each transaction set. gsCode, gsNum := ic.GroupControl() ack := []string{"AK1*" + gsCode + "*" + gsNum} for _, set := range sets { ack = append(ack, "AK2*204*"+set[0][2], "AK5*A") } ack = append(ack, fmt.Sprintf("AK9*A*%d*%d*%d", len(sets), len(sets), len(sets))) doc, err := wrap(ctx, ic.SenderID, "FA", "997", [][]string{ack}) if err != nil { http.Error(w, "db error", http.StatusServiceUnavailable) return } _ = archive(ctx, fmt.Sprintf("outbound/%s/997-%s.edi", ic.SenderID, ic.ControlNumber), []byte(doc)) io.WriteString(w, doc) } func saveTender(ctx context.Context, shipper string, set [][]string) error { var shipmentID, purpose string var stops []Stop for _, seg := range set { switch { case seg[0] == "B2" && len(seg) > 4: shipmentID = seg[4] case seg[0] == "B2A" && len(seg) > 1: purpose = seg[1] case seg[0] == "S5" && len(seg) > 2: stops = append(stops, Stop{Seq: seg[1], Reason: seg[2]}) case seg[0] == "G62" && len(seg) > 2 && len(stops) > 0 && stops[len(stops)-1].Date == "": stops[len(stops)-1].Date = seg[2] case seg[0] == "N1" && len(seg) > 2 && len(stops) > 0: stops[len(stops)-1].Party = seg[2] } } if shipmentID == "" { return fmt.Errorf("204 without B2-04") } status := "pending" if purpose == "01" { status = "cancelled" } stopsJSON, _ := json.Marshal(stops) // A change (04) replaces the stops and asks dispatch to respond again. _, err := db.Exec(ctx, ` INSERT INTO tenders (shipper_id, shipment_id, purpose, status, stops) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (shipper_id, shipment_id) DO UPDATE SET purpose = EXCLUDED.purpose, status = EXCLUDED.status, stops = EXCLUDED.stops, updated_at = now()`, shipper, shipmentID, purpose, status, stopsJSON) return err } type RespondParams struct { Accept bool `json:"accept"` } // Respond records dispatch's decision and sends the 990. // //encore:api auth method=POST path=/tenders/:shipper/:shipment/respond func Respond(ctx context.Context, shipper, shipment string, p *RespondParams) error { status, code := "declined", "D" if p.Accept { status, code = "accepted", "A" } res, err := db.Exec(ctx, `UPDATE tenders SET status = $3, updated_at = now() WHERE shipper_id = $1 AND shipment_id = $2 AND status = 'pending'`, shipper, shipment, status) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.FailedPrecondition, Message: "tender is not pending"} } b1 := fmt.Sprintf("B1*%s*%s*%s*%s", ourSCAC, shipment, time.Now().UTC().Format("20060102"), code) return send(ctx, shipper, "GF", "990", shipment, []string{b1}) } type StatusParams struct { Code string `json:"code"` // AT7-01, e.g. X3 arrived at pickup, AF departed, X1 arrived, D1 delivered At time.Time `json:"at"` } // ReportStatus sends a 214 shipment status for an accepted tender. // //encore:api auth method=POST path=/tenders/:shipper/:shipment/status func ReportStatus(ctx context.Context, shipper, shipment string, p *StatusParams) error { var status string if err := db.QueryRow(ctx, `SELECT status FROM tenders WHERE shipper_id = $1 AND shipment_id = $2`, shipper, shipment).Scan(&status); err != nil { return &errs.Error{Code: errs.NotFound, Message: "unknown tender"} } if status != "accepted" { return &errs.Error{Code: errs.FailedPrecondition, Message: "tender is not accepted"} } at := p.At.UTC() body := []string{ fmt.Sprintf("B10*%s*%s*%s", shipment, shipment, ourSCAC), "LX*1", fmt.Sprintf("AT7*%s*NS***%s*%s*UT", p.Code, at.Format("20060102"), at.Format("1504")), } return send(ctx, shipper, "QM", "214", shipment+"-"+p.Code, body) } func send(ctx context.Context, partner, gsCode, setID, name string, body []string) error { doc, err := wrap(ctx, partner, gsCode, setID, [][]string{body}) if err != nil { return err } if err := archive(ctx, fmt.Sprintf("outbound/%s/%s-%s.edi", partner, setID, name), []byte(doc)); err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, secrets.GatewayURL+"?partner="+partner, strings.NewReader(doc)) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+secrets.GatewayToken) resp, err := http.DefaultClient.Do(req) if err != nil { return &errs.Error{Code: errs.Unavailable, Message: "gateway unreachable"} } defer resp.Body.Close() if resp.StatusCode >= 300 { return &errs.Error{Code: errs.Unavailable, Message: fmt.Sprintf("gateway returned %d", resp.StatusCode)} } return nil } // wrap allocates the next control number for the partner and builds the envelope. func wrap(ctx context.Context, partner, gsCode, setID string, bodies [][]string) (string, error) { var ctrl int64 err := db.QueryRow(ctx, ` INSERT INTO control_numbers (partner_id, last_used) VALUES ($1, 1) ON CONFLICT (partner_id) DO UPDATE SET last_used = control_numbers.last_used + 1 RETURNING last_used`, partner).Scan(&ctrl) if err != nil { return "", err } return x12.Wrap(ourID, partner, gsCode, setID, ctrl, bodies, time.Now().UTC()), nil } func archive(ctx context.Context, key string, data []byte) error { w := Archive.Upload(ctx, key) if _, err := w.Write(data); err != nil { w.Abort(err) return err } return w.Close() }

encore run starts a local Postgres and bucket, so you can POST the sample 204 with the token and get a 997 back. On deploy, the database runs on RDS or Cloud SQL and the archive on S3 or Cloud Storage, and Encore provisions an IAM role for the service.

A coding agent onboarding a new shipper adds their qualifiers and a test with their sample file, runs it locally in the same change, and has no gateway, bucket or database to set up first.

How would you build it by hand?

The hand-built version uses the same gateway and the same X12 code, deployed to ECS or Cloud Run, with a managed Postgres database, a private bucket with a policy for the service, the gateway token in a secrets manager, and the networking and IAM between them in Terraform. Nothing in the EDI logic changes. The extra work is the infrastructure definitions, and keeping them right as you add partners and environments.

Things to decide early

  • Partner configuration. Keep qualifiers, stop reason codes and response windows per partner in data, not in code branches.
  • Reprocessing. With every document archived, decide how you replay a partner's interchanges after a parser fix.
  • Monitoring. Alert on tenders still pending near their response window and on interchanges that fail to parse.
  • Testing. Ask each partner for sample files and turn them into tests before go-live.

Frequently asked questions

What are EDI 204, 990 and 214?

They are the X12 transaction sets for truckload tenders. The shipper sends a 204 Motor Carrier Load Tender offering a load, the carrier answers with a 990 Response to a Load Tender to accept or decline it, and then reports progress with 214 Shipment Status Messages such as arrived at pickup, departed and delivered.

What is the difference between a 997 and a 990?

A 997 Functional Acknowledgment only confirms that the interchange was received and is syntactically valid. A 990 is a business answer to the tender, accept or decline. Shippers usually expect the 997 within minutes and the 990 within the response window in their implementation guide.

How do you avoid processing an EDI 204 twice?

Partners resend whole interchanges with the same ISA13 control number when they do not get a 997. Store each interchange under the sender ID and ISA13 and skip the business processing for a repeat, while still answering with a 997.

How do you build an EDI backend with Encore?

With Encore, declare the database, a private archive bucket and the gateway secrets in Go next to the handlers. A raw endpoint receives interchanges from the AS2 or SFTP gateway, ordinary endpoints send 990s and 214s, and deploys provision the database and bucket in your own AWS or GCP account.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders