AgriTech SaaS Backend
A multi-tenant SaaS API for farm records and machine-learning soil analysis from infrared spectra.
The problem
Agricultural cooperatives, agribusinesses and agronomists need one place to record their farms and fields, track crop seasons, log what was done to each crop, and keep soil test results. Each organisation’s data has to stay invisible to every other organisation on the same service.
Soil analysis adds a second problem. Infrared spectrometers do not agree on resolution: one instrument exports 1,500 points per scan and another more than 80,000, while the prediction model accepts exactly 2,380 features. A single upload can also hold hundreds of samples, which is not work to do inside a web request.
This backend handles both. It keeps tenant-isolated farm records behind role-based access, and it runs an asynchronous pipeline that turns raw DRIFTS/FTIR spectra into Soil Organic Matter predictions, with subscription plans that meter how much each organisation can use.
What it does
- Farm, field and crop season records, with activity logs for fertiliser applications, soil tests, weeding and harvest costs.
- Four roles:
OWNER,ORG_ADMIN,AGRONOMISTandVIEWER. Reads need any role, creates and updates need an agronomist or above, deletes need an admin, and viewers see only the farms they own. - Self-service onboarding: creating an organisation makes the creator
OWNERand attaches aFREEsubscription. - Soil spectra uploaded as a JSON array or a CSV file with one row per sample. A batch is one job, predicted in a single vectorised model call, with one Soil Organic Matter value stored per row.
- Every job records the model version that produced it.
- Stripe subscriptions with monthly quotas: 10 predictions on
FREEand 1,000 onPRO. Failed jobs are not counted. - A dashboard endpoint with total and this-month job counts, average Soil Organic Matter and job counts by status.
- A
/healthzendpoint that checks PostgreSQL and Redis and returns 503 if either is down, structured JSON logs, and Sentry for errors in the web process and the worker. - A seeding command built on
bulk_createthat generates users, organisations, farms, fields, seasons, samples and jobs for load testing. - 115 pytest tests at 91% coverage. GitHub Actions runs them against real PostgreSQL 16 and Redis 7, together with ruff and a missing-migrations check.
Architecture
Path of a prediction job
- The client posts spectra to
/api/predict/as a JSON array or a CSV file, over HTTPS with a JWT. - The web process validates the upload and resamples every row to the model’s 2,380 features with SciPy linear interpolation.
- In one transaction it locks the organisation’s subscription row, checks the monthly quota and saves the job as
PENDING. - Once the transaction commits, the job id is queued on Redis.
- A Celery worker loads the job, runs PLSR inference on every row in one call and stores the predicted Soil Organic Matter with the model version.
- The client reads the result from
/api/predict/{id}/. Any other tenant asking for the same id gets a 404.
Decisions and trade-offs
Tenant isolation in the API layer
All tenants share one schema. Each viewset filters its queryset by the caller’s organisation, and a custom serializer field, OrgScopedPrimaryKeyRelatedField, validates every foreign key in a request body against it. A record that belongs to another tenant fails exactly like an id that does not exist, so error responses cannot be used to probe for other tenants’ data.
Trade-off. One schema keeps migrations and operations simple, but isolation depends on every endpoint using the scoped queryset and field. That is why it is covered by tests in the farms, predictions and samples apps instead of trusted.
The organisation is resolved in the view, not in middleware
JWT authentication runs inside DRF, after Django’s middleware has finished, so middleware cannot know which user a token belongs to. Views and permission classes resolve the organisation through one helper that caches it on the request.
Trade-off. There is no single place that sets tenant context before a view runs. The helper is the choke point, and the isolation tests check that every endpoint goes through it.
Resample in the request, infer in the worker
Spectra are parsed and resampled before the job is saved, so a malformed upload is rejected with a 400 straight away instead of failing later in a queue. The standardised matrix is stored on the job row, and the Celery message carries only the job id.
Trade-off. Interpolation costs request time on a large batch, and stored spectra make job rows heavy. Listings paginate and defer the spectra column with .defer('spectra'), which keeps job history under 100 ms.
Linear interpolation onto one fixed grid
Each spectrum is mapped with scipy.interpolate.interp1d onto the model’s grid of 2,380 wavenumbers, from 3999.053 to 600.0723 cm⁻¹, whatever resolution the instrument exported. One model then serves every instrument.
Trade-off. Linear interpolation is cheap and predictable. The cost is an assumption: an upload without wavenumber headers is treated as evenly spaced across the model’s range.
Quota check and job creation in one transaction
The plan check takes a row lock on the organisation’s subscription with SELECT ... FOR UPDATE, and the job is inserted in the same transaction. Two simultaneous uploads cannot both claim the last free slot. The Celery task is queued with transaction.on_commit, so a worker never receives an id for a row that was rolled back or is not visible yet.
Trade-off. Concurrent submissions from one organisation wait on each other for the length of the insert. Resampling runs before the lock is taken to keep that window short.
Failed jobs do not use up quota
Database errors in the worker are retried three times with exponential backoff. Tasks have soft and hard time limits, so a stuck job is marked as failed instead of running forever. Every failed job is saved as FAILED with an error message and flagged as non-billable, so it does not count against the plan.
Trade-off. Usage is counted from job rows on each submission instead of a stored counter. That is one extra query, but there is no counter to drift out of sync.
Stripe webhooks are verified and idempotent
Every webhook is checked against Stripe’s signature before it is trusted. The event id is stored in the same transaction as the plan change it causes, so a retried event is acknowledged and skipped, and a crash can never record an event without applying it. The handler covers checkout.session.completed, customer.subscription.updated and customer.subscription.deleted.
Trade-off. The application’s view of a subscription lags Stripe by the time a webhook takes to arrive. In development a Stripe CLI container forwards test events to the API; in production Stripe calls the HTTPS endpoint registered in its dashboard.
Two production stacks on a 1 GB server
This API and the e-commerce API share one e2-micro instance. Gunicorn runs one worker with two threads, and Celery runs one prefork child, not the solo pool, so task time limits still apply. Instead of its own Redis, this stack uses database 1 of the e-commerce stack’s Redis, which is capped at 64 MB. The trained model is mounted read-only from the server, so a new model is a file swap and a version bump, with no rebuild. Only Caddy’s ports are open to the internet.
Trade-off. Throughput has a low ceiling, and a 2 GB swap file covers startup spikes. The shared Redis couples the two apps: its no-eviction policy means a large backlog makes Redis refuse new tasks instead of silently dropping queued ones.
Known limitations
- The dashboard’s average Soil Organic Matter covers single-sample jobs only. Batch jobs store a list of values per job and are not averaged yet.
- The farm list makes one extra query per farm for its nested fields.
prefetch_related("fields")would fix it. - The prediction list sorts all of an organisation’s jobs to show one page. A composite index on
(organization_id, created_at)would let the first page read only 20 rows. - Load testing with k6 against a production-sized dataset is planned, with before-and-after numbers for one targeted query optimisation.
Tech stack
- API
- Python 3.12, Django 4.2, Django REST Framework, SimpleJWT, drf-spectacular
- Async
- Celery 5.5, Redis 7
- Data
- PostgreSQL 16 (Supabase)
- ML and numerics
- scikit-learn 1.3 (PLSRegression), NumPy, pandas, SciPy, joblib
- Payments
- Stripe Checkout and webhooks
- Infrastructure
- Docker Compose, Gunicorn, Caddy, WhiteNoise, GCP Compute Engine
- Quality and operations
- pytest, pytest-django, model_bakery, coverage, ruff, GitHub Actions, Sentry, JSON logging
Links
Next project E-Commerce Backend