A backend design for filing customs declarations on cross-border shipments: item data with HS codes, validation before filing, asynchronous submission to a broker or customs API, versioned amendments, and alerts for shipments close to their filing deadline.

A customs declaration backend turns a shipment's item data into a filing, sends it to customs or a broker, and tracks the response until the goods can move. The work is mostly in the data: precise descriptions, valid HS codes and values that add up, checked before anything leaves your system.
Deadlines make it a backend problem, since a filing that arrives late holds the shipment, and for EU-bound air cargo the first data set is due before loading.
The Harmonized System gives every product a six-digit code used by more than 200 countries, and destinations extend it, such as the EU's eight-digit Combined Nomenclature. Store the six-digit code and the destination code as separate fields, validate both against a classification table you keep current, and reject descriptions like "gift", "parts" or "samples" before filing. Item values should sum to the invoice value in the declared currency, and net weights to no more than the gross weight.
Deadlines depend on the destination and transport mode, and for the EU, ICS2 requires a complete Entry Summary Declaration before arrival for all goods moving to or through the EU, and for air cargo a minimum data set before the goods are loaded. Store a file_by timestamp per shipment from those rules, and alert well before it, since a broker that queues filings or a rejection that needs a fix both take time.
Filing calls an external API that can be slow, rate-limited or down, so it runs from a queue rather than in the request that marks a shipment ready. Each submission carries an idempotency key built from the declaration ID and version, so a retry after a timeout does not file twice. The response, including the movement reference number in the EU, is stored on the version it answers, and amendments are new versions that reference it.
Encore is a backend framework with built-in infrastructure, so the declarations database, the filing queue, the deadline job and the broker credentials are declared in the Go service that uses them. Deploying provisions Postgres and Pub/Sub in your own AWS or GCP account, and the cron job runs on Encore's managed scheduler.

Run in your terminal to get started locally.
Validation, asynchronous filing with versioned idempotency keys, and deadline alerts:
// customs/customs.go
package customs
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("customs", sqldb.DatabaseConfig{Migrations: "./migrations"})
// Set per environment with: encore secret set --type prod BrokerAPIKey
var secrets struct {
BrokerAPIKey string
}
type Item struct {
Description string
HSCode string // six digits
Quantity int
ValueCents int64
NetGrams int
Origin string // ISO 3166-1 alpha-2
}
type FileRequested struct {
DeclarationID int64
Version int
}
var toFile = pubsub.NewTopic[*FileRequested]("declarations-to-file", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
var hsCode = regexp.MustCompile(`^\d{6}$`)
var vague = map[string]bool{"gift": true, "parts": true, "samples": true, "goods": true}
func validate(items []Item, invoiceCents int64, grossGrams int) error {
var sum int64
var net int
for i, it := range items {
if !hsCode.MatchString(it.HSCode) {
return fmt.Errorf("item %d: HS code must be six digits", i+1)
}
if vague[strings.ToLower(strings.TrimSpace(it.Description))] {
return fmt.Errorf("item %d: description %q is too vague", i+1, it.Description)
}
sum += it.ValueCents
net += it.NetGrams
}
if sum != invoiceCents {
return fmt.Errorf("item values %d do not match invoice %d", sum, invoiceCents)
}
if net > grossGrams {
return fmt.Errorf("net weight %dg exceeds gross weight %dg", net, grossGrams)
}
return nil
}
type SubmitParams struct {
ShipmentID string
Items []Item
InvoiceCents int64
GrossGrams int
}
type SubmitResponse struct {
DeclarationID int64
Version int
}
// Each call creates a new version; earlier versions are never edited.
//
//encore:api private method=POST path=/customs/declarations
func Submit(ctx context.Context, p *SubmitParams) (*SubmitResponse, error) {
if err := validate(p.Items, p.InvoiceCents, p.GrossGrams); err != nil {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: err.Error()}
}
items, _ := json.Marshal(p.Items)
var r SubmitResponse
err := db.QueryRow(ctx, `
WITH d AS (
INSERT INTO declarations (shipment_id) VALUES ($1)
ON CONFLICT (shipment_id) DO UPDATE SET shipment_id = EXCLUDED.shipment_id
RETURNING id
)
INSERT INTO declaration_versions (declaration_id, version, items)
SELECT d.id, COALESCE((SELECT max(version) FROM declaration_versions v WHERE v.declaration_id = d.id), 0) + 1, $2
FROM d
RETURNING declaration_id, version`, p.ShipmentID, items).Scan(&r.DeclarationID, &r.Version)
if err != nil {
return nil, err
}
if _, err := toFile.Publish(ctx, &FileRequested{DeclarationID: r.DeclarationID, Version: r.Version}); err != nil {
return nil, err
}
return &r, nil
}
var _ = pubsub.NewSubscription(toFile, "file-with-broker", pubsub.SubscriptionConfig[*FileRequested]{
Handler: file,
AckDeadline: 2 * time.Minute,
})
func file(ctx context.Context, msg *FileRequested) error {
var items json.RawMessage
var firstRef *string
err := db.QueryRow(ctx, `
SELECT v.items, (SELECT reference FROM declaration_versions f
WHERE f.declaration_id = v.declaration_id AND f.version = 1)
FROM declaration_versions v WHERE v.declaration_id = $1 AND v.version = $2`,
msg.DeclarationID, msg.Version).Scan(&items, &firstRef)
if err != nil {
return err
}
body, _ := json.Marshal(map[string]any{"items": items, "amends": firstRef})
req, _ := http.NewRequestWithContext(ctx, "POST", "https://broker.example.com/v1/declarations", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+secrets.BrokerAPIKey)
req.Header.Set("Content-Type", "application/json")
// Same key on every retry of this version, so the broker files it once.
req.Header.Set("Idempotency-Key", fmt.Sprintf("decl-%d-v%d", msg.DeclarationID, msg.Version))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests {
return fmt.Errorf("broker returned %d", resp.StatusCode) // retried
}
if resp.StatusCode >= 400 {
// A validation rejection: retrying the same data will not help.
_, err := db.Exec(ctx, `
UPDATE declaration_versions SET status = 'rejected', filed_at = now()
WHERE declaration_id = $1 AND version = $2`, msg.DeclarationID, msg.Version)
return err
}
var out struct {
Reference string `json:"reference"`
Status string `json:"status"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return err
}
_, err = db.Exec(ctx, `
UPDATE declaration_versions SET reference = $3, status = $4, filed_at = now()
WHERE declaration_id = $1 AND version = $2`,
msg.DeclarationID, msg.Version, out.Reference, out.Status)
return err
}
type DeadlineResponse struct {
AtRisk int
}
// Shipments due within two hours that have no accepted filing yet.
//
//encore:api private method=POST path=/customs/check-deadlines
func CheckDeadlines(ctx context.Context) (*DeadlineResponse, error) {
rows, err := db.Query(ctx, `
SELECT s.id, s.file_by FROM shipments s
WHERE s.file_by BETWEEN now() AND now() + interval '2 hours'
AND NOT EXISTS (
SELECT 1 FROM declarations d JOIN declaration_versions v ON v.declaration_id = d.id
WHERE d.shipment_id = s.id AND v.status = 'accepted')`)
if err != nil {
return nil, err
}
defer rows.Close()
n := 0
for rows.Next() {
var id string
var fileBy time.Time
if err := rows.Scan(&id, &fileBy); err != nil {
return nil, err
}
rlog.Warn("customs filing at risk", "shipment", id, "file_by", fileBy)
n++
}
return &DeadlineResponse{AtRisk: n}, rows.Err()
}
var _ = cron.NewJob("customs-deadlines", cron.JobConfig{
Title: "Flag shipments close to their customs filing deadline",
Every: 10 * cron.Minute,
Endpoint: CheckDeadlines,
})
-- customs/migrations/1_init.up.sql
CREATE TABLE shipments (
id TEXT PRIMARY KEY,
destination TEXT NOT NULL,
mode TEXT NOT NULL CHECK (mode IN ('air', 'sea', 'road', 'rail')),
file_by TIMESTAMPTZ NOT NULL
);
CREATE TABLE declarations (
id BIGSERIAL PRIMARY KEY,
shipment_id TEXT NOT NULL UNIQUE REFERENCES shipments (id)
);
CREATE TABLE declaration_versions (
declaration_id BIGINT NOT NULL REFERENCES declarations (id),
version INTEGER NOT NULL,
items JSONB NOT NULL,
reference TEXT,
status TEXT,
filed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (declaration_id, version)
);
CREATE INDEX shipments_file_by_idx ON shipments (file_by);
Secret values like BrokerAPIKey are set per environment and are not in the repo or in git, so they never appear in code, per the secrets docs. The databases docs cover migrations, which run on each deploy. Locally, encore run starts Postgres and the topic for this service, and CheckDeadlines can be called by hand, since cron schedules only run in deployed environments.
When an agent adds a destination's rules, it adds the validation and the file_by calculation in the same service and runs the flow locally, and the deploy applies the migration in your account with no separate infrastructure change.
Best fit: Logistics and cross-border shipping teams building declaration filing who want the database, queue, schedule and broker credentials in their own cloud account alongside the filing logic.
file_by time per shipment and alerts before it passes.Per item: a precise goods description, the HS code, quantity, weight, value and currency, and country of origin, plus consignor, consignee and transport details for the shipment. Exact data sets differ by country and by declaration type.
The international Harmonized System code has six digits, and countries extend it for their tariffs, such as the EU's eight-digit Combined Nomenclature and longer national codes, so store the six-digit HS code and the destination code separately.
ICS2 is the EU's Import Control System 2, under which operators must file an Entry Summary Declaration (ENS) for goods moving to or through the EU before arrival, and for air cargo a minimum data set before the goods are loaded.
Treat each change as a new version of the declaration and submit it as an amendment with the reference number from the first filing, keeping every version and response for audit. Never edit a filed version in place.
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.