DEV Community

Cover image for Revolutionizing Retail: A Blockchain-Powered Loyalty and Transaction System with FastAPI + Ethereum
Shushant Rishav
Shushant Rishav

Posted on • Edited on

Revolutionizing Retail: A Blockchain-Powered Loyalty and Transaction System with FastAPI + Ethereum

Traditional retail systems, despite decades of evolution, continue to struggle with fundamental structural inefficiencies. Loyalty programs remain siloed, transaction histories are opaque, and centralized databases introduce single points of failure that are vulnerable to fraud, data corruption, and administrative manipulation. At scale, these systems also suffer from high operational costs and limited interoperability across brands.

To address these challenges, I built a Hybrid Retail Blockchain System an architecture that combines the speed and reliability of traditional databases with the immutability and auditability of blockchain, without sacrificing real-time user experience.

Rather than forcing retail transactions directly on-chain (which is impractical due to latency and gas costs), this system adopts a database-first, blockchain-anchored design suitable for real-world commerce.


Why Blockchain and Why Hybrid?

Blockchains are powerful, but they are not designed for sub-second transactional workloads. Public networks like Ethereum introduce unavoidable latency due to block times and probabilistic finality.

Retail systems, on the other hand, require:

  • Low-latency DB-first confirmation
  • Deterministic correctness
  • High throughput during peak hours

This creates the finality–latency tradeoff.

The Solution: Dual-State Architecture

  • PostgreSQL serves as the hot state for real-time transactions
  • Ethereum acts as an immutable audit ledger
  • The system is DB-first, the API returns only after PostgreSQL commit, and can optionally write to Ethereum during the same request.

This preserves the UX guarantees of traditional systems while gaining the trust and transparency benefits of Web3.


What Blockchain Brings to Retail (When Used Correctly)

  • Immutability: Transaction records are cryptographically anchored and tamper-proof
  • Transparency: Transaction proofs are verifiable on-chain when enabled, loyalty balances are stored off-chain in PostgreSQL with deterministic rules.
  • Security: No single point of failure for historical data
  • Interoperability: Enables future cross-brand loyalty ecosystems

Blockchain becomes a trust layer, not a performance bottleneck.


Technology Stack

The system is designed for correctness, scalability, and operational resilience:

  • FastAPI – Async Python backend with high-throughput request handling
  • PostgreSQL – ACID-compliant transactional datastore
  • Redis – Idempotency middleware cache
  • Solidity – Smart contracts for immutable transaction anchoring
  • Ethereum / Ganache / Sepolia – Development and test networks
  • Web3.py – Blockchain interaction and transaction signing
  • solcx – Dynamic Solidity compilation
  • Docker – Environment-consistent deployment

High-Level System Architecture

[POS / Frontend]
        |
        |  POST /transactions (Idempotency-Key)
        v
[FastAPI Backend]
        |
        +-- Redis (Idempotency Lock)
        |
        +-- PostgreSQL (ACID Transaction)
        |       - Create Sale Record
        |       - Update Loyalty Balance
        |
        +-- Blockchain Anchor (Async)
                - Convert INR → Wei (cached + emergency fallback)
                - Sign & Broadcast TX
                - Wait for receipt (current implementation)
                - Persist txId + txHash back into PostgreSQL

Enter fullscreen mode Exit fullscreen mode

The customer receives an immediate response after the PostgreSQL write. When blockchain is enabled, the endpoint currently waits for the on-chain receipt before responding.


Core Backend Services

  • Transaction Manager
    Ensures atomic DB writes and maps internal transaction IDs to blockchain hashes.

  • Idempotency Guard (Redis-based)
    Prevents duplicate charges during retries, crashes, or network failures.

  • Loyalty Engine
    Deterministic, precision-safe loyalty calculation using Decimal + ROUND_CEILING, implemented in PostgreSQL-backed logic.

  • Blockchain Anchor Service
    Posts transaction metadata to Ethereum when enabled, the current implementation waits for the receipt before returning.

  • Currency Conversion Module
    Multi-tier fallback (cached ≤ 60s → live CoinGecko refresh → emergency fixed rate) to ensure uptime under API failures.


Key Features

  • ⚡ Low-latency DB-first confirmation
  • 🔒 Retry-safe execution via Redis-backed idempotency middleware
  • 📜 Immutable blockchain audit trail
  • 🎯 Deterministic loyalty rewards
  • 🔁 Retry-safe APIs
  • 📊 Swagger & ReDoc auto-generated documentation
  • 🐳 Dockerized, reproducible setup

Example API Usage

Record a Transaction

POST /transactions/record (Idempotency-Key)
{
  "orderid": "ORD-ABC123",
  "customeraddress": "0x...",
  "amountINR": 1500.75
}

Enter fullscreen mode Exit fullscreen mode

The response is immediate after the PostgreSQL write, when blockchain is enabled, the API currently waits for the on-chain receipt before responding.


Local Development Setup

Prerequisites

  • Python 3.8+
  • Docker & Docker Compose
  • Ganache CLI

Run Locally

git clone https://github.com/shushantrishav/Blockchain_In_Retail.git
cd Blockchain_In_Retail

cp .env.example .env
pip install -r requirements.txt

npx ganache-cli -d
uvicorn app.main:app --reload
Enter fullscreen mode Exit fullscreen mode

Deployment Notes

  • Switch to Sepolia / Mainnet via Infura or Alchemy
  • Persist deployed contract addresses
  • Secure private keys via environment variables or secret managers
  • Never hardcode credentials

Lessons Learned

  • Blockchain should anchor, not block, retail workflows
  • Idempotency is non-negotiable for financial systems
  • Floating-point math has no place in money or rewards
  • Async design is the difference between demos and production systems

Business Impact

  • 📈 Increased customer trust via transparent loyalty systems
  • 🔁 Higher retention due to predictable rewards
  • 🤝 Foundation for cross-brand loyalty partnerships
  • 🛡️ Auditability without operational slowdown

Roadmap

  • Zero-Knowledge Proofs for private loyalty validation
  • L2 batching with Merkle roots (99% gas reduction)
  • WalletConnect & MetaMask integration
  • Admin analytics dashboard
  • Multi-chain support (Polygon, Avalanche)

Final Thoughts

This project demonstrates how Web2 reliability and Web3 trust can coexist in real-world systems. By respecting the constraints of both domains, we can build retail infrastructure that is fast, transparent, and future-proof.

🔍 Project: https://github.com/shushantrishav/Blockchain_In_Retail
🧪 Live Demo: https://block-cart.vercel.app

⭐ If you found this useful, consider starring the repo or contributing!

Top comments (0)