Building an Idempotent, Serverless Reverse-Vending Kiosk for Campus Recycling on AWS
How we engineered an IoT reverse-vending kiosk that exchanges PET bottles and cans for calibrated community animal feed using Node.js 20 on ARM64 Graviton AWS Lambda, DynamoDB conditional writes, and API Gateway HTTP API v2.
Building an Idempotent, Serverless Reverse-Vending Kiosk for Campus Recycling & Animal Welfare on AWS
By Jtss-ux | Built for Bharat Builds Tour 2026: Environmental Hacks (Waste and Energy Track)
1. Introduction: The Urban Dual-Challenge & Regulatory Imperative
In Indian university campuses, transit terminals, and municipal centers, post-consumer beverage packaging represents an acute environmental burden. Millions of Polyethylene Terephthalate (#1 PET) bottles and aluminium cans are discarded daily into unsegregated municipal streams.
Under the Solid Waste Management Rules, 2016 (SWM Rules 2016), educational institutions, university hostels, and facilities with over 500 residents are classified as Bulk Solid Waste Generators (BWGs). They are legally mandated to install on-site source segregation and processing systems. Concurrently, under the Ministry of Environment, Forest and Climate Change (MoEFCC) Fourth Amendment to the Plastic Waste Management Rules (Schedule II) and the Central Pollution Control Board (CPCB) Common EPR Portal, Producers, Importers, and Brand Owners (PIBOs) face stringent Extended Producer Responsibility (EPR) mandates for Category I rigid plastic packaging.
Yet, despite statutory mandates, the primary barrier to campus recycling remains incentive asymmetry. Traditional bins offer zero immediate feedback, zero tangible civic reward, and zero transparency.
Simultaneously, campuses sustain large populations of community animals (stray dogs, community cats, urban birds). The Supreme Court of India (Order dated 07.11.2025 in Suo Motu W.P. Civil No. 5/2025) and the Animal Welfare Board of India (AWBI Standard Operating Procedure) direct institutional premises to establish structured, designated, and hygienic feeding mechanisms to eliminate food competition, aggressive scavenging, and waste-pile feeding.
ReCycle2Feed was engineered to solve both statutory challenges in a unified, closed-loop automated system:
A user deposits an eligible PET bottle or aluminium can → Smart optical and inductive sensors verify the material → An internal rotary compactor crushes the container by 70% → An AWS Serverless microservice authorizes a calibrated 10g–20g portion of nutritious feed into a sanitized community bowl → An immutable environmental record is logged in Amazon DynamoDB.
In this technical deep-dive, I'll walk through how we architected ReCycle2Feed using AWS SAM, Node.js 20.x on ARM64 Graviton AWS Lambda, Amazon DynamoDB atomic conditional writes, Amazon API Gateway HTTP API v2, and LocalStack.
2. High-Level Architecture Overview
A physical reverse vending machine (RVM) operating in a public environment must satisfy three non-negotiable operational requirements:
- Sub-Second Edge Responsiveness: Users standing in front of a kiosk expect immediate feedback.
- Guaranteed Transaction Idempotency: Flaky Wi-Fi/LTE connections must never trigger duplicate dispensing or double-counting.
- Zero Idle Infrastructure Cost: As a public civic initiative, hosting costs during nighttime lulls must be exactly $0.00.
3. The Core Challenge: Absolute Idempotency in Reverse Vending
In traditional web applications, duplicate requests might create a duplicate cart or harmless log entry. In an IoT reverse vending machine dispensing physical food portions, duplicate requests cause physical motor actuation, hopper depletion, and potential over-feeding hazards.
When an edge kiosk connects over cellular (4G/LTE) or public campus Wi-Fi, temporary connection drops are frequent:
- The kiosk submits a transaction event (
eventId: evt-173892-x89f2).
- The Lambda function processes the event and decrements inventory.
- The network drops before the kiosk receives the 200 OK HTTP response.
- The kiosk retry-client re-transmits the identical payload.
The Solution: DynamoDB Atomic Conditional Writes
Rather than implementing brittle distributed locks in Redis or relying on memory caches, we leverage Amazon DynamoDB's native conditional expressions:
TypeScript
// backend/src/repositories/dynamoDbRepo.tsimport { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb';export class DynamoDbRepository implements IRepository {constructor(private docClient: DynamoDBDocumentClient,private tableName: string) {}async createTransaction(tx: TransactionRecord): Promise<void> {const command = new PutCommand({TableName: this.tableName,Item: tx,// CRITICAL IDEMPOTENCY GUARD:ConditionExpression: 'attribute_not_exists(eventId)',});try {await this.docClient.send(command);} catch (err: any) {if (err.name === 'ConditionalCheckFailedException') {throw new Error(`Duplicate transaction detected for eventId: ${tx.eventId}. Dispense rejected.`);}throw err;}}}
[ ESP32 Edge Sensors & Load Cells ] │ ▼ (TLS 1.3 HTTPS / MQTT) [ Amazon API Gateway (HTTP API v2) ] │ ▼ (Proxy Payload) [ AWS Lambda (Node.js 20.x / Graviton ARM64) ] ├── Material Verification Engine ├── Safety Cooldown Lockout └── Idempotency Guard (attribute_not_exists) │ ├──► [ Amazon DynamoDB (3 Tables) ] │ ├── r2f-transactions-prod │ ├── r2f-machines-prod │ └── r2f-maintenance-prod │ └──► [ Amazon CloudWatch ] └── Structured Telemetry & Alarms
Plain text
---## 3. The Core Challenge: Absolute Idempotency in Reverse VendingIn traditional web applications, duplicate requests might create a duplicate cart or harmless log entry. In an IoT reverse vending machine dispensing physical food portions, **duplicate requests cause physical motor actuation, hopper depletion, and potential over-feeding hazards.**When an edge kiosk connects over cellular (4G/LTE) or public campus Wi-Fi, temporary connection drops are frequent:1. The kiosk submits a transaction event (`eventId: evt-173892-x89f2`).2. The Lambda function processes the event and decrements inventory.3. The network drops before the kiosk receives the 200 OK HTTP response.4. The kiosk retry-client re-transmits the identical payload.### The Solution: DynamoDB Atomic Conditional WritesRather than implementing brittle distributed locks in Redis or relying on memory caches, we leverage Amazon DynamoDB's native conditional expressions:```typescript// backend/src/repositories/dynamoDbRepo.tsimport { DynamoDBDocumentClient, PutCommand } from '@aws-sdk/lib-dynamodb';export class DynamoDbRepository implements IRepository { constructor( private docClient: DynamoDBDocumentClient, private tableName: string ) {} async createTransaction(tx: TransactionRecord): Promise<void> { const command = new PutCommand({ TableName: this.tableName, Item: tx, // CRITICAL IDEMPOTENCY GUARD: ConditionExpression: 'attribute_not_exists(eventId)', }); try { await this.docClient.send(command); } catch (err: any) { if (err.name === 'ConditionalCheckFailedException') { throw new Error(`Duplicate transaction detected for eventId: ${tx.eventId}. Dispense rejected.`); } throw err; } }}
Because
ConditionExpression: attribute_not_exists(eventId) is evaluated atomically inside DynamoDB's storage engine at the partition level, simultaneous or retried requests fail instantaneously with a ConditionalCheckFailedException in under 4 milliseconds, without triggering secondary mechanical dispensing.
4. Infrastructure as Code: AWS SAM Template
To maintain zero cloud lock-in and allow one-click reproducible deployments, the entire infrastructure is declared in an AWS SAM template (infrastructure/template.yaml):
- Amazon API Gateway HTTP API v2 with CORS enabled for high throughput and sub-15ms overhead.
- AWS Lambda running Node.js 20.x on ARM64 Graviton architecture for 20% lower cost and higher energy efficiency.
- Amazon DynamoDB with PAY_PER_REQUEST on-demand billing across 3 dedicated tables: r2f-transactions-prod, r2f-machines-prod, and r2f-maintenance-prod.
Why Graviton ARM64?
Under the AWS Well-Architected Framework: Sustainability Pillar, computing efficiency is carbon reduction. Deploying on ARM64 Graviton gives our Node.js runtime:
- 3x better CPU performance-per-watt compared to current-generation x86 processors.
- 20% direct reduction in compute cost.
- Sub-40ms warm execution times across all evaluation routes.
5. Automated Verification & Testing
To ensure safety interlocks work before physical deployment, we authored 14 automated Vitest unit tests covering the entire business logic domain:
- Material Verification Engine: Rejects unsupported waste materials (e-waste, glass, multi-layer pouches) with code MATERIAL_NOT_ACCEPTED.
- Idempotency Engine: Guarantees zero double-dispensing on duplicate transaction re-transmissions.
- Operational Thresholds: Triggers emergency safety lockout when bin capacity reaches 95%.
All 14 unit tests pass cleanly in under 35 milliseconds.
6. Physical IoT Sensor & Mechanical Safeguards
Software correctness is only half the battle; physical reverse vending machines require defensive hardware engineering.
- Optical Time-of-Flight (VL53L1X): Profiles the physical cross-section of the inserted container.
- Inductive Metal Proximity (LJ12A3): Differentiates aluminium drink cans from plastic containers.
- Calibrated Load Cell (HX711 24-bit ADC): Validates tare weight. If a bottle contains residual liquids (>60g), it is rejected to keep the internal compaction bin dry and odor-free.
- Current-Sensing Stall Protection: If the rotary compactor encounters an obstruction, current sensing cuts motor power within 15ms and auto-reverses for 1.5 seconds. If unresolved after 3 cycles, the machine sets a DISPENSER_MOTOR_JAM fault, alerts caretakers, and locks the intake shutter.
Solving Historical Precedent Failures (Pugedon vs. ReCycle2Feed)
In 2014, the viral "Pugedon" smart box in Istanbul introduced the concept of stray dog feeding via bottle recycling. However, longitudinal field studies revealed acute real-world vulnerabilities:
- Unregulated Liquid Contamination: Users poured dregs into the intake or deposited half-full bottles, creating sludge that ruined electronics and spoiled food hoppers.
- Lack of Material Discrimination: Children deposited non-recyclable garbage, rocks, or glass that jammed manual gravity chutes.
- Zero Telemetry / Overflow Blindness: Machines overflowed with no caretaker notification, causing street littering around the unit.
ReCycle2Feed solves every single one of these operational failure modes through load-cell liquid rejection (<60g threshold), dual optical + inductive gating, real-time AWS CloudWatch telemetry, and hermetically sealed food hoppers.
7. Circular Feasibility: A BBA Business Analytics Model
A frequent pitfall of sustainability hackathon projects is the lack of unit economic feasibility. As a business analytics builder, I modeled the real-world operational economics using verified wholesale scrap indices across Delhi NCR and Maharashtra (corroborated via IndiaMART secondary raw material markets):
- Clear PET Bottle Scrap (Clean): Rs. 42.00 - Rs. 50.00 / kg
- Hot-Washed rPET Flakes (Recycled): Rs. 72.00 / kg
- Crushed Aluminium Can Scrap: Rs. 110.00 - Rs. 125.00 / kg
- CPCB EPR Plastic Credit Value: Rs. 1.50 - Rs. 3.00 / kg
Unit Economics Per Dispense Cycle
- Average Bottle Weight: ~28 grams (36 bottles yield 1 kg of clean flake)
- Scrap Revenue per Bottle: ~Rs. 1.18 / bottle (based on Rs. 42/kg base baled scrap value)
- Feed Portion Cost (20g kibble): ~Rs. 1.70 / portion (bulk wholesale dry feed procurement at Rs. 85/kg)
- EPR Credit Offtake Value: ~Rs. 0.08 / bottle (CPCB registered plastic recycling certificate generation)
- Brand Sponsorship / CSR Co-Pay: ~Rs. 2.24 / cycle (on-kiosk digital signage sponsored by pet nutrition & FMCG brands)
- Total Gross Revenue per Cycle: Rs. 3.50 / cycle
- Total Direct Cost per Cycle: Rs. 1.70 / cycle
- Net Operational Contribution: +Rs. 1.80 / cycle (100% self-funding for caretaker servicing, electricity, and maintenance)
Reverse Logistics Optimization
Because ReCycle2Feed reduces container volume by 70%, municipal collection trucks require 3.3x fewer emptying trips. In campus environments generating 500 bottles daily, this eliminates ~14 unnecessary diesel truck trips per month, directly cutting Scope 1 transport emissions.
8. Frontend Engineering: Cyberpunk Terminal HUD
To make the system memorable and interactive for judges and users, we redesigned the frontend from a generic green theme into a high-tech dark cyberpunk HUD:
- Live Telemetry Bar: Real-time ticker showing station node status, active AWS region (ap-south-1), DynamoDB conditional write latency, and hackathon track indicators.
- Touchscreen Kiosk: Fully bilingual (English & Hindi: कचरे से देखभाल की ओर), with an interactive Evaluator Test Bench enabling judges to simulate full bins (98%), motor jams, empty hoppers, and network disconnects.
- Auditable Impact Ledger: Interactive transaction exploration with zero fabricated claims: real grams recovered, portions dispensed, and complete event logs.
9. Key Lessons & Feedback for AWS
Building ReCycle2Feed provided valuable architectural insights into the AWS ecosystem:
- DynamoDB Conditional Writes are a Game-Changer for IoT: Implementing idempotency at the database layer eliminated race conditions and double-reward risks with zero operational complexity.
- AWS SAM is Dramatically Faster than Raw CloudFormation: Writing high-level AWS::Serverless::Function and AWS::Serverless::HttpApi constructs reduced infrastructure code by over 60%.
- Room for Improvement in SAM CLI Local Emulation: Better first-class flags for routing SAM local invocations to LocalStack containers without manual environment URL overrides would significantly improve edge developer onboarding.
10. Conclusion & Project Links
ReCycle2Feed proves that when cloud-native serverless architecture is paired with thoughtful physical engineering and realistic unit economics, we can turn everyday litter into community care.
- Live Interactive Web App: https://jtss-ux.github.io/recycle2feed/
- GitHub Repository: https://github.com/Jtss-ux/recycle2feed
- 3-Minute Demo Video (YouTube): https://youtu.be/KCqz4FkRvRI
- AWS SAM Infrastructure: infrastructure/template.yaml
Built for the Bharat Builds Tour 2026: Environmental Hacks (Waste & Energy Track) by WeMakeDevs & AWS.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article