Wednesday, July 16, 2025

๐Ÿ”„ A Curious case of Redis vs Caffeine and ever existing Trade-offs

๐Ÿง  The Assumption

For years, I treated Redis as the default solution for caching.... after all

  • It's fast.
  • It supports persistence.
  • It’s distributed.
  • Everyone uses it.

It was one of those tools that seemed like an automatic “yes” whenever caching came up in any design discussion.

So naturally, when I started analyzing a high-performance OAuth server, I was fully expecting Redis to be at the heart of its caching layer.

But what I found instead was... Caffeine.

And that changed how I look at caching decisions entirely. I always knew its always a trade-off but we inherently bias towards our favorite solutions and we need to learn to stop and think.


๐Ÿงญ Lessons from Existing Code: Don’t Just Learn by Building

As engineers, we often think the best way to learn is to build from scratch. But this experience reminded me how much there is to learn from studying well-designed production systems — especially when built by expert teams operating in high-stakes environments like banking/fintech. Afterall why reinvent a wheel each time.

I didn't write the OAuth server. But reviewing its code, dissecting the reasoning, and understanding the performance considerations taught me as much as (if not more than) writing one myself.


๐Ÿ” Redis vs. Caffeine: Revisiting the Comparison

Feature Redis Caffeine
Location Remote (over network) In-JVM
Latency ~1-3 ms <1 ฮผs (nanoseconds)
Setup Needs deployment, scaling, monitoring Zero setup, embedded
Persistence Yes No
Cross-instance sharing Yes No (per instance)
Eviction policies LRU, TTL Advanced: size, frequency, TTL
Serialization overhead Yes None
Startup state Warm (centralized) Cold start
Failure handling Needs retry, backoff logic JVM-safe, no external calls

๐Ÿ” Why Redis Wasn’t Chosen — and Why That Makes Sense

1. The cache wasn’t critical to correctness

The cached data was:

  • Mostly static client configuration
  • Derivable from a database or config service
  • Frequently read, rarely updated

A cache miss wasn’t a system failure — just a slightly slower response.

2. Latency mattered more than persistence

In an OAuth server that processes thousands of token validations per second, even 1ms per lookup has measurable impact.

Redis: ~1-3ms
Caffeine: sub-millisecond (nanoseconds)

3. Simplicity wins in high-availability setups

Using Redis in a high performance/critical environment means:

  • Setting up secure connections (TLS)
  • Managing replication/failover
  • Ensuring Redis HA is as resilient as the app itself

Caffeine required none of that — it was a zero-dependency, drop-in cache with advanced eviction and tuning capabilities.

4. Each instance could function independently

The OAuth server didn’t require session sharing or cross-instance consistency. Local in-memory cache was not just acceptable — it was ideal.


๐Ÿง  Key Realization: The Best Tool is Use-Case Driven

Before this, I might have pitched Redis on auto-pilot. But this real-world implementation forced me to slow down and ask:

“What does this specific use case actually need?”

And the answer wasn’t persistence, or distributed state, or warm startup.

It was:

  • Speed
  • Simplicity
  • Per-instance safety
  • GC-aware eviction
  • Minimal moving parts

Caffeine was the better fit — not because Redis is bad, but because Caffeine aligned better with the real goals of the system.


๐Ÿšง Learning From Existing Systems

This wasn’t something I learned by building a new service from scratch.

It was something I learned by observing what had already been done well, and then understanding why those decisions were made.

We often glorify greenfield projects. But there is incredible value in studying the systems already running reliably in production.

Existing codebases, especially in complex environments are full of real, hard-earned lessons.


๐Ÿงญ Final Thought: It’s Always About Trade-offs

This experience brought me back to a fundamental truth of software engineering:

There is no best tool — only the best fit for the problem.

Redis is great — even amazing — when the problem demands:

  • Shared state
  • Central cache
  • Persistence
  • Warm start

But in a high-performance OAuth server, built to run fast, scale horizontally, and tolerate cold starts — Caffeine was the elegant and practical choice.


๐Ÿ”š Takeaways worth summarizing

  • Don’t default to Redis just because it’s popular.
  • Understand the performance vs. persistence trade-off.
  • Learn from production code — not just personal projects.
  • Choose the caching strategy that fits your use case, not your toolbox.

Tuesday, July 15, 2025

⚓ Kanhoji: Real-Time Monitoring – The Guardian of Fraud-Free Swarajya


“The sea is no one’s property. But its protector, I shall be.”
— Kanhoji Angre, Admiral of the Maratha Navy


๐ŸŒŠ Why I Named Our Monitoring Module kanhoji

Every great kingdom needs a vigilant guardian — someone who spots threats before they reach the shore. In the Swarajya movement, that role was embodied by Kanhoji Angre, the legendary admiral of the Maratha Navy.

  • Kanhoji wasn’t just a warrior — he was a master strategist.
  • He intercepted enemy ships, anticipated surprise attacks, and built naval intelligence networks.
  • He knew that if you wait until a breach happens, it’s already too late.

In our modern-day microservices architecture, that role belongs to real-time monitoring. Thus, I named our observability module kanhoji — a tribute to the admiral who kept the empire safe with foresight and maritime mastery.

๐Ÿ“ˆ What kanhoji (Monitoring) Does in Our System

In the context of our AI-powered fraud detection platform, kanhoji is responsible for:

  • Keeping an eye on service health
  • Monitoring response times, error rates, and traffic patterns
  • Exposing custom metrics (e.g. fraud score thresholds)
  • Powering a Grafana dashboard for real-time visibility

Just like Kanhoji Angre kept Aurangzeb’s navy in check, our monitoring module makes sure fraud doesn’t creep in through hidden blind spots.

๐Ÿ”ง The Tech Behind It

ComponentRole
PrometheusPull-based metrics scraping and time series storage
GrafanaBeautiful dashboards for real-time data
MicrometerJava metrics facade for Spring Boot
Spring ActuatorAuto-exposes HTTP metrics (count, latency, status)

I integrated kanhoji into our existing services (sindhudurg, tanaji) with minimal overhead and maximum insight.

๐Ÿ“Š Our Dashboard in Action

I track metrics like:

  • ๐Ÿ“‰ http_server_requests_seconds_count – endpoint latency
  • ๐Ÿงช status="500" – internal server errors
  • ๐Ÿ” jvm_memory_used_bytes – memory health
  • ๐Ÿง  Coming soon – fraud-related custom metrics

I even tried to write a Python traffic simulator to test the dashboard in action! :) a little fun. 

๐Ÿง  Why Monitoring Matters in Fraud Detection

Fraud isn’t always loud. Sometimes it comes as:

  • A slow buildup of failed transactions
  • An AI model that’s taking too long to respond
  • Unusual traffic patterns on specific endpoints

Without observability, we’d be flying blind. Kanhoji gives us:

  • ⏱️ Early warnings
  • ๐Ÿงฏ Quick troubleshooting
  • ๐Ÿ” Root cause clarity

⚓ Kanhoji Angre: The Real Legend

Before we end, let’s celebrate the namesake:

  • ๐ŸŒŠ Known as the “Shivaji of the Sea”
  • ๐Ÿ‡ฎ๐Ÿ‡ณ Never defeated by British, Portuguese, or Dutch fleets
  • ⚔️ Ran a full naval intelligence network from Kolaba Fort
  • ๐Ÿšข Used small, agile ships to outsmart colonial navies — like microservices!

๐Ÿ›ก️ What’s Next?

  • Expose Redis and Rule Engine metrics
  • Enable alerts for fraud score spikes
  • Track rule overrides and fraud trends in real time

If Tanaji is the warrior, and Dadoji the wise council, then Kanhoji is the watchtower.
Every system needs one.

๐Ÿ“– Explore the Code

๐Ÿ”— GitHub: github.com/pcm1984/fraud-free-swarajya

๐Ÿ“Š For dashboard JSON and usage instructions: Kanhoji Monitoring README

Friday, July 11, 2025

๐Ÿ“š The Lost Art of Reading — And Why We Must Bring It Back


A few days ago, I wrote about how writing is slowly fading from our lives—and why it desperately needs a revival. But writing isn’t the only silent casualty. Reading, too, is on life support. And if we don’t act soon, we may lose one of the most timeless habits that shaped who we are.

“A reader lives a thousand lives before he dies. The man who never reads lives only one.”
— George R.R. Martin

 

Do you remember the last time you got lost in a book?

Not just skimmed headlines, not doomscrolled your social feed, but really fell into a story—where minutes became hours, and a chapter became an entire evening?

If that feels like a distant memory, you’re not alone.

We live in a world of blazing reels, 2x speed podcasts, and "tl;dr" summaries. The rhythm of life is so fast, reading sometimes feels like a forgotten luxury. But perhaps, it’s time to dust off those paperbacks (or power up the e-reader), because reading isn’t just nostalgic—it’s necessary.


1. A Short, Beautiful History of Reading

Reading was once a quiet revolution. When Gutenberg printed the first books, knowledge leaped beyond monasteries and reached every curious mind. Libraries became temples, and readers, seekers of truth.

In ancient times, people read aloud—then silently, then voraciously. For centuries, to be well-read meant to be well-versed in life. Books traveled across time, generations, and cultures—carrying wisdom in ink and paper.

But then... came autoplay.

2. The Underrated Magic: Benefits of Reading

  • ๐Ÿ“– Expands vocabulary and deepens comprehension
  • ๐Ÿง  Boosts memory and focus
  • ๐Ÿง˜ Reduces stress—sometimes more than meditation!
  • ๐Ÿ’ญ Enhances empathy by letting us live others’ lives

It’s a workout, but for your imagination. With every page, your brain builds new connections, makes predictions, fills gaps, imagines tone, pictures faces.

TikTok doesn’t do that.

3. But Videos Are More Fun, Right? Not Really.

Sure, videos are flashy. They’re fast, loud, addictive. But they’re often passive. You sit back and watch. The story unfolds for you.

With reading, you co-create the world.

  • A haunted castle isn’t just seen—it’s felt.
  • A hero’s decision isn’t just told—it’s wrestled with.
  • That twist ending? You didn’t see it. You earned it.

4. Reading vs. Videos: Cognitive Advantage

Studies show readers retain information longer and understand nuance better than video watchers. Why?

Because reading activates multiple areas of the brain: language, memory, critical thinking, and imagination. It slows you down just enough to process and reflect.

Videos? They often rush past details like a news ticker on steroids. They entertain, sure—but rarely enlighten.

5. Why Blogs Beat Vlogs (Sorry, YouTube)

  • ๐Ÿ“ Blogs allow pause and ponder.
  • You can skim, scroll, highlight, reread—your way, your pace.
  • They respect your time. No waiting for a “like and subscribe” moment.
  • They don’t yell at you with flashing thumbnails.

And guess what? Good writing feels like a quiet conversation, not a sales pitch wrapped in a skit.

6. Your Eyes Will Thank You

Let’s be real—hours of screen glare is brutal. Eye strain, dry eyes, headaches—the digital fatigue is real.

Reading, especially on paper or e-ink, is soothing. It feels like sipping tea on a rainy day compared to chugging espresso shots while staring at your inbox.

7. The Gift of Slowness

When you read, you slow down.

You wonder, What will happen after 10 pages?

You pause, reflect, guess. You live in the in-between.

There’s peace in that space. The slowness becomes your sanctuary.

Unlike binge-watching, where one episode demands the next, reading lets you close the book and still feel full.

8. Still More Benefits? Of Course.

  • Improves writing and articulation
  • Encourages lifelong curiosity
  • Offers deep dives, not shallow swipes
  • Builds quiet confidence and concentration
  • Cultivates patience in a dopamine-flooded world

Reading is a rebellion against the algorithm.

9. Small Homes, Big Stories: The Rise of eBooks

Let’s talk practical. Don’t have space for a library? EBooks to the rescue.

Modern eReaders like Kindle or Kobo can hold thousands of books in your palm. You can highlight, bookmark, take notes, and carry your entire collection on a plane—or a train to Wakad.

Less clutter, more chapters.


Final Word: Let’s Revive the Reader in Us

We don’t have to choose between reels and reading. But if we want deeper thinking, richer ideas, and quieter minds—we have to make room for reading again.

Start small. One page before bed. One blog with your morning chai. One weekend with a good novel.

“Books are a uniquely portable magic.”
— Stephen King

Let’s bring back the magic.

Thursday, July 10, 2025

๐Ÿง  The Wisdom of Rules: Building Dadoji for Explainable Fraud Detection

A tribute to Dadoji Konddev — the strategic mind behind structure, just like our rule engine.

๐Ÿ›• Inspired by Dadoji Konddev

Dadoji Konddev, the mentor and guardian of young Shivaji Maharaj, wasn't just a caretaker — he was a visionary. He laid the foundations of discipline, systems, and early strategies that made the idea of Swarajya possible.

In the Fraud-Free Swarajya project, our rule engine is named dadoji in his honor — a system that brings stability, structure, and wisdom to our fraud detection stack.


❓ Why Rules When We Have AI?

This question is at the heart of explainable AI systems.

AI (like our tanaji module) is great at detecting patterns — even ones you can't explicitly define. But there are scenarios where hard rules are:

  • Easier to explain
  • Legally required (compliance)
  • Faster to execute
  • Safer to override AI mistakes

Rules bring clarity and confidence, especially for edge cases.


๐Ÿงฉ When Do We Use Rules?

Here are some real-world fraud detection scenarios where rules are powerful:

Rule Name Condition Action
HighAmountRule Amount > 10,000 Mark as HIGH risk
RiskyLocationRule Location in [“risky”, “banned_country”] Raise risk level
FrequentTxnRule Too many txns from same user in 1 min Flag as suspicious
BlacklistedCardRule Card ends with known fraud pattern Auto-reject
VIPBypassRule User is admin/VIP Adjust recommendation

๐Ÿง  AI + Rules Together = Smarter Detection

Capability AI (Tanaji) Rules Engine (Dadoji)
Learns over time ✅ Yes ❌ No
Deterministic ❌ Not always ✅ Always
Transparent ⚠️ Depends ✅ Fully explainable
Override AI ❌ No ✅ Yes
Business control ⚠️ Harder ✅ Business-friendly
“Let AI detect the unknown. Let rules defend the known.”

⚙️ How It Works in Code

Every rule implements a common interface:

public interface FraudRule {
    boolean apply(TransactionRequest txn);
    String getExplanation();
    RiskIndicator getRiskIndicator();
}

A sample rule:

public class HighAmountRule implements FraudRule {
    public boolean apply(TransactionRequest txn) {
        return txn.getAmount().compareTo(BigDecimal.valueOf(10000)) > 0;
    }

    public String getExplanation() {
        return "High amount transaction";
    }

    public RiskIndicator getRiskIndicator() {
        return RiskIndicator.HIGH_AMOUNT;
    }
}

๐Ÿ”„ How Tanaji + Dadoji Work Together

  1. sindhudurg receives the transaction
  2. Forwards to tanaji (AI engine)
  3. tanaji returns fraud score and risk factors
  4. Response goes to dadoji
  5. dadoji runs applicable rules
  6. If a rule applies:
    • Explanation is added
    • Risk level may be escalated
    • Recommendation may be overridden
  7. Final response sent back to user

๐Ÿน Real-World Analogy

Tanaji Malusare was the courageous warrior who scaled walls.
Dadoji Konddev was the quiet tactician who taught how forts are built.

We need both — just like fraud detection needs AI for intelligence and rules for discipline.


๐Ÿ“œ A Word on Explainability

In banking and fintech, decisions that affect customers (like rejecting a transaction) must be explainable. Dadoji’s rules let us say:

  • “This transaction was rejected because the amount exceeded ₹10,000.”
  • “Risk increased due to login from a risky location.”

These aren’t guesses — they’re policies.


๐Ÿ”ฎ What’s Next?

  • ๐ŸŒ€ Feedback loop (santaji) — to learn from flagged frauds
  • ๐Ÿ”” Real-time notification service (SMS, push, email)
  • ๐Ÿงญ Admin dashboard (ashtapradhan) for rule management
  • ๐Ÿ” API Security and compliance

๐Ÿง  Takeaway

“A rule engine isn’t about replacing AI.
It’s about building trust, consistency, and strategic governance into a system designed to defend.
”

Our tribute to Dadoji is more than a name — it’s a mindset.


๐Ÿ”— GitHub

See the code for all rules and architecture:
๐Ÿ‘‰ github.com/pcm1984/fraud-free-swarajya


๐Ÿ‡ฎ๐Ÿ‡ณ Closing Words

“Shivaji Maharaj won battles not only through might, but through systems.
We too must build software that’s both brave and wise.”

“Marathi Paaul Padte Pudhe…”

Monday, July 7, 2025

๐Ÿšข Dockerizing Fraud-Free Swarajya: Building Forts for Modern-Day Defense

“Code that works is good. Code that runs anywhere is great. Code that stands strong like a fort — that's legendary.”
Inspired by Chhatrapati Shivaji Maharaj’s empire-building wisdom.

๐Ÿงญ Quick Recap

In our open-source journey toward a fraud detection system inspired by the Swarajya movement, we’ve already built:

  • ๐Ÿ›ก️ sindhudurg: Fraud Scoring API (Spring Boot)
  • ๐Ÿง  tanaji: AI Engine (FastAPI + Python)
  • ๐Ÿ“œ dadoji: Rules Engine
  • ⚡ jiva: Redis-based caching
  • ๐Ÿฆ ramchandrapant: PostgreSQL for transaction storage
  • ๐Ÿ“Š kanhoji: Prometheus + Grafana Monitoring

Now it’s time to bring these warriors together in formation — reliably, portably, and scalably.


๐Ÿฐ Inspired by Shivaji Maharaj’s Fort Strategy

Shivaji Maharaj built over 300 forts — not to dominate land, but to secure Swarajya.
Every fort was:
- Modular
- Self-sufficient
- Strategically connected but independently operational

That’s exactly what Docker does for us today in software.

⚔️ Shivaji’s Forts = Our Containers

Forts of Swarajya Docker Microservices
Had their own food, water Contain dependencies & config
Stood independently Isolated service containers
Could signal one another Docker networking
Decentralized command Compose-managed services
Fortified walls Runtime boundary & security
Moved troops via sea/land Image portability across environments

๐Ÿง  Each microservice is a Fort. Docker is our General. Compose is our battle plan.


๐Ÿ›  Why Docker?

  • Before Docker: Manually ran services, installed dependencies, dealt with port conflicts
  • Now: 1 command spins up the entire system reliably across machines

๐Ÿงฉ What We’re Running in Docker

Container NameModule
sindhudurg-appSpring Boot REST API
tanaji-apiFastAPI AI Service
ramchandrapantPostgreSQL DB
jivaRedis Cache
kanhoji-prometheusPrometheus Monitoring
kanhoji-grafanaGrafana Dashboard

๐Ÿ“‚ docker-compose.yml (Snippet)

services:
  sindhudurg-app:
    build: ./sindhudurg
    ports:
      - "8080:8080"
    depends_on:
      - tanaji-api
      - redis
      - postgres-db

  tanaji-api:
    build: ./tanaji
    ports:
      - "8000:8000"

  redis:
    image: redis:7

  postgres-db:
    image: postgres:15
    environment:
      POSTGRES_DB: transactions_db
      POSTGRES_USER: txn_db_user
      POSTGRES_PASSWORD: transactions_secret

๐Ÿš€ Run the System

docker compose up --build

This command:

  • Starts all services
  • Builds Docker images
  • Connects networks internally


๐Ÿ” Test a Transaction

curl -X POST http://localhost:8080/api/v1/fraud-score \
  -H "Content-Type: application/json" \
  -d '{
    "transactionId": "txn001",
    "userId": "user123",
    "amount": 5000,
    "currency": "INR",
    "paymentMethod": "risky",
    "cardNumberLast4": "1234",
    "transactionTime": "2025-04-22T14:30:00Z",
    "location": "risky",
    "deviceId": "d1234",
    "ipAddress": "192.168.1.10",
    "merchantId": "m123"
  }'

๐Ÿ“Š Monitoring in Action

  • Prometheus: http://localhost:9090
  • Grafana: http://localhost:3000 (Login: admin/admin)

๐Ÿ› Troubleshooting Log

ProblemFix
Port ConflictsMapped to different host ports
Redis not visibleSkipped advanced metrics for MVP
Connection refusedUsed service names, not localhost
Postgres driver errorAdded missing dependency
Grafana not showing dataFixed Prometheus targets

๐ŸŽฏ What I Learned

  • Docker = Forts for Software
  • Each service = A garrison of Swarajya
  • Shivaji Maharaj didn’t wait for chaos — he built resilience.

๐Ÿ“Œ GitHub

https://github.com/pcm1984/fraud-free-swarajya


๐Ÿ›ค What’s Next?

  • ๐Ÿ“ฌ Notification Service (SMS, Email)
  • ๐Ÿ” Santaji – Feedback Learning Loop
  • ๐Ÿงช Integration Testing + Observability

๐Ÿ™ Final Thought

“If Shivaji Maharaj could build forts that confused and defeated the mightiest empires…
...surely we can build software systems that don't fall apart on deploy.” ๐Ÿ‡ฎ๐Ÿ‡ณ

Monday, June 30, 2025

Why I Chose AI + Rules for Fraud Detection (Instead of Reinventing the Wheel)


“Smart systems don’t always mean new ideas. Sometimes they mean proven ones, applied well.”


๐Ÿงญ Introduction

When I started designing the architecture for Fraud-Free Swarajya, I spent time analyzing how successful real-world payment platforms like Stripe, Razorpay, Adyen, and PayPal combat fraud.

The pattern was clear:

๐Ÿ” They use AI models to detect patterns and Rules to enforce business logic.

It wasn’t a choice between the two — it was both.

That insight changed how I designed the system.


๐Ÿง  Why Not Just Use AI?

There’s no doubt — modern fraud detection depends heavily on machine learning. AI can detect complex, evolving fraud techniques that rules simply can't catch. And that’s what my module tanaji does.

But here’s what these platforms taught me:

✅ AI predicts. Rules enforce.
✅ AI adapts. Rules protect.
✅ AI learns. Rules ensure compliance.

So I didn’t try to invent something fancy.

I used the established combo:
๐Ÿ”น AI (for learning & scoring)
๐Ÿ”น Rules (for deterministic decisions)


๐Ÿค– Tanaji – The AI Fraud Scoring Engine

I built tanaji using Python and FastAPI. It runs a Random Forest model that accepts transaction data and returns:

  • A fraud score between 0 and 1

  • An explanation (e.g., “High amount”, “Risky country”)

  • List of factors that influenced the score

AI is great for:

  • Learning from past fraud trends

  • Handling edge cases and evolving behavior

  • Detecting subtle correlations (e.g., device + merchant + time pattern)

But it’s not perfect.


⚠️ The Limitations of AI (and Why Big Players Use Rules Too)

  1. AI is probabilistic – It predicts likelihood, not certainty

  2. AI needs training data – Rare fraud types may get missed

  3. AI can’t enforce business policies – Like limits, geofencing, KYC rules

That’s where dadoji enters — our Rule Engine module.


๐Ÿงญ Dadoji – Business Rules That Make the System Accountable

Each rule in dadoji is:

  • Independent

  • Explainable

  • Easy to test and extend

For example:

  • HighAmountRule – Flags transactions above ₹50,000

  • RiskyLocationRule – Flags based on IP or country

  • GiftCardLimitRule – Rejects large gift card purchases

These are not data-driven — they’re policy-driven.

๐Ÿ’ก Even Stripe uses this dual approach — using AI to assess risk, but backing it up with strict rules and thresholds that can override decisions.


๐Ÿ”„ How They Work Together

When a transaction hits sindhudurg (our API gateway):

  1. It first goes to tanaji for fraud scoring

  2. Then passes through dadoji for rule evaluation

  3. The final decision is made using both

Example:

  • Score = 0.93 → Suggests FLAG

  • Rules violated: HighAmount & RiskyMethod → Recommendation: REJECT

This way, business certainty and predictive intelligence work hand-in-hand.


๐Ÿ’ฌ Why This Was the Right Decision

  • ✅ It mirrors what industry leaders are already doing

  • ✅ It gives us flexibility to improve either layer independently

  • ✅ It keeps the system transparent and testable

  • ✅ It simplifies compliance and auditing

I didn’t want to reinvent the wheel.

I just wanted to build it with precision and purpose.


⚔️ Why “Tanaji” and “Dadoji”?

Because Tanaji was the fierce warrior — bold, quick, instinctive.

And Dadoji Konddev was the calm strategist — enforcing rules, discipline, and logic.

Every fraud system needs both.


๐Ÿ› ️ What’s Next

  • A Feedback Loop module (santaji) to learn from false positives

  • Notifications & asynchronous workflows

  • Admin dashboard for monitoring and tuning


๐Ÿ”— GitHub

Code & commits: https://github.com/pcm1984/fraud-free-swarajya


Wednesday, June 25, 2025

Dadoji: The Rule Engine That Brings Wisdom to AI

 

๐Ÿงญ Introduction

In the early days of Swarajya, before Shivaji Maharaj raised a sword or won a fort, there was a man guiding him with discipline, vision, and strategy.

That man was Dadoji Konddev — mentor, administrator, and steward of Shivaji’s early years.

In our Fraud-Free Swarajya system, dadoji is our rule engine — the voice of grounded wisdom that complements the instincts of AI (tanaji).
Because not every decision can be made by machine learning — sometimes, you need good old domain knowledge.


๐Ÿง  Why Do We Need Rules When We Have AI?

AI is great at learning patterns.
But AI can also:

  • Be overconfident

  • Miss edge cases

  • Require lots of data to get it right

That’s where business rules come in — to override, validate, or support AI decisions with deterministic logic like:

✅ "Reject any transaction over ₹2,00,000 unless user is verified"
✅ "Flag if payment method is 'gift card' AND location is flagged"
✅ "Approve only if AI score is < 0.3 AND no high-risk indicators exist"


⚙️ How Dadoji Works

The dadoji component is implemented in Java and is integrated with sindhudurg via method calls for now.

๐Ÿงฉ Architecture

  • Rules are modeled as Java interfaces (FraudRule).

  • Each rule implements:

    java

    boolean evaluate(TransactionRequest request); String getExplanation(); RiskIndicator getRiskIndicator();
  • Multiple rules are evaluated by the RuleExecutor, which returns:

    • ✅ A list of triggered RiskIndicators

    • ✅ Additional explanations if any

    • ✅ Final recommendation (APPROVE, FLAG, or REJECT)


๐Ÿงช Sample Rule: High Amount Rule

java

public class HighAmountRule implements FraudRule { private static final BigDecimal THRESHOLD = new BigDecimal("100000"); public boolean evaluate(TransactionRequest request) { return request.getAmount().compareTo(THRESHOLD) > 0; } public String getExplanation() { return "High amount flagged by rule engine."; } public RiskIndicator getRiskIndicator() { return RiskIndicator.HIGH_AMOUNT; } }

๐Ÿง  AI + Rule Engine = Power Combo

Let’s say:

  • tanaji gives a score of 0.92 and recommends REJECT

  • dadoji runs and says "Wait, it’s high amount, but merchant is whitelisted"

→ The system now has explainable override logic
→ Logs every decision
→ Helps humans audit, trust, and refine the system


๐Ÿ›ก️ Trivia: Who Was Dadoji Konddev?

  • ๐Ÿ“œ He was appointed as administrator of Pune Jagir under Shahaji (Shivaji’s father).

  • ๐Ÿง  Played a formative role in Shivaji’s education, strategy, and administrative foundations.

  • ๐Ÿน Ran the estate with fairness and discipline — no emotion, just principle.

  • ๐Ÿ›️ A rare combination of mentor, manager, and tactician.

In our system, Dadoji is the guardian of fairness, applying laws and boundaries before emotions or instinct kick in.


๐Ÿ” When Rules Beat AI

Real-world examples:

  • AI thinks it’s safe? Business says “No international payments on weekends.”

  • AI misses pattern? Rule says “Block transactions from blacklisted IPs.”

By combining these two, we get:

  • ✅ Predictability

  • ✅ Customizability

  • ✅ Trustworthy explainability


✅ What’s Done

  • Java-based modular Rule System

  • Interfaces to add custom rules easily

  • Enum-driven RiskIndicator system

  • Seamless integration with sindhudurg response


๐Ÿงฑ What’s Next?

๐ŸŽฏ We’ll soon work on santaji — the feedback loop.
It will learn from false positives/negatives and feed back into tanaji.

After that:

  • ๐Ÿ“ฉ Real-time alerts (via push/SMS)

  • ๐Ÿ›ก️ Security hardening

  • ๐Ÿ“Š Admin dashboard for observability


๐Ÿง  Want to Try Adding a Rule?

Clone the repo and add your own:

java

public class VelocityCheckRule implements FraudRule { // Flag too many transactions in short time }

We'll even accept solid rule contributions via PR!


๐Ÿ”— GitHub Repo

๐Ÿ“ฆ https://github.com/pcm1984/fraud-free-swarajya


๐Ÿ’ฌ Closing Thought

Shivaji Maharaj needed Tanaji on the battlefield...
...but he needed Dadoji to prepare him for it.