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.
Orchestrating aServerless Ecosystem.
A unified view of how our Next.js frontends, FastAPI microservices, and AWS infrastructure work together to power a multi-role digital storefront.
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.
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.
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.
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 EnforcedUser Portal
Google SSOAdmin Portal
Credentials"...so we had to ensure that the Delivery Agents couldn't hit the Admin endpoints."
The 4-LayerPerformance 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.
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.
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.
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.
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 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.
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.
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.
WHERE MATCH(symptoms)
AGAINST('yellow spots')
Operational Excellence:
From Code to Cloud
The Engine Room: Meet the Team
Sapana
Full-Stack Engineer
Senior Architect
Backend & Systems
Frontend Lead
Next.js & UX Design
Ready to dive deeper into the architecture?