Real World Example

Deduplicating UPI Transactions

Payment systems receive the same callback from the bank more than once (retries). A Set of immutable, value-based transaction keys makes processing idempotent: a duplicate is detected by equals/hashCode.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Callback> callbacks = List.of(
                new Callback(new TxnKey("HDFC", "UTR1001"), 500),
                new Callback(new TxnKey("SBI", "UTR2002"), 1200),
                new Callback(new TxnKey("HDFC", "UTR1001"), 500),     // bank retry
                new Callback(new TxnKey("ICICI", "UTR3003"), 75),
                new Callback(new TxnKey("SBI", "UTR2002"), 1200));    // bank retry

        Set<TxnKey> processed = new HashSet<>();
        long credited = 0;
        for (Callback cb : callbacks) {
            if (processed.add(cb.key())) {          // add returns false for duplicates
                credited += cb.amount();
                System.out.println("Credited " + cb.amount() + " for " + cb.key());
            } else {
                System.out.println("Duplicate ignored: " + cb.key());
            }
        }
        System.out.println("Total credited: " + credited);
    }
}

record TxnKey(String bank, String utr) {}
record Callback(TxnKey key, long amount) {}

Output

Credited 500 for TxnKey[bank=HDFC, utr=UTR1001]
Credited 1200 for TxnKey[bank=SBI, utr=UTR2002]
Duplicate ignored: TxnKey[bank=HDFC, utr=UTR1001]
Credited 75 for TxnKey[bank=ICICI, utr=UTR3003]
Duplicate ignored: TxnKey[bank=SBI, utr=UTR2002]
Total credited: 1775

In Production

Note: Across many servers the "processed" set lives in the database: a unique constraint on (bank, utr) makes the second insert fail, which is the same idea at the storage level.