Machine Learning & Full-StackCompleted2024

Crop Recommendation System

Full-stack agricultural decision support platform with a FastAPI ML microservice, scikit-learn Random Forest classifier, and a Node.js backend for farmer expense tracking.

RoleFull-Stack Developer
Timeline2 months
PublishedDecember 2024
Source Code
PythonFastAPIscikit-learnNode.jsExpressMongoDBNext.jsNumPyPandas

A comprehensive full-stack application built for Nepali farmers that combines ML-driven crop recommendations with a financial tracking dashboard. The system is split into three distinct services: a Next.js frontend, a Node.js/MongoDB backend for user accounts and farm expense management, and a Python FastAPI microservice that serves predictions from a trained scikit-learn Random Forest classifier.

Fig 1. Three-Service Architecture — Request Flow
Crop Recommendation System: Next.js Frontend → Node.js Backend (JWT auth, expense CRUD, MongoDB) → FastAPI ML microservice (port via app.py) → Scikit-learn Random Forest (pickle model) → JSON prediction response

How a crop recommendation request flows from the Next.js frontend through the Node.js/Express backend to the Python FastAPI microservice, and how the ML prediction response returns to the client.

What We Set Out to Solve

Nepali farmers often make crop selection decisions based on tradition rather than soil data, leading to suboptimal yields. The goal was to build an accessible tool that translates soil nutrient readings and environmental data into a concrete, ML-backed crop recommendation — alongside financial tracking to help farmers log and review farm expenses.

Architecture Highlights

  • Three-service monorepo: frontend/ (Next.js), backend/ (Node.js + Express + MongoDB), ml-service/ (Python + FastAPI)
  • FastAPI ML microservice with CORS middleware pre-configured for the frontend origins, Pydantic schema validation at the prediction endpoint via PredictionRequest model
  • scikit-learn Random Forest classifier trained on soil nutrient (N, P, K), pH, temperature, humidity, and rainfall features — serialised to disk with pickle for fast loading at inference time
  • Dedicated schema and service layers in the ML service: ml-service/src/schemas/ (Pydantic models) and ml-service/src/services/predictor.py (model loading and prediction logic)
  • JWT-based authentication in the Node.js backend with a MONGO_URI environment variable configured via .env

End-to-End Data Pipeline

Key Engineering Decisions

01

Decoupled FastAPI Microservice for ML Inference

The trained scikit-learn model is served exclusively through a dedicated Python FastAPI service (`ml-service/src/app.py`). The Node.js backend proxies prediction requests to this service rather than embedding Python in the Node.js process.

Rationale: Isolating the Python runtime from Node.js means each service can be scaled, updated, and restarted independently. ML dependencies (scikit-learn, numpy, pandas) remain confined to a single Python environment without polluting the Node.js container.

02

Pydantic Schema Validation at the ML API Boundary

All incoming prediction requests are validated against a `PredictionRequest` Pydantic model in `ml-service/src/schemas/prediction.py` before reaching the prediction logic.

Rationale: Without input validation, invalid sensor readings (e.g. negative NPK values, pH outside the valid range) would silently produce meaningless predictions. FastAPI's Pydantic integration returns clear 422 Unprocessable Entity errors with field-level details when validation fails.

03

Scikit-learn Random Forest with Pickle Serialization

The model is trained offline in a Jupyter notebook (`ml-service/notebook/`) and serialized to `ml-service/saved_models/`. The FastAPI service loads the pickle file on startup via `predictor.py`, avoiding re-training on every request.

Rationale: Loading a pre-trained model once at startup gives consistent sub-millisecond inference latency per request. The notebook → training → pickle → serve pipeline is a standard production-ready ML deployment pattern.

04

MongoDB for User Data, PostgreSQL-free

The Node.js backend stores farmer profiles, authentication tokens, and expense records in MongoDB (configured via MONGO_URI in .env). The ML predictions are stateless and never persisted.

Rationale: Farmer profile data is document-shaped and schema-flexible — different farmers may track different expense categories. MongoDB's document model fits this without requiring schema migrations for every new expense type.

Core Code Pattern

ml-service/src/app.pyPYTHON
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from src.schemas.prediction import PredictionRequest
from src.services.predictor import predict_crop

app = FastAPI(
    title="Crop Recommendation API",
    description="Crop Recommendation System using Machine Learning",
    version="1.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3001", "http://localhost:3000"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/predict")
async def predict(data: PredictionRequest):
    result = predict_crop(data)
    return {"recommended_crop": result}

FastAPI handles request validation through the PredictionRequest Pydantic schema. The predictor service loads the trained scikit-learn model once at startup and returns the top recommended crop for the given soil and environmental inputs.

Technical Challenges & Resolutions

Challenge 1

Serving the ML model efficiently without reloading it on every request

Resolution: The pickle model is loaded once during FastAPI startup using a module-level variable in `predictor.py`. All subsequent requests share the single in-memory model object. This keeps prediction latency consistently low regardless of model size.

Challenge 2

Cross-origin requests between the Next.js frontend and the FastAPI service

Resolution: Added FastAPI's `CORSMiddleware` with explicit `allow_origins` for `localhost:3000` and `localhost:3001`. On the Node.js side, the backend acts as a proxy, keeping the ML service's internal URL hidden from the browser and avoiding CORS issues in production deployments.

Challenge 3

Coordinating three separate services during local development

Resolution: Structured the monorepo with a root `package.json` and concurrently-compatible start scripts so all three services (Next.js, Node.js, uvicorn FastAPI) can be launched together. Each service exposes a different port (3000, 3001, ML port) to avoid conflicts.

Measurable Outcomes

Results based on local benchmarks and integration test runs during development.

  • Supports 22 crop classes across Nitrogen, Phosphorus, Potassium, pH, Temperature, Humidity, and Rainfall feature inputs
  • Sub-100ms ML inference latency per prediction request with the pickle model loaded in memory
  • Both Logistic Regression and Random Forest models trained and evaluated — Random Forest selected for higher validation accuracy

Crop Recommendation System

This case study documents the architecture, engineering decisions, and key challenges for Crop Recommendation System. The full implementation is available in the source repository.