Delivered remotely for a business based in Perth, Australia. Names withheld by agreement.
Project Overview
Across Western Australia's wheatbelt and pulse corridors, physical commodity trading still leans heavily on telephone brokerage, messaging-group price sheets, and manual spreadsheet reconciliation. Growers storing grain on-farm face opaque bid spreads and slow counterparty settlement, while domestic millers and export accumulators struggle to verify exact protein, screenings, and moisture specs across dispersed silos before committing trucks.
We architected and delivered a farm-to-buyer agricultural marketplace in Perth built on Next.js, NestJS, and PostgreSQL. The platform replaces ad-hoc brokerage threads with structured harvest lot publishing, verified lab assay attachments, real-time bid negotiation, weighbridge docket reconciliation, and auditable milestone escrow settlement.
Market & Settlement Friction
Generic e-commerce cart architectures fail immediately when applied to bulk agricultural commodities:
- Variable quality and grade pricing: Tonnage rarely clears at a flat SKU price; wheat, barley, and lupins trade across moisture, protein, falling-number, and foreign-material grades with explicit dockage tables.
- Partial-load fulfillment: A 400-tonne silo lot clears across multiple road-train dispatches over several days, requiring exact tracking of contracted versus delivered weight.
- Counterparty credit and non-delivery risk: Growers hesitate to load trucks without verified buyer funds, whereas buyers refuse full prepayment before destination weighbridge and sample confirmation.
- High-stakes concurrency: During rapid export price spikes, multiple merchants attempt to lock the same parcel simultaneously, demanding strict inventory isolation.
Architectural Strategy
We structured the system around contract-grade state machines backed by a unified TypeScript monorepo. Next.js handles low-latency marketplace discovery and responsive trading desks, while NestJS orchestrates domain modules—Catalog, Matching, Logistics, Assays, and Ledger—over a single transactional PostgreSQL cluster.
Financial and inventory state never rely on eventual consistency. Every tonnage reservation, weighbridge adjustment, and escrow release commits inside ACID transactions paired with an immutable double-entry ledger, ensuring accounting balances reconcile cleanly down to the cent and kilogram.
Core Capabilities
- Verified Harvest Lot Listings: Growers publish silo location, commodity grade, indicative tonnage, pickup windows, and certified lab analysis sheets with geospatial distance filters for buyers.
- Spot Bids, Counter-Quotes & Forward Contracts: Supports direct acceptance, multi-round counter-pricing, and split-lot allocations with live order-book updates via Redis pub/sub.
- Automated Freight & Weighbridge Manifests: Generates dispatch dockets per truckload, capturing gross, tare, and net weights alongside destination sample results directly against the parent contract.
- Specification Variance & Escrow Engine: Holds buyer funds in protected escrow milestones, releasing funds automatically when delivered grade readings fall within agreed contract tolerances.
- Grower & Buyer Settlement Statements: Produces clean tax invoices, recipient-created invoices, and exportable accounting ledgers per harvest season.
Technical Architecture
Browser requests hit Next.js App Router pages, where public lot catalogs benefit from server rendering and authenticated trading desks communicate over typed REST and WebSocket endpoints exposed by NestJS. Redis accelerates faceted commodity search, distributes live bid-status events across NestJS instances, and powers BullMQ workers for contract PDF generation.
Flow: Next.js Trading Web App → NestJS API & WebSocket Gateway → Redis Pub/Sub & BullMQ → PostgreSQL (Lot Locks & Double-Entry Ledger) → Stripe Connect & EFT Settlement Webhooks
When a buyer locks a quote, NestJS acquires a pessimistic row lock on the target lot in PostgreSQL, verifies active buyer credit or funding hold status, decrements open tonnage, creates a binding contract snapshot, and triggers asynchronous BullMQ jobs to issue signed contract PDFs and notify haulage coordinators.
Technology Stack
| Category | Technology detail |
|---|---|
| Buyer & Seller Web App | Next.js (App Router, SSR/ISR public lot catalogs & authenticated trading desk) |
| Core Trading Backend | NestJS modular monolith with domain-driven trading & settlement modules |
| Primary Transactional DB | PostgreSQL 16 with serializable row locks and double-entry ledger tables |
| End-to-End Type Safety | TypeScript shared monorepo DTOs, OpenAPI contracts, and Zod validators |
| Order Book & Rate Cache | Redis for optimistic bid locks, search facets, and WebSocket pub/sub |
| Escrow & Split Payouts | Stripe Connect & Australian EFT/BECS settlement webhooks |
| Document & Cert Storage | S3 object storage for lab assay PDFs, weighbridge dockets, and NGR records |
| Async Jobs & Notifications | BullMQ (Redis) for contract PDF generation and settlement reminders |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| Simultaneous bids on scarce high-protein lots risk overselling | Enforced pessimistic PostgreSQL row locking during bid acceptance instead of optimistic caching; adds minor write serialization per hot lot while eliminating double-sold contracts completely. |
| Weighbridge delivery weights rarely match exact contracted tonnage | Built agreed contract weight-variance envelopes and pro-rata settlement formulas into NestJS rather than forcing manual contract amendments on every truckload. |
| Rural farm offices often run low-bandwidth satellite or 4G connections | Pre-rendered Next.js listing pages server-side and kept trading payload schemas compact; deferred heavy lab PDF rendering to on-demand signed downloads. |
| Microservice boundaries would complicate atomic escrow and inventory updates | Consolidated trading and ledger logic inside a modular NestJS monolith over one PostgreSQL cluster; simplified ACID compliance while preserving clear module boundaries for future extraction. |
Security & Reliability
B2B commodity settlement requires strict identity, authorization, and audit controls. Every merchant, grower entity, and independent laboratory undergoes KYB verification before gaining contract execution rights. NestJS route guards validate organization membership and role authority—preventing farm dispatch staff from altering settlement bank accounts or approving payouts.
Webhook endpoints receiving payment confirmations validate cryptographic signatures and record idempotency keys in PostgreSQL before mutating ledger balances. All contract amendments, assay uploads, and weighbridge entries write append-only audit records with user attribution and timestamps, protecting both counterparties during grade-dispute reviews.
Performance & Scale
Harvest surges compress months of trading volume into intense post-rain and header-front windows. PostgreSQL partial indexes on active open-tonnage lots and PostGIS distance queries keep buyer search sub-second even across thousands of historical closed contracts.
Redis caches regional port-zone price bands and handles WebSocket fan-out cleanly so live bid updates never hammer primary database connections. BullMQ isolates CPU-intensive PDF rendering and batch settlement digest emails onto background workers, keeping interactive Next.js page transitions and API confirmations responsive.
Operational Outcomes
Moving regional bulk grain transactions onto an integrated Next.js, NestJS, and PostgreSQL platform brought transparency and structure to every step from paddock storage to buyer payment:
- Faster price discovery across regions: Growers see live verifiable demand by port zone and grade without spending hours fielding repetitive broker calls.
- Eliminated allocation errors: Transactional row locks and load-level weighbridge tracking stop accidental double-commitments of on-farm silo tonnage.
- Shorter, dispute-free settlement cycles: Clear contract tolerance math and milestone escrow accounts assure sellers of timely payment while protecting buyers on delivered specifications.
- Audit-ready commercial records: Unified contract PDFs, assay certificates, and double-entry payout logs streamline seasonal tax compliance and supply-chain verification.