Engineering a Distributed ServerlessE-Commerce Platformfor Modern Agriculture.

An end-to-end e-commerce platform featuring secure Cognito role-based access, fault-tolerant payment flows powered by the Saga pattern, and event-driven architecture for automated notifications.

Next.js
Next.js
Python
Python
FastAPI
FastAPI
AWS
AWS
MySQL
MySQL
Scroll to Explore

Orchestrating a
Serverless Ecosystem.

A unified view of how our Next.js frontends, FastAPI microservices, and AWS infrastructure work together to power a multi-role digital storefront.

01User

The User Portal

High-Performance UX: A Next.js frontend designed for speed, featuring an Amplify-cached catalog, intelligent search, and a seamless Razorpay checkout flow.

02Admin

The Admin Control Center

Master Data Management: A secure, master-access portal allowing the business owner to push instant seasonal homepage updates, manage product lifecycles, and oversee global order fulfillment.

03Delivery

The Delivery Agent Module

Role-Based Logistics: A specialized UI module restricted via Cognito RBAC. It equips delivery personnel with real-time order routing using embedded Google Maps and reverse geocoding (longitude/latitude) for precise drop-offs.

04Cloud

The Cloud Backbone

Distributed & Event-Driven: A highly scalable Python/FastAPI backend executing entirely on AWS Lambda. State is managed via RDS MySQL, with complex asynchronous tasks orchestrated through AWS Step Functions.

Securing the Perimeter:
Multi-Portal Identity & RBAC

Security cannot be a single point of failure. We implemented a federated, Zero-Trust architecture using AWS Cognito to govern identities and access across two entirely distinct web portals.

Dual-Flow Authentication & UI Rendering

To minimize checkout friction, the public User Portal leverages Google SSO via Cognito. Conversely, the internal operations portal enforces strict credential-based logins.

Edge Authentication (The API Layer)

Every REST endpoint is shielded by API Gateway Cognito Authentication. Python Lambdas strictly enforce Role-Based Access Control (RBAC).

Stateful Connection Security

Securing asynchronous communication requires more than standard token checks. We engineered a Custom Lambda Authorizer specifically for WebSockets.

API Gateway

Cognito Authorizer

RBAC Enforced

User Portal

Google SSO

Admin Portal

Credentials

"...so we had to ensure that the Delivery Agents couldn't hit the Admin endpoints."

The 4-Layer
Performance Shield:
Zero-Latency UX.

To make the web platform feel as instantaneous as a native mobile app—while simultaneously protecting our FastAPI backend from redundant database queries—we engineered a sophisticated, 4-tier caching architecture.

Layer 01

Edge Caching (Next.js ISR)

The First Line of Defense: We utilize Next.js Incremental Static Regeneration (revalidate) to cache dynamic product catalogs at the AWS Amplify edge. If 1,000 users search for the same fertilizer, the database is queried exactly once.

Layer 02

In-Memory Mutability (React Query)

Eliminating Network Latency: We integrated React Query (TanStack) to manage data directly in the browser's active memory. Navigating between product details and previously viewed lists results in instant, zero-network-request loads.

Layer 03

Persistent Browser Storage

Bypassing the Server: Heavy, static layout data—such as category trees and global navigation menus—are written directly to LocalStorage. A custom invalidation script ensures the UI instantly loads from the hard drive.

Layer 04

Synchronized Application State

Volatile Session Memory: To prevent component re-renders, highly dynamic data like the shopping cart is held in a centralized React Context. Clicking 'Add to Cart' instantly synchronizes the UI globally without a page refresh.

The Engine Room: Distributed Transactions & The Saga Pattern

Processing payments requires absolute fault tolerance. We architected a zero-trust, event-driven checkout pipeline utilizing AWS Step Functions to guarantee exact-once execution and seamless rollbacks across our microservices.

Zero-Trust PricingDomain-Driven Saga OrchestrationRollbacks & Cold StartsThe VPC Security SplitAsync WebSocket Callbacks

Zero-Trust Pricing

Zero-Trust Payload

To eliminate client-side price manipulation, our frontend payload strictly transmits shipping coordinates and payment preferences. The REST API never trusts client pricing. Instead, it extracts the Cognito Sub from the Authorization header to securely fetch the immutable cart state directly from RDS. To prevent double-charging during network retries, we generate a cryptographic Hash Key from the checkout payload.

Domain-Driven Saga Orchestration

Domain-Driven Step Functions

Because a checkout spans multiple microservices (Orders, Promotions, Payments), a standard synchronous API would risk catastrophic timeouts. We decoupled this into an asynchronous AWS Step Function. The Saga securely routes the payload through strictly isolated GitHub repositories—calculating dynamic product and payment-method discounts before securely handing off to the Payment Service.

Rollbacks & Cold Starts

Two-Phase Compensation

Graceful failure handling is the backbone of our Saga. If any state fails, the Step Function's Catch flow passes the error context to our compensate_handler. Recognizing that the business has lower baseline traffic, we intentionally avoided provisioning separate rollback Lambdas that would suffer from slow 'Cold Starts'. Instead, all failures route to a single, highly-warm Lambda that safely reverts all previous steps.

The VPC Security Split

VPC Isolation

Security and connectivity are handled in distinct network layers. The core Payment Process Lambda executes entirely inside a private VPC with no internet access, ensuring database credentials remain air-gapped. To communicate with Razorpay, the Step Function orchestrates a dedicated External Notification Lambda residing outside the VPC, securely bridging the network gap.

Async WebSocket Callbacks

Real-Time UI Updates

Because the Step Function processes the Saga asynchronously, the frontend cannot wait on an HTTP connection. We engineered a bi-directional WebSocket connection via API Gateway. As the Step Function resolves the Razorpay order ID or finalized offline payment, the backend pushes a real-time success or failure notification directly to the client's connection_id, ensuring a zero-lag user experience.

Spatial Logistics: Precision Routing with Google Maps

Precision Coordinate Capture

Triple-Fallback Logistics: Agricultural addresses can be highly unpredictable. To guarantee exact last-mile routing, we engineered a three-tier location capture UI. Users can leverage Google Places Auto-Suggest, trigger an instant 'Current Location' GPS ping, or manually drag-and-drop a map pin for pinpoint targeting. The frontend seamlessly normalizes these three distinct inputs into strict Longitude/Latitude coordinates for our backend validation engine.

|123 Farm Route, Gujarat

Event-Driven WhatsApp Pipeline:
Bridging the VPC Boundary

To guarantee zero API latency during checkout, we completely decoupled document generation from the main thread. By leveraging AWS S3 Event Notifications, we engineered a highly scalable pipeline to deliver real-time WhatsApp receipts.

PRIVATE_SUBNET
JSON Payloadpayload.json
Offline JSONoffline.json
PDF Invoiceinvoice.pdf
Razorpay WebhookRazorpay Webhook
Admin Portal
Order LambdaOrder Lambda
Payment LambdaPayment Lambda
Receipt ServiceReceipt Service
RDS MySQLRDS MySQL
Amazon S3Amazon S3
Receipt MsgReceipt Msg
WhatsApp API

Instant Confirmation & The Success Trigger

State-Aware Messaging: Communication maps strictly to the order's lifecycle. The heavy PDF receipt pipeline remains dormant until the order definitively reaches a SUCCESS payment state.

The VPC Boundary & PDF Generation

Cost-Optimized Isolation: Our Receipt Lambda lives strictly inside a private VPC to query RDS. To avoid a $30/mo NAT Gateway just to reach WhatsApp, it uploads the PDF to S3.

The Air-Gap Bridge & WhatsApp Dispatch

Crossing the Network Divide: The S3 upload triggers our external Receipt Message Lambda. By reading the phone number from the S3 metadata, it bridges the network gap flawlessly.

The V2 Roadmap:
Voice-Activated AI Agronomist

Bridging the digital literacy gap. To keep serverless costs under $30/month while ensuring absolute safety, we are architecting a custom, highly-constrained RAG pipeline built on robust AI engineering patterns rather than bloated frameworks.

System Telemetry
// Audio Input Translated:
"What do I spray for yellow spots right now?"
// LLM Generated SQL:
SELECT * FROM treatments
WHERE MATCH(symptoms)
AGAINST('yellow spots')
AND season = 'Monsoon';

Schema-First Relational RAG

Schema-First Relational RAG

MySQL FULLTEXT retrieval utilizing strict agricultural seasonality filtering to guarantee deterministic, hallucination-free context. Bypassing expensive Vector DBs entirely.

Voice-to-Intent Pipeline

Voice-to-Intent Pipeline

Translating raw Gujarati audio into normalized, programmatic search inputs via Whisper API.

Agentic Model Routing

Agentic Model Routing

Evaluating query complexity at the retrieval layer to dynamically route between gpt-4o-mini and gpt-4o—protecting the budget without sacrificing intelligence.

Cost-Zero Semantic Caching

Cost-Zero Semantic Caching

Collapsing frequent seasonal queries into cached key-value hits via DynamoDB, bypassing inference costs entirely.

Confidence Floors

Confidence Floors

Programmatic confidence thresholds that refuse low-probability generation, instantly triggering an asynchronous handoff to human agronomists.

Prompt Injection Defenses

Prompt Injection Defenses

Strict XML delimiters and database-level payload restrictions to enforce absolute Data Leak Control.

Automated Red Teaming

Automated Red Teaming

CI/CD adversarial testing to guarantee the agent strictly rejects Out-of-Domain (OOD) non-agricultural requests and prompt leaks.

Perceived Zero-Latency UX

Perceived Zero-Latency UX

Streaming Web UI responses via Server-Sent Events (SSE) to mask backend RAG latency and maintain instant user engagement.

Operational Excellence:
From Code to Cloud

main.tf
deploy.yml
cloudwatch.log
qa_matrix.csv
resource "aws_lambda_function" "checkout_saga" {
function_name = "payment-orchestrator"
role = aws_iam_role.lambda_exec.arn
handler = "main.handler"
runtime = "python3.10"
environment {
variables = {
LOG_LEVEL = "ERROR" # Dynamically adjusted
}
}
}

Zero Console Clicks

Production environments should never be configured by hand. We utilized Terraform for 100% of our Infrastructure as Code (IaC). Every Lambda, DynamoDB table, S3 bucket, and Step Function is version-controlled, reproducible, and deployed strictly via code, eliminating configuration drift.

name: Production Deploy
on:
push:
branches: [ "main" ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Terraform Apply
run: terraform apply -auto-approve

Automated CI/CD

To maintain high engineering velocity, we implemented streamlined GitHub Actions. Our workflows handle the automated packaging of Python dependencies, Next.js build steps, and secure deployments directly to AWS, ensuring clean, repeatable releases.

10:45:12 [INFO] POST /checkout - STATUS 200
10:45:14 [DEBUG] Invoking Step Function
10:45:15 [ERROR] Gateway Timeout - Retrying (1/3)
10:45:17 [WARN] Latency spike in RDS pool
10:45:18 [INFO] Payment Successful.
10:45:19 [INFO] Orchestration Complete.

Proactive Debugging

We instrumented the entire backend with highly granular DEBUG, INFO, WARNING, and ERROR logging. By leveraging AWS CloudWatch and writing custom Log Insights queries, we maintain complete visibility into API health and real-time bottlenecks.

ID, FLOW_NAME, EXPECTED, ACTUAL, STATUS, OWNER
TC-01, Guest Checkout, 200 OK, 200 OK, [PASS], Sapana
TC-02, Out of Bounds, 400 Reject, 400 Reject, [PASS], Sapana
TC-03, Invalid Token, 401 Auth, 500 Err, [FAIL], Backend
TC-04, DB Rollback, Compensate, Reverted, [PASS], DevOps

Lean E2E Testing

Heavy project management tools like Jira often create unnecessary friction for lean teams. We engineered a highly disciplined, multi-sheet Google Drive Test Matrix. It tracks rigorous end-to-end user flows and bug triaging with zero administrative overhead.

MACBOOK PRO

The Engine Room: Meet the Team

S

Sapana

Full-Stack Engineer

SA

Senior Architect

Backend & Systems

FL

Frontend Lead

Next.js & UX Design

Ready to dive deeper into the architecture?