Inspiration

I raise broilers and catfish myself. I've lost birds to heat stress overnight, run out of feed mid-cycle because I miscounted bags and consumption rates, and watched mortality creep up because I was tracking things across scattered paper notes, WhatsApp groups, the notes app, and memory. Every smallholder farmer I know faces the exact same chaos. Nigeria's poultry sector alone loses an estimated 15–20% of broiler production to preventable causes every year — roughly ₦600 billion ($750M) in dead birds.

I built FarmOps because I needed it. The operations tool I wanted didn't exist. I wanted something that tracks feed, mortality, financials, and batches with the rigor of enterprise software, but designed for a farmer standing in a poultry house at 7am.

Before building FarmOps, I was already relying on AI for daily farm decisions, but the workflow was hectic and fragmented. I had to type out the same background context over and over again; batch age, feed types, current stock, past mortality. I realized: why not build a dedicated farm platform where the AI already has full, secure database context for every query?

So I layered an AI assistant directly on top of the farm database — one that watches the farm, drafts corrective actions, and never touches financial records without explicit confirmation. And critically: if you turn the AI off (though you honestly wouldn't want to), the core farm operations platform still works perfectly. The AI is an enhancement, not a dependency.

What it does

FarmOps is a multi-tenant B2B SaaS farm operations platform with a credit-metered AI layer for Nigerian poultry and catfish farms. Two things make it different:

First, it's a complete farm operations platform that works without AI. Farm management software exists, but existing tools are built for enterprise-scale operations, specialized to a single niche, and too complex for smallholder farmers. FarmOps covers units, feed inventory, money (sales, expenses, profit), mortality tracking, batch lifecycle, and team management with RBAC roles — all pure database CRUD, all functional the moment you sign up, all designed for a farmer standing in a poultry house at 7am. No AI credits required. No AI dependency. And none of the existing tools have schema-enforced AI safety.

Second, the AI layer is governed, metered, and fully controllable.

  • Today Dashboard — Real-time KPIs, proactive risk flags, feed runway alerts, and AI-generated daily insights.
  • AI Assistant — Ask questions, log records via voice or text, and get contextual recommendations. Uses agentic tool calling to query live database records and drafts action cards for confirmation.
  • Autonomy Safety Floor — Configurable per-farm autonomy tiers (suggestdraftauto). Financial mutations and destructive writes are hardcoded to require human confirmation regardless of settings.
  • Credit Metering & B2B Monetization — Integrated with Nomba payments (Naira gateway) supporting tiered subscriptions (Free / Growth / Pro). Append-only credit ledger with atomic reservation/settlement — no race conditions under concurrent AI load.
  • Multi-Tenant SaaS Isolation — Every database record and vector embedding is strictly farm_id-scoped. Tenant isolation is enforced at the schema level, not just in application logic.
  • Bidirectional Voice Mode — Real-time, hands-free operation in the poultry house powered by Amazon Bedrock Nova Sonic via a low-latency WebSocket bridge.
  • Platform Admin Console — 15+ page staff panel for monitoring AI runs, credit usage, customer management, and feature flags. Three-layer AI kill switch: global master toggle, per-feature flags (8 individual AI capabilities), and per-farm freeze — all propagated to Vercel Edge Config for sub-1ms global enforcement.

How I built it

Database-First Foundation (Amazon Aurora Serverless v2). I built the system on a 48-table schema in Amazon Aurora PostgreSQL 17 with pgvector. The database enforces reliability and performance through CHECK constraints, FOR UPDATE row locks on credit balances, composite and partial indexes tuned to actual access patterns (unit detail pages, mortality aggregations, feed charts, task priority queues), and isolated vector search with HNSW indexes for per-farm RAG. The application is a thin layer over schema-enforced invariants.

Two Required IAM Roles via Vercel OIDC, plus Optional Storage:

  • AWS_ROLE_ARN (access-farmhandops) — DB access only via RDS IAM auth, permission-boundary-capped
  • BEDROCK_ROLE_ARN (farmops-bedrock) — AI access only (Nova 2 Lite, Nova Sonic, Nova MM Embeddings)
  • Vercel Blob as primary file storage (zero-config, no AWS credentials). Optional STORAGE_S3_ROLE_ARN for S3 fallback when cross-region backup is needed.

Zero static AWS credentials exist anywhere in the project architecture.

AI Governance as a Database Primitive. Every agentic execution creates an auditable ai_runs row. Every recommendation writes to an assistant_drafts state machine (pendingconfirmed | discarded). Every credit mutation writes to an append-only credit_ledger using integer minor units (kobo) to prevent floating-point drift. Code evals run on raw model outputs to catch safety failures.

Three-Layer AI Kill Switch. Before every model invocation, aiPreflight checks (1) a global master flag, (2) per-feature flags for 8 distinct AI capabilities (insight, recommendations, assistant, drafts, RAG, voice, vision, OCR), and (3) a per-farm freeze column. If any layer blocks, the AI call throws and the farm operations platform continues normally — no degradation to the core product.

Proactive Intelligence Layer:

  • Growth velocity checks (vs species benchmarks)
  • FCR trend analysis (recent vs prior periods)
  • Seasonal awareness (Harmattan, rainy season prep actions)
  • Multi-batch comparison (flags mortality divergence)
  • Cross-session memory (continuity between conversations)
  • Local terminology resolver ("the big pond", "starter feed", "smoke them")

Frontend & Design. The UI concepts were prototyped with Vercel v0 and then transitioned into a production Next.js 16 App Router codebase powered by AWS Kiro agentic steering (.kiro custom skills, quality hooks, and architectural specs). Mobile-first responsive design — every page renders cleanly from 390px (phone in a poultry house) to 1512px (desktop). Full light and dark theme support. The front-end is designed in direct relation to the back-end: each KPI card maps to a live parameterized query, each feed runway chart to a time-series aggregate, each mortality curve to a windowed SUM over farm_events, and each AI draft card to a schema-enforced state machine row in assistant_drafts. Production design system built on Tailwind CSS v4 and shadcn/ui.

Stack: Vercel v0 (prototyping) · AWS Kiro (agentic orchestration & steering) · Next.js 16 App Router (with Next.js 16 'use cache') · TypeScript · Tailwind CSS v4 + shadcn/ui · Auth.js v5 · Amazon Aurora PostgreSQL 17 (Serverless v2 + pgvector) · Amazon Bedrock (Nova 2 Lite, Sonic, MM Embeddings) · Nomba payments · Vercel (streaming, cron, OIDC, Analytics, Edge Config, Blob, KV/Upstash)

Challenges I ran into

  1. Storage Within the Keyless Boundary. The Vercel OIDC DB role is permission-boundary-capped to RDS-only actions — it cannot touch S3 or other AWS services. Rather than maintain a third IAM role just for file uploads, I adopted Vercel Blob as the primary storage provider — zero-config, no credentials, native to the deployment platform. S3 remains available as an optional fallback via a dedicated STORAGE_S3_ROLE_ARN for farms that need cross-region media backup, auto-selected when BLOB_READ_WRITE_TOKEN is absent.

  2. Credit Race Conditions in Multi-Tenant SaaS. Two concurrent AI requests could both observe balance = 1 and both proceed. I solved this with an atomic conditional UPDATE (SET balance = balance - 1 WHERE balance > 0 RETURNING balance) with Postgres FOR UPDATE row locks — serializing execution at the database layer.

  3. Clinical Safety in Streaming. You can't filter a token-by-token stream without buffering the full response (breaking UX responsiveness). I made system prompts the primary guard, implemented post-execution code evals on raw output, and constrained state mutations to human-confirmed draft blocks. Documented as an ADR with an escalation trigger if eval failure rates exceed 5%.

  4. Voice Streaming over Serverless Timeouts (The EC2 WebSocket Bridge). Vercel serverless functions cap execution at 300 seconds, making long-running bidirectional audio sessions impossible over standard serverless HTTP. I architected a standalone Node 22 WebSocket bridge (services/sonic-bridge) hosted on an Amazon Linux t4g.small EC2 instance in us-east-1 exposed safely via Cloudflare Tunnel. The browser connects over WebSocket; the bridge maintains the persistent HTTP/2 Bedrock Nova Sonic session with continuous silence frames to prevent Bedrock 532 idle timeouts.

  5. Model Hallucination of Market Prices. Nova confidently invents ₦/kg prices that don't exist in the farm's database. I added explicit anti-hallucination constraints: NEVER cite external sources, NEVER provide prices unless present in farm records, and prefer "I don't have data on that" over plausible guessing.

Accomplishments that I'm proud of

  • 1,629+ Tests Passing (79 unit test files + 28 integration test files running against a real pgvector Docker service in CI).
  • The platform works without AI. Every core farm operation — units, feed, money, mortality, team management — runs on pure database CRUD. The AI is an enhancement layer, not a dependency. Turn it off and the farmer still has a full operations platform.
  • Mobile-first, production-grade design. Prototyped with Vercel v0, refined into a cohesive design system where every UI component mirrors a database entity — KPI cards map to live queries, charts to time-series aggregates, draft cards to schema-enforced state machines. Responsive from 390px mobile to 1512px desktop with full dark/light theme support.
  • Zero Static AWS Credentials — 100% keyless infrastructure via Vercel OIDC and RDS IAM authentication.
  • Auditable AI Governance Trail — Public judge-facing /admin/evidence dashboard proves live Aurora pool stats, table counts, and real-time AI Converse run histories without requiring a login.
  • Race-Condition-Proof Credit Metering — Bank-grade integer ledger verified under concurrent load integration tests.
  • Three-Layer Kill Switch — Platform staff can disable AI globally, per-feature, or per-farm in under 1ms via Edge Config. The farm operations platform continues without interruption.
  • Multilingual Native AI — The assistant speaks Hausa, Yoruba, Igbo, and Pidgin with multilingual safety lexicons catching local-language drug names.
  • Proactive Intelligence — Autonomous risk detection flags growth anomalies and feed critical states before the farmer asks.

What I learned

  • Schema-First Thinking Beats Application Hacks. When non-negative balances, tenant isolation, and audit trails are enforced at the database layer (Aurora Postgres), application code remains simple, clean, and resilient to edge cases.
  • AI Should Be a Layer, Not the Product. Building the farm operations platform first and the AI second meant I never compromised the core CRUD reliability. The AI enhances — it doesn't gatekeep. A farmer with zero credits still gets full farm management.
  • Keyless OIDC is the Enterprise Gold Standard. Ephemeral credentials eliminate secret rotation overhead, leak risks, and environment setup friction across Vercel and AWS.
  • AI Governance is a B2B Competitive Moat. The draft-confirmation loop, immutable credit ledgers, and database audit trails transform unpredictable AI into a trustworthy enterprise SaaS operations tool.
  • Domain Realism Shapes Technical Architecture. Designing for a farmer standing in a poultry house at 7am with dirty hands forces you to eliminate unnecessary UI clicks, prioritize voice interaction, and automate RAG context so the user never has to manually re-type farm state. Real-world physical constraints drive better software design.

What's next for FarmOps

  • Verified Livestock & Input Marketplace — Connecting farmers directly to verified feed mills, hatcheries, and commercial off-takers. Wholesale buyers can purchase livestock backed by immutable, auditable production records (FCR, mortality curves, vaccination compliance) directly from the farm's database trail.

  • Agricultural Credit Passport — Exporting bank-grade, time-series production integrity reports to help smallholders access microfinance loans and working capital based on verified historical yields rather than physical collateral.

  • Veterinary Tele-Consulting & Health Watchdog — Structured clinical handoffs derived from AI mortality, symptom, and water quality logs, allowing licensed veterinarians to conduct remote consultations and issue digital prescriptions safely.

  • Offline-First PWA Synchronization — Service worker background sync queues allowing farm workers inside insulated metal poultry sheds or remote riverine ponds to log operational data without cellular coverage.

  • Continuous AI Refinement & Multi-Modal Enhancements — Adapting local languages with lexicons across Hausa, Yoruba, Igbo, and Pidgin, alongside multi-modal vision model integration for automated fish biomass sizing and poultry lesion analysis.

  • Explore Marketplace, Extension, Supplier, Vet, Buyer additions -- Explore turning the platform into an Ecosystem for all involved with Livestock in Nigeria first, then neighboring countries.

  • Whatsapp Integration-- Deeply integrate Whatsapp into FarmOps to allow farmers to interact with the assistant, log activities and get info through Whatsapp without needing to login to the platform.


Built for the H0: Hack the Zero Stack hackathon (#H0Hackathon) in Track 2 (Monetizable B2B App). Amazon Aurora PostgreSQL and Amazon Bedrock form the core backend; deployed on Vercel.

Built With

Share this project:

Updates