AWS Builder Center
Saving Every Drop: How We Built JalLoop

Saving Every Drop: How We Built JalLoop

JalLoop is an open-source, IoT-enabled domestic water recycling system that intercepts RO reject and washing machine greywater, governs multi-stage filtration via an ESP32 microcontroller, enforces safety invariants using AWS Cedar, and provides real-time telemetry on AWS Cloud.

Authors: Babli Rawat and Abhinav Tiwari Track: Bharat Builds Tour • Environmental Hacks (Water Track) • AWS Builder Center Date: October 2026 Repository:  https://github.com/bablirawat/WaterRecycleSystem 



1. The Daily Waste Nobody Measures

If you walk behind almost any residential apartment complex or suburban home equipped with a reverse osmosis (RO) drinking water purifier, you will see a thin white plastic pipe draining steadily into an open sewer or paved driveway.
For every single liter of drinking water a standard domestic RO membrane purifies, it discards approximately two to three liters of reject water. The exact rejection ratio varies depending on membrane age, feed pressure, and inlet Total Dissolved Solids (TDS). Because concentrated dissolved minerals are trapped during filtration, this reject water cannot be consumed or used for cooking. However, it is clear, odor-free, and well-suited for non-potable residential chores: toilet flushing, balcony and vehicle washdowns, and select gardening (depending on plant species and soil salinity tolerance). When you factor in the final rinse cycles of modern washing machines and seasonal rooftop rainwater runoff, an average ten-apartment housing society discards between 300 and 500 liters of recoverable greywater every single day.
A painful paradox unfolds just a few hours later: municipal pipeline supply shuts off, overhead storage tanks run dry, and the housing society committee calls a commercial diesel water tanker, paying commercial market rates to pump groundwater back into the building sumps. We literally spend money to buy back groundwater while dumping usable greywater into stormwater drains every morning.
Centralized Sewage Treatment Plants (STPs) exist for sprawling commercial townships, but their capital expense, large physical footprint, and full-time mechanical maintenance requirements make them economically unfeasible for independent residential homes and small apartment complexes. Manual bucket collection fails because of human friction: nobody wants to carry 20-kilogram buckets of washing machine water across stairs every evening.
We wanted to see if embedded computing and automated cloud systems could solve this friction at the source:
  1. Intercept non-potable greywater at the point of discharge.
  1. Monitor physical liquid levels using low-cost acoustic ultrasonic sensing.
  1. Enforce deterministic safety guardrails before running physical pumps.
  1. Give residents transparent, real-time visibility over water saved every day.
That is why we built JalLoop.



2. The Physical System: Three Tanks and an ESP32

Before touching cloud infrastructure, we modeled the physical fluid loop. JalLoop routes greywater through three distinct stages:
Plain text
[Inflows: Domestic RO Reject / Laundry Rinse / Rooftop Rainwater] │ ▼ ┌─────────────────────────────────────┐ │ Collection Tank │ ◄── HC-SR04 Sonar (TRIG: 5, ECHO: 18) [30 cm Depth / 100 L] │ Raw Greywater Buffer │ ◄── Optical Turbidity Sensor (ADC: GPIO 34) └──────────────────┬──────────────────┘ │ (12V High-Pressure Booster Pump — Relay GPIO 32) ▼ ┌─────────────────────────────────────┐ │ 3-Stage Filter Pack │ ◄── Coarse Particle, Suspended Sediment & Carbon Adsorption │ (LED 26, LED 16, LED 33) │ Physical Filtration & Particulate Polishing └──────────────────┬──────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ Recycled Tank │ ◄── HC-SR04 Sonar (TRIG: 19, ECHO: 21) [60 cm Depth / 200 L] │ Treated Non-Potable Water │ ───► Outflow Relays: Toilet (GPIO 2), Garden (17), Floor (13) └─────────────────────────────────────┘
The physical fluid loop is governed by dedicated C++ firmware executing on an ESP32 microcontroller ( firmware/jalloop_esp32.ino ):
  • Ultrasonic Liquid Level Sensing (HC-SR04): Non-contact ultrasonic acoustic transducers mounted at the top of each tank emit 40 kHz sound waves down to the fluid surface and capture the echo reflection timing. Deriving the air gap from sound velocity (v ≈ 343 m/s), the firmware calculates liquid column height, converted volume in liters, and percentage full.
  • Inflow Clarity Tracking (GPIO 34 ADC): Greywater quality varies widely depending on whether it comes from clear RO reject or soapy laundry rinse. An optical turbidity sensor measures light transmission across a 12-bit ADC channel (0–4095), allowing firmware to categorize water clarity as Good, Fair, or Poor.
  • Status LEDs and Physical Push-Button Override: 13 dedicated indicator LEDs provide immediate status feedback on the enclosure for maintenance technicians across pumps, filtration stages, and valves. A heartbeat LED on  GPIO 25  toggles every 500 ms to confirm watchdog vitality, while a tactile button on  GPIO 0  enables immediate manual pump toggling.



3. Real Project Interface: The Live Telemetry Dashboard

The sensory data collected by the ESP32 is presented in a modern React 19 web application, providing building occupants and facilities managers with an intuitive, real-time view of water recycling and storage:
The system supports two complementary operating workflows:
  1. Demo Mode & Virtual Hardware Workbench: For rapid development, testing, and evaluation without physical wiring, Demo Mode runs entirely in the browser. We built the Virtual Hardware Workbench ( VirtualHardwareWorkbench.jsx ), an interactive breadboard simulator with sliders to inject simulated collection tank levels, adjust turbidity, trip emergency interlocks, and observe live animated SVG fluid piping and mirrored LED states.
  1. Live Mode & Firebase RTDB Synchronization: In Live Mode, the dashboard connects directly to Firebase Realtime Database. The ESP32 firmware pushes telemetry every 2000 ms ( UPLOAD_INTERVAL = 2000 ) via HTTP PATCH to  /sensorData.json , polls for remote operator commands every 800 ms ( COMMAND_INTERVAL = 800 ) from  /commands.json , and reflects LED states every 400 ms. If incoming sensor readings stall beyond 8000 ms, the dashboard flags the telemetry as stale.



4. Safety Must Come Before Automation: AWS Cedar Policy Invariants

Automated water transfer presents physical mechanical risks. If an operator triggers a manual pump command while the collection tank is dry, running without fluid lubrication and cooling induces rapid thermal overheating, mechanical seal degradation, and impeller cavitation. Furthermore, if heavily soiled laundry water with high suspended solids is pumped directly into fine filters, it blinds the carbon membranes instantly.
Rather than scattering ad-hoc conditional statements across UI controllers, we codified formal authorization rules and safety guardrails using the open-source AWS Cedar Policy Engine ( policies/jalloop.cedar  and  src/services/cedarPolicy.js ):
Plain text
cedar// Policy 4 from policies/jalloop.cedar: Turbidity Protection Guardrailforbid ( principal, action == JalLoop::Action::"StartRecycling", resource) when { resource.turbidity > 85 // Prevents fine filter membrane clogging from high particulate load};// Policy 5 from policies/jalloop.cedar: Dry-Run Cavitation Invariantforbid ( principal, action == JalLoop::Action::"UseRecycledWater", resource) when { resource.recycledLiters < 5 // Requires minimum liquid buffer to protect distribution pump};
By decoupling safety invariants into Cedar policies, autonomous AI agent recommendations ( src/services/aiAgentService.js ) and administrative control handlers must pass formal policy evaluation before commands reach hardware.
At the hardware level, this is backed by an autonomous firmware fail-safe: if ultrasonic sensing detects collection tank depth below 15%, the ESP32 forces the pump relay open locally, overriding any external cloud command.



5. Cloud Architecture: From Local Emulation to Production Design

As part of our submission for the AWS Open Source & Cloud Challenge, we designed JalLoop to be tested locally on developer laptops using open-source tools while remaining architecturally ready for deployment on AWS managed cloud services across 7 specialized tracks:
Track & Local Tool
Target AWS Cloud Service
Implementation in JalLoop
1. Agents & AI (Strands SDK)
Amazon SageMaker AI / Bedrock
Autonomous ReAct reasoning loop evaluating live metrics against ISO 30500 non-potable benchmarks.
2. Containers (Finch / Docker)
Amazon ECS / AWS Fargate
Multi-stage container definitions running frontend UI, LocalStack mocks, and OpenSearch nodes.
3. Serverless (SAM CLI & LocalStack)
AWS Lambda, DynamoDB, API Gateway
Serverless SAM CloudFormation template and telemetry ingestion event handlers.
4. Servers & Runtimes (Amazon Corretto, Node)
AWS Amplify Hosting, App Runner
Automated CI/CD build specification powering single-page application hosting with zero server overhead.
5. Data & Search (OpenSearch 2.x)
Amazon OpenSearch Service, Amazon S3
Time-series indexing and Query DSL searching to detect filter wear.
6. Auth & Policy (AWS Cedar)
Amazon Cognito, JWT Tokens
Role-based access control with RFC 7519 HMAC-SHA256 JWT tokens and 2-step email verification.
7. The Plumbing (OpenEvent Specs)
Amazon EventBridge, CloudFront
Asynchronous pub/sub event bus routing threshold alerts with CloudFront CDN edge caching.



6. What Works Today vs. Pre-Production Roadmap

To maintain rigorous engineering honesty, we explicitly separate our verified implementations from planned roadmap items:
  • Verified and Demonstrated Today:
  • Complete React 19 web application featuring animated SVG glass piping, live tank level gauges, and Recharts historical analytics.
  • In-browser Virtual Hardware Workbench enabling zero-hardware development and simulation.
  • Production-ready ESP32 C++ firmware ( jalloop_esp32.ino ) operating in Wokwi simulation and physical circuits, synchronizing HC-SR04 sonar distances, turbidity ADC values, and 13 LEDs over Firebase Realtime Database.
  • AWS Cedar declarative authorization and dry-run safety invariant verification ( policies/jalloop.cedar ).
  • Containerized SAM, LocalStack, and OpenSearch integration configurations.
  • Pre-Production Roadmap:
  • Upgrading exposed HC-SR04 transducers to sealed, waterproof JSN-SR04T ultrasonic sensors with conformal-coated IP67 enclosures to withstand long-term sump humidity.
  • Transitioning cloud connectivity from HTTP polling to AWS IoT Core MQTT endpoints authenticated with device X.509 certificates.
  • Adding an automated mechanical backwash lint trap for high-debris washing machine inflows.



7. A Grounded Closing

Water conservation is often treated as an exercise in personal discipline: take shorter showers, turn off the tap while brushing. While valuable, individual restraint is an incomplete solution when our residential buildings are engineered to discard hundreds of liters of recoverable greywater into sewers every single day.
Building JalLoop demonstrated that water recycling does not require multi-crore municipal installations or manual bucket hauling. By uniting accessible microcontrollers, declarative safety guardrails, and observable cloud architectures, we can close the drain—turning discarded domestic wastewater into an automated, predictable, and measurable asset.
Every drop saved is a drop that does not have to be pumped from an over-extracted aquifer or purchased from a diesel tanker.


Authors: Babli Rawat & Abhinav Tiwari GitHub Repository:  https://github.com/bablirawat/WaterRecycleSystem 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article