HomeCase studiesB2B Agricultural Commodity Marketplace with Next.js, NestJS,...

Case study · Perth, Australia

B2B Agricultural Commodity Marketplace with Next.js, NestJS, and Transactional PostgreSQL Settlement

Farm-to-Buyer Commodity Trading

Broadacre growers and regional commodity buyers traditionally clear grain, hay, and pulse contracts through fragmented broker phone calls, delayed email spreadsheets, and manual weighbridge reconciliation. We engineered a B2B agricultural marketplace in Perth using Next.js, NestJS, and PostgreSQL to digitize harvest lot listings, laboratory grade verification, contract matching, and milestone-based escrow settlement. Growers publish verified tonnage with moisture and protein certificates, while buyers lock transparent forward or spot contracts backed by automated freight dispatch and double-entry ledger accounting.

Industry
Farm-to-Buyer Commodity Trading
Solution
A Next.js B2B trading web application and modular NestJS/PostgreSQL transactional platform managing verified crop lot listings, bid matching, freight manifests, and escrow payouts.
Platforms
Web & API
Stack
Next.js · NestJS · PostgreSQL · TypeScript · Redis · Stripe Connect
Location
Perth, Australia · delivered remotely
Role
Engineering, with the team behind for mobile and QA

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.

01 — Questions

asked about this kind of project

How does PostgreSQL prevent double-allocation when multiple buyers bid on the last remaining tonnage of a harvest lot?

Bid acceptance and partial-tonnage allocation execute inside PostgreSQL transactions using SELECT ... FOR UPDATE row locks on the parent lot inventory record. If two buyers submit concurrent acceptance requests, one transaction commits and decrements available metric tonnes while the second receives an immediate capacity-changed conflict.

How are commodity quality disputes handled when delivered truckloads differ from the listed moisture or protein grade?

Each contract binds explicit tolerance bands and price-adjustment schedules derived from official laboratory assay certificates uploaded at listing time. Upon weighbridge delivery, destination test metrics post against the contract record; within-band variances auto-compute pro-rata settlement adjustments, while out-of-spec loads pause payout release into an arbitration workflow.

Why choose a NestJS modular monolith over microservices for an agricultural marketplace?

Lot inventory, contract pricing, weighbridge reconciliation, and escrow accounting share tight transactional boundaries. A modular NestJS architecture keeps domain modules cleanly decoupled via internal interfaces while retaining single-database ACID guarantees across order acceptance and ledger posting.

How does Next.js optimize performance for regional growers browsing over slow rural broadband?

Public commodity boards render server-side with Next.js App Router and aggressive edge caching, keeping initial payloads lean. Interactive trading filters debounce server queries cleanly, and heavy PDF contract previews load lazily only when a user opens settlement details.

How do you guarantee financial accuracy across split payouts between growers, hauliers, and platform fees?

Every movement of funds is modeled in an append-only double-entry PostgreSQL ledger storing integer cents alongside external payment-gateway references. Webhook handlers are idempotent on provider event IDs so duplicate network callbacks can never double-credit an account.

What identity checks prevent fraudulent crop listings or phantom buyer bids?

Growers and merchants verify business tax identifiers, farm accreditation numbers, and bank ownership during onboarding before trading privileges unlock. High-value spot bids require verified funding holds or pre-approved buyer credit limits enforced in NestJS guards.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.