<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samuelgbenga on Medium]]></title>
        <description><![CDATA[Stories by Samuelgbenga on Medium]]></description>
        <link>https://medium.com/@samuelgbenga972?source=rss-e791994f242------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*y-M5VAJPQAY1UuYE</url>
            <title>Stories by Samuelgbenga on Medium</title>
            <link>https://medium.com/@samuelgbenga972?source=rss-e791994f242------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:06:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samuelgbenga972/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Do Supermarkets Use POS Terminals Instead of Bank Transfers?]]></title>
            <link>https://medium.com/@samuelgbenga972/why-do-supermarkets-use-pos-terminals-instead-of-bank-transfers-11048144c35f?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/11048144c35f</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[banking-technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 00:49:01 GMT</pubDate>
            <atom:updated>2026-10-22T00:51:27.480Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Do Supermarkets Use POS Terminals Instead of Bank Transfers? Understanding the Engineering Behind Payment Gateways</h3><p><em>An exploration of how payment gateways work, why businesses need them, and the technology powering modern financial transactions.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSYJeIyEvLhrhkJwwPaBUw.png" /></figure><p>Imagine walking into a supermarket in Lagos.</p><p>You pick up a few groceries, head to the checkout counter, and the cashier tells you your bill is ₦25,000.</p><p>You open your banking application, transfer ₦25,000 directly to the supermarket’s bank account, and show the cashier your debit notification.</p><p>Simple, right?</p><p>But here is an interesting question:</p><p><strong>Why don’t supermarkets simply accept payments into their regular bank accounts instead of investing in POS terminals, payment gateways, and other payment infrastructure?</strong></p><p>After all, money is money. Whether it arrives through a bank transfer or a POS terminal, the supermarket eventually receives the same ₦25,000.</p><p>The answer reveals something fascinating about financial technology.</p><p><strong>Receiving money is only one part of processing a payment.</strong></p><p>Businesses also need to identify who paid, verify that the money arrived, match payments to purchases, prevent fraud, and reconcile thousands of transactions.</p><p>This is where payment gateways come into play.</p><p>In this article, we’ll explore how payment gateways work, the difference between gateways and processors, the technologies that power them, and some important considerations when designing payment systems.</p><h3>1. The Problem Payment Gateways Were Built to Solve</h3><p>Before modern electronic payment systems became widespread, businesses relied heavily on cash, cheques, bank deposits, and manual transfers.</p><p>Consider a supermarket processing 500 transactions daily.</p><p>If every customer pays through a regular bank transfer, the cashier must verify each payment before releasing the goods.</p><p>This introduces several problems.</p><h3>Problem 1: Payment verification</h3><p>A customer claims to have transferred ₦15,000.</p><p>How does the cashier know the payment was successful?</p><p>A debit notification on the customer’s phone does not necessarily prove that the merchant received the money.</p><p>The cashier needs confirmation from the merchant’s own bank or payment system.</p><h3>Problem 2: Payment identification</h3><p>Imagine five customers transferring exactly ₦10,000 within the same minute.</p><p>Which transfer belongs to which customer?</p><p>Without a reliable reference or payment-matching mechanism, identifying individual transactions becomes difficult.</p><h3>Problem 3: Fraud</h3><p>A customer might present a fake transfer receipt or a misleading debit notification.</p><p>If the cashier releases the goods without independently verifying the payment, the business risks losing money.</p><h3>Problem 4: Reconciliation</h3><p>At the end of the business day, the supermarket needs to answer several questions:</p><ul><li>How many transactions were completed?</li><li>How much money was received?</li><li>Which payments belong to which sales?</li><li>Were there failed or reversed transactions?</li><li>Does the amount received match the amount recorded by the sales system?</li></ul><p>Without payment infrastructure, answering these questions can become a tedious accounting exercise.</p><h3>How payment gateways help</h3><p>A properly integrated payment system can associate a transaction with an order, customer, cashier, terminal, or branch.</p><p>It can also provide structured payment statuses, transaction references, and settlement records.</p><p>Traditional bank transferIntegrated payment systemCashier manually checks paymentMerchant receives payment confirmationDifficult to identify similar transfersTransactions are linked to specific ordersCustomer may present fake proofMerchant verifies through a trusted channelReconciliation requires manual effortTransaction reports support reconciliationPayment amount may be incorrectExpected amount can be specifiedLimited transaction trackingReferences and audit trails are available</p><p>Of course, POS terminals and payment gateways are not immune to network failures, fraud, or delayed confirmations.</p><p>However, they provide a more structured approach to managing payments at scale.</p><p><strong>The real value of payment infrastructure is not merely moving money. It is making payments identifiable, verifiable, traceable, and manageable.</strong></p><h3>2. What Exactly Is a Payment Gateway?</h3><p>A payment gateway is a technology platform that enables businesses to securely accept and manage electronic payments.</p><p>Think of it as a bridge connecting a customer, a merchant, and the financial institutions or payment providers responsible for processing the transaction.</p><p>For example, when a customer pays for an item on an e-commerce website, the payment gateway may:</p><ol><li>Receive the payment request.</li><li>Validate the transaction details.</li><li>Securely transmit payment information.</li><li>Route the request to the appropriate processor or payment provider.</li><li>Receive the transaction response.</li><li>Communicate the payment status to the merchant.</li><li>Store relevant transaction records for reporting and reconciliation.</li></ol><p>The exact responsibilities depend on the gateway’s architecture and business model.</p><p>Some gateways focus mainly on securely collecting and forwarding payment information. Others provide a much broader platform, including fraud prevention, merchant onboarding, virtual accounts, reporting, and reconciliation.</p><h3>Payment gateway versus payment processor</h3><p>These terms are often used interchangeably, but they represent different responsibilities.</p><p><strong>Payment Gateway</strong></p><p>The gateway provides the integration and orchestration layer through which merchants initiate and manage payments.</p><p><strong>Payment Processor</strong></p><p>The processor handles transaction-processing functions and communicates with the relevant financial infrastructure to facilitate authorization, clearing, or other payment operations.</p><p>In some payment ecosystems, a single company provides both services.</p><p>A simplified card-payment flow looks like this:</p><pre>Customer<br>   |<br>   v<br>Merchant Website / POS<br>   |<br>   v<br>Payment Gateway<br>   |<br>   v<br>Payment Processor / Acquirer<br>   |<br>   v<br>Card Network<br>   |<br>   v<br>Customer&#39;s Issuing Bank<br>   |<br>   v<br>Authorization Response</pre><p>The response travels back through the payment infrastructure to the merchant.</p><p>This diagram is deliberately simplified. Actual routing depends on the payment method, card scheme, processor, and acquiring arrangement.</p><h3>Issuing bank versus acquiring bank</h3><p>Two important participants in card payments are the issuing bank and the acquiring bank.</p><p>InstitutionRepresentsResponsibilityIssuing bankCustomerIssues the customer’s card and authorizes or declines transactionsAcquiring bankMerchantEnables merchants to accept card payments and supports settlement</p><p>Understanding this distinction is essential when investigating card-payment failures.</p><p>For example, a declined transaction might originate from the issuing bank rather than the merchant’s gateway.</p><h3>3. Why Payment Gateways Evolve Faster Than Payment Processing Infrastructure</h3><p>One interesting characteristic of the payment industry is that customer-facing payment experiences evolve rapidly, while many underlying financial protocols remain relatively stable.</p><p>Consider how customers can pay today:</p><ul><li>Debit and credit cards</li><li>Bank transfers</li><li>QR codes</li><li>Mobile wallets</li><li>USSD</li><li>Contactless payments</li><li>Payment links</li><li>Hosted checkout pages</li></ul><p>These experiences continue to evolve with consumer behavior and technology.</p><p>However, many underlying payment networks still rely on established financial messaging standards, strict security requirements, and carefully controlled integrations.</p><p>For example, ISO 8583 remains relevant in card-payment systems, while ISO 20022 is increasingly important across modern financial messaging infrastructure.</p><p>Why does this matter?</p><p>Because financial systems prioritize interoperability, reliability, security, and predictable behavior.</p><p>A customer-facing payment gateway might be built with Java, Go, Node.js, Python, or another suitable technology.</p><p>The choice of programming language does not fundamentally determine whether money can move between financial institutions.</p><p>What matters is how reliably and securely the gateway integrates with the appropriate payment infrastructure.</p><p>A well-designed gateway should therefore separate rapidly evolving customer-facing functionality from the more stable financial integrations beneath it.</p><p>This is an important architectural principle for payment engineers.</p><h3>4. Understanding the Different Payment Channels</h3><p>A payment gateway can support multiple payment channels.</p><p>A payment channel describes the method through which a customer initiates or completes a payment.</p><p>Some common channels include:</p><h3>Card payments</h3><p>Customers pay using debit, credit, prepaid, or virtual cards.</p><p>The payment typically involves card networks, processors, acquiring institutions, and issuing banks.</p><h3>Bank transfer / Pay with Transfer</h3><p>The customer transfers money to a designated bank account.</p><p>Modern implementations may use virtual accounts to associate incoming payments with specific customers or transactions.</p><h3>USSD payments</h3><p>Customers initiate payments through short banking codes, often without needing a smartphone application.</p><h3>Wallet payments</h3><p>Customers pay using balances held in digital wallets or supported payment applications.</p><h3>QR payments</h3><p>Customers scan a QR code to initiate or complete a transaction.</p><h3>POS and contactless payments</h3><p>Customers pay through physical terminals using cards, contactless devices, or other supported payment methods.</p><h3>Payment links and hosted checkout</h3><p>Merchants generate payment links or direct customers to hosted checkout pages.</p><h3>Recurring payments</h3><p>Businesses collect recurring payments using authorized mandates or securely stored payment tokens.</p><p>In Nigeria, commonly encountered payment methods include bank transfers, cards, USSD, POS transactions, wallets, and payment links.</p><p>An important distinction is that not everything listed as a payment channel is technically a separate payment rail.</p><p>For example, a hosted checkout page is a payment interface that may support multiple underlying channels.</p><p>Similarly, a payment link can lead to a checkout experience where the customer chooses between cards and bank transfers.</p><h3>5. Virtual Accounts: How Payment Gateways Identify Incoming Transfers</h3><p>Let’s return to our supermarket example.</p><p>Suppose a business receives hundreds of bank transfers daily.</p><p>How can it automatically identify which customer made each payment?</p><p>One approach is the use of virtual accounts.</p><p>A virtual account is an account number associated with a customer, merchant, or payment transaction for collection and reconciliation purposes.</p><p>Depending on the provider, a virtual account may be temporary or permanently assigned.</p><h3>Example</h3><p>Imagine a customer wants to pay ₦35,000 for an online order.</p><p>The merchant’s payment gateway creates a payment request and obtains a virtual account from its banking or collection provider.</p><pre>Order ID: ORD-2026-001<br>Amount: NGN 35,000<br>Virtual Account: 1234567890<br>Payment Status: PENDING</pre><p>The customer transfers ₦35,000 to the provided account.</p><p>When the banking infrastructure processes the incoming transfer, the payment provider sends a notification to the gateway.</p><p>The gateway can then associate the incoming payment with the appropriate order.</p><pre>Customer transfers money<br>          |<br>          v<br>Virtual Account<br>          |<br>          v<br>Bank / Collection Provider<br>          |<br>          v<br>Payment Notification<br>          |<br>          v<br>Payment Gateway<br>          |<br>          v<br>Match Payment to Order<br>          |<br>          v<br>Update Order Status</pre><p>In a production system, receiving a notification should not automatically mean that the payment is trusted.</p><p>The gateway must verify the notification’s authenticity, validate the payment amount and reference, and handle duplicate notifications safely.</p><h3>Virtual account versus transaction session ID</h3><p>These are two different concepts.</p><p><strong>Virtual Account Number:</strong> Identifies a receiving account or payment collection arrangement.</p><p><strong>Transaction Session ID:</strong> Identifies a particular transfer within a banking or payment network.</p><p>For example, in a Nigerian interbank transfer integration, a session ID can be used to trace the transaction, query its status, and investigate failed or disputed transfers.</p><p>The session ID is associated with the transfer transaction, not the virtual account itself.</p><p>Its generation point depends on the payment network’s protocol and implementation. It should not be assumed that a session ID is always generated only after the money has moved.</p><p>This distinction is particularly important when designing transaction-status-query and reconciliation services.</p><h3>6. The Core Components of a Payment Gateway</h3><p>From a software engineering perspective, a payment gateway is much more than an API endpoint that receives payment requests.</p><p>A production payment platform typically needs several important capabilities.</p><h3>Payment initiation</h3><p>The system creates a payment request with the correct amount, currency, customer information, and transaction reference.</p><h3>Payment routing</h3><p>The gateway determines which payment processor, bank, switch, or integration should handle the transaction.</p><h3>Payment confirmation</h3><p>The system obtains a reliable response indicating whether the transaction succeeded, failed, or remains pending.</p><h3>Transaction tracking</h3><p>Every transaction should have a traceable lifecycle.</p><p>For example:</p><pre>CREATED<br>   |<br>   v<br>PENDING<br>   |<br>   +------&gt; SUCCESS<br>   |<br>   +------&gt; FAILED<br>   |<br>   +------&gt; EXPIRED</pre><p>Real systems may also require additional states for authorization, capture, reversal, refund, or settlement.</p><h3>Notifications</h3><p>Merchants and customers need updates when transaction states change.</p><p>These notifications may be delivered through webhooks, email, SMS, or application events.</p><h3>Reconciliation</h3><p>The gateway compares internal transaction records with information obtained from banks, processors, or settlement providers.</p><p>This helps identify missing payments, duplicate records, and discrepancies.</p><h3>Settlement</h3><p>Settlement involves transferring or making funds available to the appropriate merchant according to the relevant payment arrangement.</p><p>A successful customer payment does not necessarily mean that the merchant has already received its final settlement.</p><h3>Dispute and refund management</h3><p>The system needs mechanisms for tracking refunds, reversals, failed transactions, and payment disputes.</p><p>Together, these components turn a simple payment interface into a reliable financial platform.</p><h3>7. Security: The Most Important Responsibility of a Payment Gateway</h3><p>Payment systems handle sensitive financial information.</p><p>Consequently, security cannot be treated as an optional feature.</p><p>A gateway must protect information during transmission, processing, and storage.</p><p>Several technologies are particularly important.</p><h3>TLS and HTTPS</h3><p>Transport Layer Security protects communication between clients and servers.</p><p>It helps prevent attackers from reading or modifying sensitive information while it travels across networks.</p><h3>AES encryption</h3><p>The Advanced Encryption Standard is commonly used to encrypt sensitive data.</p><p>Payment systems may use AES to protect information stored in databases or exchanged between trusted components.</p><p>Secure encryption requires an appropriate mode of operation, correct key handling, and proper management of initialization values or nonces.</p><h3>RSA and elliptic-curve cryptography</h3><p>Public-key cryptography supports capabilities such as digital signatures, secure key establishment, and certificate-based authentication.</p><h3>HMAC and digital signatures</h3><p>These mechanisms help verify message authenticity and integrity.</p><p>For example, a payment gateway can use an HMAC signature to verify that a webhook genuinely originated from a trusted payment provider and has not been modified.</p><h3>Tokenization</h3><p>Tokenization replaces sensitive payment information with a token.</p><p>Instead of repeatedly exposing a customer’s card number, a payment platform can reference a securely managed token.</p><h3>Hardware Security Modules</h3><p>An HSM is specialized hardware designed to protect cryptographic keys and perform sensitive cryptographic operations.</p><p>HSMs are particularly important in certain card-processing and banking environments.</p><h3>PCI DSS</h3><p>The Payment Card Industry Data Security Standard establishes security requirements for environments that store, process, or transmit payment card data.</p><p>PCI DSS compliance is especially important for systems handling cardholder information.</p><h3>CVV and sensitive authentication data</h3><p>The Card Verification Value helps verify card information in certain card-not-present transactions.</p><p>A crucial rule is that sensitive authentication data such as CVV must not be stored after authorization, even if encrypted.</p><h3>Other important security concepts</h3><p>Payment engineers should also understand:</p><ul><li>Mutual TLS (mTLS)</li><li>PIN block encryption</li><li>DUKPT key management</li><li>3-D Secure authentication</li><li>Digital certificates</li><li>Secure key management</li><li>API authentication and authorization</li><li>Fraud detection and transaction monitoring</li></ul><p>One interesting detail is the Luhn algorithm, which is used to detect certain errors in identification numbers, including payment card numbers.</p><p>However, passing a Luhn check does not prove that a card is genuine, active, or authorized for payment.</p><h3>8. Designing a Payment Gateway: A Software Engineer’s Perspective</h3><p>If you were asked to design a payment gateway today, where would you start?</p><p>A common mistake would be to begin immediately with the programming language, database, or microservices architecture.</p><p>But before choosing technologies, you need to understand the payment lifecycle.</p><p>Some important design questions include:</p><p><strong>Payment processing:</strong> How will transactions be initiated, routed, and confirmed?</p><p><strong>Reliability:</strong> What happens when a processor times out after receiving a payment request?</p><p><strong>Idempotency:</strong> How will the system prevent duplicate financial operations when a merchant retries a request?</p><p><strong>Transaction state:</strong> How will the system distinguish between pending, successful, failed, and reversed payments?</p><p><strong>Security:</strong> How will sensitive information and cryptographic keys be protected?</p><p><strong>Reconciliation:</strong> How will the gateway detect differences between its internal records and the processor’s records?</p><p><strong>Extensibility:</strong> How easily can new banks, switches, or payment providers be integrated?</p><p>A simplified architecture could look like this:</p><pre>Merchant Applications<br>                      |<br>                      v<br>                API Gateway<br>                      |<br>                      v<br>             Payment Service<br>                      |<br>           +----------+----------+<br>           |                     |<br>           v                     v<br>    Transaction Store      Payment Router<br>                                 |<br>                  +--------------+-------------+<br>                  |              |             |<br>                  v              v             v<br>             Bank API       Card Processor   Wallet API<br>                  |              |             |<br>                  +--------------+-------------+<br>                                 |<br>                                 v<br>                       Payment Responses<br>                                 |<br>                                 v<br>                       Transaction Updates<br>                                 |<br>                  +--------------+-------------+<br>                  |                            |<br>                  v                            v<br>          Notification Service       Reconciliation Service</pre><p>This is a conceptual architecture rather than a complete production blueprint.</p><p>For instance, a real implementation would also need robust authentication, observability, webhook verification, retry policies, audit logging, and secure credential management.</p><h3>Why extensibility matters</h3><p>Imagine integrating three payment providers today.</p><p>Six months later, the business wants to support a fourth provider.</p><p>You should not need to rewrite the entire payment-processing application.</p><p>This is where software design principles such as the Open/Closed Principle become valuable.</p><p>For example, in Java, you might define a common processor contract:</p><pre>public interface PaymentProcessor {<br>PaymentResponse process(<br>        PaymentRequest request<br>    );<br>}</pre><p>Each integration provides its own implementation:</p><pre>public class BankTransferProcessor<br>        implements PaymentProcessor {<br>@Override<br>    public PaymentResponse process(<br>            PaymentRequest request) {<br>        // Integrate with bank transfer provider<br>        return null;<br>    }<br>}</pre><pre>public class CardPaymentProcessor<br>        implements PaymentProcessor {<br>@Override<br>    public PaymentResponse process(<br>            PaymentRequest request) {<br>        // Integrate with card processor<br>        return null;<br>    }<br>}</pre><p>These are illustrative skeletons, not production-ready payment implementations.</p><p>A routing component can then select the appropriate processor using a Strategy pattern, factory, or dependency-injection-based registry.</p><p>The advantage is that new integrations can be introduced with minimal changes to existing business logic.</p><p>This approach also makes integrations easier to test, mock, and maintain.</p><h3>9. Mobile POS: How Payment Acceptance Became More Accessible</h3><p>Traditionally, accepting card payments often required dedicated payment terminals and merchant-acquiring arrangements.</p><p>Mobile Point of Sale, or mPOS, helped make card acceptance more portable.</p><p>Consider a small food vendor who operates at different locations.</p><p>Instead of relying on a fixed checkout terminal, the vendor can use a compatible card reader connected to a smartphone or tablet.</p><p>One well-known example is Square’s mobile card-reader ecosystem.</p><p>This approach combines portable hardware, mobile applications, secure card-data capture, and payment-processing infrastructure.</p><p>The innovation is not necessarily a completely new banking network.</p><p>Rather, it is a more accessible way of interacting with existing payment infrastructure.</p><p>This illustrates a broader lesson:</p><p><strong>Innovation in payments often happens at the interface and orchestration layers, even when the underlying financial rails remain the same.</strong></p><h3>10. White-Label Payment Gateways: Building Once, Serving Multiple Brands</h3><p>Another interesting concept in the fintech industry is white-label payment infrastructure.</p><p>A white-label payment gateway is a payment platform developed by one company but customized and offered under another company’s branding.</p><p>Imagine Company A builds a payment gateway.</p><p>Company B wants to offer payment services to its merchants but does not want to develop the entire infrastructure from scratch.</p><p>Company B licenses the platform from Company A and launches it under the brand name B-Pay.</p><p>To merchants, the platform appears as B-Pay.</p><p>Behind the scenes, Company A may still provide much of the underlying technology.</p><p>This business model allows organizations to introduce branded financial products without independently building every technical component.</p><p>However, branding does not eliminate regulatory, security, contractual, or operational responsibilities.</p><p>Those obligations depend on the arrangement between the technology provider, the branded company, and the regulated financial institutions involved.</p><h3>11. Why Understanding Payment Infrastructure Matters for Software Engineers</h3><p>For developers interested in fintech, understanding payment gateways is an excellent starting point.</p><p>But knowing how to call a payment API is only the beginning.</p><p>The more interesting engineering problems appear when transactions do not behave as expected.</p><p>Consider these scenarios:</p><p>A merchant sends a payment request.</p><p>The processor receives it and successfully completes the transaction.</p><p>However, the gateway experiences a network timeout before receiving the response.</p><p>Should the gateway retry the payment immediately?</p><p>What if retrying creates a duplicate debit?</p><p>Or imagine a webhook is delivered three times.</p><p>Should the system process the payment notification three times?</p><p>What happens when a payment succeeds but the merchant’s application crashes before updating the order?</p><p>These are the kinds of problems that make payment engineering challenging.</p><p>They introduce concepts such as:</p><ul><li>Idempotency and duplicate prevention</li><li>Transaction status queries</li><li>Retry strategies</li><li>Event-driven processing</li><li>Asynchronous notifications</li><li>Reconciliation</li><li>Distributed system consistency</li><li>Auditability and observability</li></ul><p>For backend engineers, these problems demonstrate why payment systems require more than clean REST APIs.</p><p>They require careful thinking about uncertainty, failure recovery, and financial correctness.</p><h3>12. Final Thoughts: Payment Gateways Are About Trust, Not Just Transactions</h3><p>Let’s return to the question that started this discussion.</p><p>Why do supermarkets use POS terminals and payment gateways instead of relying entirely on ordinary bank transfers?</p><p>Because collecting money is not the same as managing payments.</p><p>A supermarket needs to know whether a payment was completed, which customer made it, which sale it belongs to, and whether the transaction can be reliably traced.</p><p>At scale, the business also needs reporting, reconciliation, fraud controls, and predictable operational processes.</p><p>Payment gateways and integrated payment infrastructure help solve these problems.</p><p>And from a software engineering perspective, this is what makes the field fascinating.</p><p>Behind a seemingly simple payment confirmation are multiple systems communicating across banks, processors, networks, databases, and merchant applications.</p><p>The customer sees a successful payment.</p><p>The engineer sees transaction routing, security, state management, failure recovery, and reconciliation.</p><p><strong>The next time you tap your card, scan a QR code, or complete a bank transfer at checkout, remember that the most important part of the experience is not simply sending money. It is ensuring that every participant can reliably understand what happened to that money.</strong></p><h3>Further Reading</h3><p>For anyone interested in exploring payment gateways and financial infrastructure further, these resources provide useful starting points:</p><ol><li><a href="https://stripe.com/en-sg/resources/more/payment-gateways-101">Stripe — Payment Gateways 101</a></li><li><a href="https://www.investopedia.com/terms/p/payment-gateway.asp">Investopedia — Payment Gateway</a></li><li><a href="https://monnify.com/blog/what-is-a-payment-gateway-how-to-choose-the-right-one-for-your-business">Monnify — What Is a Payment Gateway?</a></li><li><a href="https://www.flutterwave.com/us/blog/types-of-payment-gateways-in-nigeria">Flutterwave — Types of Payment Gateways in Nigeria</a></li><li><a href="https://www.jpmorgan.com/insights/treasury/treasury-management/payment-gateways-what-they-are-and-how-to-choose-one">J.P. Morgan — Understanding Payment Gateways</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11048144c35f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotent Operation and Atomic Transaction Part 2]]></title>
            <link>https://medium.com/@samuelgbenga972/idempotent-operation-and-atomic-transaction-part-2-145cb002438e?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/145cb002438e</guid>
            <category><![CDATA[atomicity]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[enterprise-software]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[idempotency]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 08:33:14 GMT</pubDate>
            <atom:updated>2026-02-20T08:33:14.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydKMwBmrQ2MXowBwlHREYA.png" /></figure><p>If you’ve ever built a payment system, API service, or any distributed application, you’ve probably encountered two fundamental concepts: <strong>idempotency</strong> and <strong>atomicity</strong>, but still haven’t quite been able to wrap your head around them.</p><p>Let me walk you through the curiosity that finally made it click for me personally.</p><h3>The Question That Started It All</h3><p>Picture this: You’re designing a payment processing system. You know you need:</p><ul><li><strong>Atomicity</strong> to ensure transactions either complete fully or not at all</li><li><strong>Idempotency</strong> to handle duplicate requests safely</li></ul><p>But then you realize something unsettling:</p><blockquote><em>Idempotency expects one consistent result every time. But atomicity can produce two outcomes: </em><strong><em>commit</em></strong><em> or </em><strong><em>rollback</em></strong><em>.</em></blockquote><p>It was at this moment I knew something was not adding up.</p><p>To resolve, further research must be done my dear Reader. Let’s delve.</p><h3>The Layers Matter More Than You Think</h3><p>Here’s the first crucial insight: <strong>idempotency </strong>and<strong> atomicity operate at different layers</strong>.</p><p><strong>Atomicity</strong> is bottom-level. It lives in your database, your transaction log, your state machine. It answers one question:</p><blockquote><em>“Did this state transition complete cleanly?”</em></blockquote><p><strong>Idempotency</strong> is top-level. It lives in your API contract, your request handling, your business logic. It answers a different question:</p><blockquote><em>“Has this </em>intent<em> already been fulfilled?”</em></blockquote><p>Different questions. Different layers. <strong>Not competitors, Just collaborators on different levels.</strong></p><h3>The leave that breaks the Camel’s back.</h3><p>Most developers assume idempotency means “always return success for the same request.” (atleast I did 😊)</p><p><strong>Well…..</strong></p><p>Idempotency doesn’t promise success. It promises <strong>stability (of consistent failure or success or in-between if there is an inbetween)</strong>.</p><p>For a given idempotency key, once an operation reaches a terminal state, every retry must observe <em>the same terminal outcome</em> — whether that’s:</p><ul><li>✅ Success</li><li>❌ Business failure</li><li>⚠️ Validation rejection</li></ul><p>The terminal state can be a failure. That’s still idempotent.</p><h3>What Atomicity Actually Gives You</h3><p>Here’s where atomicity becomes idempotency’s perfect ally:</p><p>Atomicity guarantees a <strong>clean boundary</strong> between two states:</p><ul><li>“This happened” (commit)</li><li>“This never happened” (rollback)</li></ul><p>No halfway states. No partial writes. No corruption.</p><p>That clean boundary is what lets idempotency answer its question confidently. Without atomicity’s guarantee, idempotency would be guessing about what actually occurred.</p><h3>The Missing Abstraction: Intent State</h3><p>The breakthrough comes when you realize you’re not just tracking <em>database state</em>. You’re tracking <strong>intent state</strong>.</p><p>This introduces a crucial lifecycle:</p><pre>RECEIVED → IN_PROGRESS → SUCCEEDED/FAILED</pre><p>Now the roles become clear:</p><ul><li><strong>Atomicity</strong> governs the transition from IN_PROGRESS to a terminal state</li><li><strong>Idempotency</strong> governs whether retries are allowed and what result gets reused</li></ul><h3>The Production Pattern That Actually Works</h3><p>Here’s how banking systems and payment processors solve this — the pattern that’s been battle-tested at scale:</p><h3>Step 1: Record the Intent</h3><pre>Create idempotency record<br>  - key: unique identifier<br>  - state: IN_PROGRESS<br>  - timestamp: now</pre><h3>Step 2: Execute Atomically</h3><pre>Begin atomic transaction<br>  - Perform all business operations<br>  - Update all necessary state<br>Commit or rollback (atomicity guarantees clean outcome)</pre><h3>Step 3: Lock In the Result</h3><pre>If transaction commits:<br>  - Update idempotency record → SUCCEEDED<br>  - Store the response payload<br>  <br>If transaction rolls back:<br>  - Update idempotency record → FAILED<br>  - Store the failure reason</pre><h3>Step 4: Handle Retries</h3><pre>On subsequent requests with same key:<br>  - If SUCCEEDED → return stored success response<br>  - If FAILED → return stored failure response<br>  - If IN_PROGRESS → reject or wait (operation ongoing)</pre><h3>The Critical Rule That Prevents Bugs</h3><p>Here’s the rule that prevents the “halfway failure” scenario:</p><blockquote><strong><em>Never respond before atomicity resolves.</em></strong></blockquote><p>If your transaction fails, that failure <em>is</em> your idempotent outcome. Retries must see the same failure.</p><p>If your process crashes before recording the outcome? The idempotency record stays IN_PROGRESS, and the retry can safely re-attempt.</p><h3>The One-Sentence Mental Model</h3><p>After all this complexity, here’s the simplest way to think about it:</p><blockquote><strong><em>Atomicity ensures clean state transitions; idempotency ensures those transitions are observed only once.</em></strong></blockquote><p>They’re not rivals. They’re orthogonal controls that only work correctly <em>together</em>.</p><h3>Why This Matters in Production</h3><p>Understanding this relationship isn’t academic. Here’s what breaks when you get it wrong:</p><p><strong>Mistake 1</strong>: Caching results before atomic commit</p><ul><li>Result: Users see “success” but the transaction rolled back</li><li>Reality: Money disappeared into the void</li></ul><p><strong>Mistake 2</strong>: Not storing failures idempotently</p><ul><li>Result: Retries re-execute failed operations</li><li>Reality: Multiple failed charges, angry customers</li></ul><p><strong>Mistake 3</strong>: Confusing “no duplicate execution” with “always success”</p><ul><li>Result: System can’t handle legitimate failures</li><li>Reality: Every failure causes a retry storm</li></ul><h3>The Takeaway</h3><p>Next time you’re designing an API or distributed system, remember:</p><ul><li><strong>Atomicity</strong> decides what happened</li><li><strong>Idempotency</strong> decides what may happen again</li><li><strong>Intent state</strong> bridges them together</li></ul><p>Master this, and you’ll build systems that handle the chaos of the real world: network failures, duplicate requests, crashes mid-transaction, and all the beautiful mess that comes with distributed computing.</p><p>Because in the end, robust systems aren’t built by avoiding complexity. They’re built by understanding exactly where different guarantees meet — and designing for that intersection with precision.</p><p><em>Have you encountered this tension in your own systems? What patterns have you found that work? I’d love to hear your experiences in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=145cb002438e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotent Operation and Atomic Transaction Part 1]]></title>
            <link>https://medium.com/@samuelgbenga972/idempotent-operation-and-atomic-transaction-part-1-96a54f8c3175?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a54f8c3175</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[atomic-operation]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 05:02:26 GMT</pubDate>
            <atom:updated>2026-02-09T05:02:26.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydKMwBmrQ2MXowBwlHREYA.png" /></figure><p>It’s crazy how some things look very innocent at the surface level, but once you go deeper, you realize how complicated — and yet calm — they really are. But it gets better, dear reader.</p><p>So, what is an <strong>idempotent operation</strong>?</p><p>An idempotent operation is one where making the same request <strong>N times</strong> results in the <strong>same final state</strong> as making it once. Simple, right? As we go on, we’ll answer some tough questions that might just be eye-opening.</p><p>Let’s clear this up early: <strong>idempotency does not naturally apply to an initial POST request</strong>. The reason is simple — POST creates a new record, and each creation results in a new, unique resource. That alone breaks the idea of getting the same result every time.</p><p>For example:</p><pre>POST /posts<br>{ &quot;title&quot;: &quot;Hello World&quot; }</pre><p>If you send this twice, you usually get:</p><ul><li>Post A</li><li>Post B</li></ul><p>Two different resources → not idempotent.</p><p>However, idempotency <em>does</em> come into play when <strong>the same request is sent more than once</strong>, often due to retries. Once an object has already been created, you don’t want to recreate it. Ideally, this is where a <strong>PUT</strong> operation fits better than POST, since PUT is idempotent by design.</p><p>If, for any reason, a client still uses POST for an already existing resource, idempotency logic should treat that request like a PUT — returning the same result every time, as long as the object already exists and remains in the same state.</p><blockquote><strong>Note: An operation is idempotent if making the same request N times results in the same final state as making it once.</strong></blockquote><p>One key problem idempotency solves is <strong>preventing duplicate entries during retries</strong>. While this can be handled on its own, a more robust, enterprise-grade approach combines <strong>idempotency with atomic transactions</strong>. Understanding how these two concepts work together provides a clearer and more reliable way to handle retries at scale.</p><p>We’ll introduce <strong>atomic operations</strong> in Part Two of this series, so hold your horses — or better yet, don’t worry about it too much for now 🙂</p><p>So let’s look at idempotency through the <strong>lens of retries</strong>. What usually causes a retry in the first place?</p><ul><li>Network timeouts</li><li>Client didn’t get a response</li><li>Load balancer retries</li><li>Mobile clients retrying automatically</li></ul><p>The server may have already processed the request — the client just doesn’t know.</p><h3>How Idempotency Solves Retries for POST</h3><p><strong>Key idea:</strong> POST can be made idempotent <strong>by design</strong>, even though it isn’t idempotent by default. However, this applies <strong>only to subsequent retries of the same POST request for the same data</strong>, not the initial creation itself.</p><h3>The Trick: Idempotency Keys</h3><p>Client sends a unique key with the request:</p><pre>POST /posts<br>Idempotency-Key: 8f9c2c9a</pre><p><strong>Server logic:</strong></p><ol><li>Check if this key already exists</li><li>If yes → return the previously created post</li><li>If no → create the post, store the key + result</li></ol><p>So:</p><ul><li>First request → creates post</li><li>Retry with same key → no new post, same response</li></ul><p><strong>Final state is the same → idempotent behavior</strong></p><p>This is how big enterprise solutions handle retries.</p><h3>HTTP Method Angle (Very Important)</h3><ul><li><strong>GET</strong> → naturally idempotent</li><li><strong>PUT</strong> → idempotent (replace resource)</li><li><strong>DELETE</strong> → idempotent (delete once or many times = deleted)</li><li><strong>POST</strong> → not idempotent unless you design it that way</li></ul><p>That’s why:</p><ul><li>PUT /posts/{id} is preferred when the client can define the ID</li><li>POST is used when the server generates the ID → needs idempotency keys for safety</li></ul><h3>Spoiler Alert: A little bit about Atomic operation</h3><p>An atomic operation is one that is executed as a single, indivisible unit of work. It either <strong>completes entirely or fails entirely</strong>, leaving the database in a consistent state with no partial changes.<br>Rule of thumb: <strong>Atomicity protects the database; idempotency protects the business meaning of an API call</strong></p><p>But also note that <strong>atomic operations by themselves do not prevent retries from creating new entries</strong>. Below is a sample flow showing how this happens:</p><ol><li>POST request hits server</li><li>Transaction commits successfully</li><li>Response is lost (timeout)</li><li>Client retries</li><li><strong>New transaction runs → new post created</strong></li></ol><p>So yes: <strong>A Atomic operation can still create a new post on every retry</strong></p><p><strong>Atomic Operation ≠ Data Uniqueness.</strong></p><p>Combining both concepts gives you a <strong>more stable system</strong> that prevents duplicate entries — an error so dreaded in financial transactions that you really don’t that.</p><p>While <strong>atomic operations</strong> ensure that transaction results are consistent in the database, <strong>idempotency adds memory to the system</strong> — allowing it to track the persistent state of a request and return the correct response.</p><p>We’ll be diving deeper into this topic in the next part of the series. Stay tuned 🚀</p><p><em>Have questions or thoughts? Drop a comment below or follow me for more backend engineering deep dives.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a54f8c3175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HashMap vs ConcurrentHashMap]]></title>
            <link>https://medium.com/@samuelgbenga972/hashmap-vs-concurrenthashmap-a77190cbc16a?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/a77190cbc16a</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[concurrenthashmap]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashmap-in-java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 13:10:47 GMT</pubDate>
            <atom:updated>2026-02-07T13:10:47.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTudmHeTuTG4p81PgAwOUw.png" /></figure><p>Before we look into the “vs”, it’s important to understand their relationship with their parent. This gives us a broader view of where they come from and why you mostly see codebases implement them the way they do. Let’s dive in.</p><p>In Java, Map is an <strong>interface</strong>, not a concrete class. It defines <em>what</em> a key–value data structure should do (store, retrieve, update entries), but it does not define <em>how</em> those operations are implemented. Concrete classes such as HashMap, ConcurrentHashMap, TreeMap, and LinkedHashMap are the actual implementations. Each of them provides different behavior with its own pros and cons.</p><h3>Flow of the relationship</h3><pre>Map (interface)<br>               |<br>   --------------------------------<br>   |              |               |<br>HashMap   ConcurrentHashMap   TreeMap</pre><p>Your code interacts with the Map interface, while the JVM works with a chosen implementation underneath, abstracting away the complexity of how things work internally. In fact, when you inspect the interface itself, you’ll mostly see method declarations with empty bodies. That’s the beauty of abstraction.</p><h3>2. Why Initialize With Map and Assign an Implementation</h3><p>Declaring variables using the Map interface instead of a concrete class leads to <strong>loose coupling</strong>, better <strong>scalability</strong>, and easier <strong>maintenance</strong>.</p><h3>Why this is important</h3><ul><li>You can swap implementations without touching business logic</li><li>Code becomes easier to test and refactor</li><li>It follows the principle: <em>program to an interface, not an implementation</em></li></ul><h3>Example</h3><pre>Map&lt;String, Integer&gt; scores = new HashMap&lt;&gt;();</pre><p>Later, if concurrency becomes a concern:</p><pre>Map&lt;String, Integer&gt; scores = new ConcurrentHashMap&lt;&gt;();</pre><p>✔ Only one line changes<br>✔ No method rewrites<br>✔ No impact on business logic</p><p>This approach scales well as applications grow from simple, single-threaded systems into complex, multi-threaded ones.</p><h3>3. What Is HashMap?</h3><p>HashMap is a <strong>non-thread-safe</strong> implementation of the Map interface that uses a hash table for fast data access. If you think about it, it isn’t thread-safe because it was not built with multi-threading in mind. It was designed primarily for single-threaded use cases. So yes, it is definitely not thread-safe, and if you plan to do complex multi-threading work, you should use its better sibling.</p><p>Before going further, let’s briefly talk about what a <em>hash table</em> actually is. A hash table may look like a literal table, but it is not. It only gives that perception as a mental model — like the key being in the left column and the value in the right column. With that mental image, it feels like looking up a key simply fetches the corresponding value directly. But that’s a big no.</p><p>It’s okay to hold that view initially, but let’s look at how it actually works.</p><ul><li>The key you put into the map is used to compute a <strong>hash</strong></li><li>That hash is converted into an <strong>index</strong> (this is very important and what gives you the <em>O(1)</em> average-time lookup and insert behavior)</li><li>The index points to a <strong>Node reference</strong></li><li>That Node holds references to the actual <strong>key and value objects in heap memory</strong></li></ul><h3>Key characteristics</h3><ul><li>Allows one null key and multiple null values</li><li>Not synchronized</li><li>Very fast in single-threaded environments</li></ul><h3>Typical use</h3><ul><li>Local caches</li><li>Temporary data storage</li><li>Single-threaded applications</li></ul><h3>4. What Is ConcurrentHashMap?</h3><p>ConcurrentHashMap is a <strong>thread-safe</strong> implementation of the Map interface designed for high-concurrency environments.</p><h3>Key characteristics</h3><ul><li>Does not allow null keys or values</li><li>Uses fine-grained locking and CAS (Compare-And-Swap)</li><li>Supports atomic operations like putIfAbsent, compute, and merge</li><li>High performance under concurrent access</li></ul><h3>Typical use</h3><ul><li>Web servers</li><li>Real-time counters and metrics</li><li>Shared state in multi-threaded applications</li></ul><p>It is very common in interviews to be asked about the difference between HashMap and ConcurrentHashMap, and many people immediately jump to saying “HashMap is not thread-safe.” While that’s true, it’s also important to add this:</p><blockquote><em>We cannot totally blame </em><em>HashMap. It performs very well for single-threaded applications and was probably never built with multi-threading in mind.</em></blockquote><h3>6. Code Samples and Pros &amp; Cons</h3><h3>HashMap Example</h3><pre>Map&lt;String, Integer&gt; likes = new HashMap&lt;&gt;();<br><br>likes.put(&quot;post1&quot;, 1);<br>likes.put(&quot;post1&quot;, likes.get(&quot;post1&quot;) + 1);</pre><h4>Pros</h4><p>- Fast and lightweight<br>- Low memory overhead<br>- Simple API</p><h4>Cons</h4><p>- Not thread-safe<br>- Unsafe in concurrent environments<br>- Can cause data inconsistency</p><h3>ConcurrentHashMap Example</h3><pre>Map&lt;String, Integer&gt; likes = new ConcurrentHashMap&lt;&gt;();<br><br>likes.merge(&quot;post1&quot;, 1, Integer::sum);</pre><h4>Pros</h4><p>- Thread-safe<br>- High performance with multiple threads<br>- Atomic operations prevent race conditions<br>- No global locking</p><h4>Cons</h4><p>- Slightly higher memory usage<br>- Slower in single-threaded scenarios<br>- No ordering guarantees</p><h3>7. Final Conclusion</h3><p>Map provides the <strong>contract</strong>, while classes like HashMap and ConcurrentHashMap provide the <strong>behavior</strong>. Declaring variables using the Map interface keeps your code loosely coupled, scalable, and easy to evolve.</p><ul><li>Use <strong>HashMap</strong> when performance matters and only one thread is involved</li><li>Use <strong>ConcurrentHashMap</strong> when multiple threads access shared data</li></ul><p>There’s a wise saying that sums it all up:</p><blockquote><strong><em>Code to the </em></strong><strong><em>Map interface today so your system can scale tomorrow without painful rewrites.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a77190cbc16a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From H2 to Dockerized Database: Quick Setup with Docker Compose]]></title>
            <link>https://medium.com/@samuelgbenga972/from-h2-to-dockerized-database-quick-setup-with-docker-compose-df8a6145068e?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/df8a6145068e</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 14:58:21 GMT</pubDate>
            <atom:updated>2025-09-06T14:58:21.267Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8w5XHqrP6V8S1UR-uX1Nkw.jpeg" /></figure><p>Oh H2DB, H2DB… you’ve done this to me, and you’ll surely do it to someone else. You worked perfectly fine on my local machine, but the moment we moved to staging — or when another dev tried to run it — you failed us. Team, we all know this story.</p><p>Now, don’t get me wrong. As much as H2DB tries to play the role of a real database, it will never truly be one. But kudos to H2DB — it really does its best. Still, the <em>subtle, not-so-real</em> database quirks can be painfully frustrating.</p><p>Here are some examples I’ve personally stumbled upon:</p><ul><li>Connect with the <strong>wrong username</strong>? H2DB won’t throw an error — it will happily create a new schema instead.</li><li>Try generating an <strong>ERD with DBeaver</strong>? Even if the DB name is wrong, the connection goes through because H2DB quietly creates what doesn’t exist.</li><li>Run into <strong>ID-related issues</strong>? Instead of failing, H2DB might just generate one for you.</li></ul><p>That’s the thing: H2DB is far less strict than a real database. And if you rely on it as your test environment, you’ll likely miss errors that will break your staging or production setup. I’ve been there, and trust me — you don’t want to.</p><p>Especially if you’re using a migration tool like <strong>Flyway</strong>, H2DB is the wrong partner. It can mask problems that come back to bite you later.</p><p>So hear me loud and clear: ❌ <strong>Do not rely only on H2DB for your test environment</strong>. It will spoil something, and you’ll regret it.</p><p>When starting out, many Spring Boot apps use <strong>H2DB</strong> for convenience it’s in-memory, requires zero setup, and wipes clean on restart. But when you’re ready for a more realistic environment, switching to a Dockerized database gives you the same lightweight feel with more real-world experience.</p><p>Here’s how you can get that <strong>“H2-like experience”</strong> using <strong>Docker Compose</strong> a database that spins up with your app and shuts down when your app stops, leaving no persistent data behind.</p><h3>⚙️ Step 1: Add Docker Dependencies</h3><p>In your pom.xml (if using Maven), add:</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-docker-compose&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>This ensures Spring Boot can automatically manage docker-compose lifecycle.</p><h3>📄 Step 2: Create docker-compose.yml</h3><p>Example with <strong>MySQL</strong>:</p><pre>version: &#39;3.9&#39;<br>services:<br>db:<br>image: postgres:17-alpine<br>container_name: myapp-db<br>environment:<br>POSTGRES_DB: testdb<br>POSTGRES_USER: postgres<br>POSTGRES_PASSWORD: postgres<br>ports:<br>- &quot;5433:5432&quot;<br># Remove volumes on shutdown → no data stored<br>tmpfs:<br>- /var/lib/postgresql/data</pre><p>💡 tmpfs makes the DB behave like H2 (all data is in memory, wiped on stop).</p><p>Note: if you want to persist the data this is how you docker-compose will look like instead. This will persist the data even after shut down.</p><pre>version: &#39;3.9&#39;<br>services:<br>db:<br>image: postgres:17-alpine<br>container_name: myapp-db<br>environment:<br>POSTGRES_DB: testdb<br>POSTGRES_USER: postgres<br>POSTGRES_PASSWORD: postgres<br>ports:<br>- &quot;5433:5432&quot; # Map container&#39;s 5432 → host&#39;s 5433<br>volumes:<br>- myapp-data:/var/lib/postgresql/data # ✅ persistent storage<br>volumes:<br>myapp-data: # Named volume</pre><h3>⚡ Step 3: Configure application.properties</h3><pre>spring.datasource.url=jdbc:postgresql://localhost:5433/testdb<br>spring.datasource.username=postgres<br>spring.datasource.password=postgres<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true</pre><h3>▶️ Step 4: Run the App</h3><p>Now run your system how ever you like:</p><p>Spring Boot will:</p><ul><li>Start the db container automatically.</li><li>Connect your app to it.</li><li>Shut it down when your app stops.</li></ul><p>Since we used <strong>tmpfs</strong>, the database clears itself on exit — just like H2.</p><h3>✅ Result</h3><p>You now have:</p><ul><li><strong>Real DB experience</strong> (MySQL/Postgres) instead of H2.</li><li><strong>Zero manual setup</strong> (thanks to Docker Compose + Spring Boot integration).</li><li><strong>Fresh start every run</strong> (no lingering data).</li></ul><p>Perfect for dev/test environments where you want <strong>realistic DB behavior without the setup pain</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df8a6145068e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is AI Replacing Traditional Algorithms?  No. Thought Is Worth the Shot.]]></title>
            <link>https://medium.com/@samuelgbenga972/is-ai-replacing-traditional-algorithms-no-thought-is-worth-the-shot-a6a41e0e2806?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a41e0e2806</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[thoughts-and-ideas]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 14:08:50 GMT</pubDate>
            <atom:updated>2025-06-01T14:08:50.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>💭 Is AI Replacing Traditional Algorithms? No. But the Thought Is Worth the Shot.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcEOyEhR82_j3TDLiBgzBA.png" /><figcaption>gpt</figcaption></figure><p>I sat down today, staring at my screen, lost in a river of thoughts. Among the many that raced through my mind, one stood out:<br>“<em>Is AI replacing traditional algorithms?</em>”</p><p>The answer is simple — No.<br>Yes, the answer is No.</p><p>But the thought itself? It’s worth exploring.</p><h3>🤖 Why This Question Even Arises</h3><p>In today’s world, AI can help us do so many things — often without us needing to think too hard. From content creation to solving LeetCode problems, AI feels like magic.</p><p>But here&#39;s the catch: not everything can or should be delegated to AI. Some problems require deep algorithmic thinking, the kind that can’t be shortcut with pre-trained models.</p><h3>🧠 The Power of Traditional Thinking</h3><p>Based on my experience solving problems on LeetCode and comparing ChatGPT’s answers with those of top users, there’s a pattern:</p><blockquote>The top 5–10 human solutions almost always outperform AI-generated answers when it comes to time and space complexity.</blockquote><p><strong>Why</strong>?</p><p>Because AI typically generates generic solutions — the kind that will work but won’t win contests. It’s not bad — in fact, it’s pretty helpful. But when you want optimal performance, AI rarely beats a seasoned problem solver with a deep understanding of algorithmic trade-offs.</p><h3>📊<strong> AI Needs Data — Algorithms Need You</strong></h3><p>AI is data-driven. It learns from examples.<br>But what happens when:</p><p>The problem is brand new?</p><p>There’s no dataset?</p><p>There’s no prior theory or structure to guide the model?</p><p>In those cases, AI fails. GPT can’t invent proofs or optimal solutions for problems that humanity hasn’t solved — not without data or a framework to reason from.</p><p>That’s where traditional algorithms — and more importantly, your brain — come in.</p><p>There’s a rule of thumb:</p><blockquote>If you can write explicit rules to solve a problem reliably, use a traditional algorithm.<br>If you can’t, and you have data, use AI.</blockquote><p>Also Note:</p><blockquote>AI excels at what is known.<br>Humans still dominate in what is unknown</blockquote><p>🤔 A Robot’s Journey: A Thought Experiment</p><blockquote>I thought about delivery robots. You might think they need complex AI to navigate. But if all they’re doing is moving from Point A to Point B in a static, well-defined environment, then simple “if condition statement” and classic pathfinding algorithms are enough.</blockquote><p><strong><em>Cranes are not AI!</em></strong></p><p>Why complicate what’s already solvable with deterministic logic?</p><p>Ironically, even AI models themselves are built on top of traditional algorithms — from the matrix multiplications in backpropagation to optimization methods like gradient descent. AI is layered on traditional algorithms. It doesn’t replace them. It builds upon them.</p><h3>👨‍💻 Final Thoughts</h3><p>Traditional algorithms aren’t going anywhere. In fact, in an AI-saturated world, their value only increases — because they represent what AI can’t do without us: think critically and design deterministic systems.</p><p>So no — AI isn’t replacing traditional algorithms.</p><p>But it does raise the bar on when and where we should still reach for our thinking caps as a D<strong>eveloper</strong>.<br>And that, in itself, is a good thing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a41e0e2806" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Java Threads: Platform, Virtual, and the Async Illusion]]></title>
            <link>https://medium.com/@samuelgbenga972/understanding-java-threads-platform-virtual-and-the-async-illusion-a3c076be2ac6?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3c076be2ac6</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[synchronous-programming]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Wed, 14 May 2025 06:54:48 GMT</pubDate>
            <atom:updated>2025-05-14T06:54:48.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*4PznyRhysF5eHZX6P0S96A.jpeg" /><figcaption>Photo by Steve Johnson: <a href="https://www.pexels.com/photo/gray-yarn-ball-845263/">https://www.pexels.com/photo/gray-yarn-ball-845263/</a></figcaption></figure><p><strong>In this article we will be talking about the following:</strong></p><ul><li>Platform threads vs traditional terminology</li><li>Virtual threads</li><li>The <strong>misconception</strong> between virtual threading and async</li><li>How virtual threads help <strong>both</strong> sync and async code</li></ul><p>In the world of Java concurrency, terms like <strong>“platform thread,” “virtual thread,”</strong> and <strong>“asynchronous programming”</strong> can easily get tangled up.</p><p>So let’s untangle the threads — literally, hypothetically, and metaphorically.</p><h3>☕ Traditional Threads: What We Used to Call Them</h3><p>In Java’s early days (and honestly, up until recently), we simply called them <em>threads</em>. For example:</p><pre>new Thread(() -&gt; doWork()).start();</pre><p>…you were spinning up what is now formally called a <strong>platform thread</strong>. Why the new name?</p><p>Because virtual threads entered the chat in <strong>Java 21</strong>, and the JVM needed to make a distinction.</p><h3>🔍 What Is a Platform Thread?</h3><p>A <strong>platform thread</strong> is essentially a wrapper around an <strong>OS thread</strong>. That means:</p><ul><li>One Java thread = One operating system thread.</li><li>They’re <strong>expensive to create</strong>.</li><li>They are <strong>limited in number</strong>.</li><li>And they <strong>block CPU resources</strong> while waiting (e.g., during I/O or Thread.sleep()).</li></ul><p>So nowadays, when people say “traditional thread,” they’re really referring to a <strong>platform thread</strong>.</p><h3>💡 Enter Virtual Threads</h3><p><strong>Java 21</strong> introduced <strong>virtual threads</strong> — lightweight threads <strong>managed by the JVM</strong>, not the OS.</p><p>You can create them like this:</p><pre>Thread.startVirtualThread(() -&gt; doWork());</pre><p>Or with an executor:</p><pre>Executors.newVirtualThreadPerTaskExecutor()</pre><p>Unlike platform threads, <strong>virtual threads are cheap</strong> and you can spin up <strong>millions</strong> of them without overloading your system.</p><h3>🧠 Virtual Threads ≠ Asynchronous Programming</h3><p>One of the biggest misconceptions in the Java world right now is:</p><blockquote><em>“Virtual threads are for asynchronous code.”<br> </em>(At least, that’s what I thought at first!)</blockquote><p><strong>Not true.</strong></p><p>Virtual threads are about <strong>optimizing synchronous code</strong>.</p><p>They don’t replace asynchronous programming — they just <strong>make blocking operations cheaper</strong> (e.g., file or DB access) by decoupling your logic from expensive OS-managed threads.</p><h3>🧪 How They Work Together</h3><p>Here’s the trick:<br> Your <strong>async code</strong> can still run on virtual threads, and your <strong>sync code</strong> can now scale much better <strong>thanks to virtual threads</strong>.</p><p>Think of it like this:</p><ul><li><strong>Async programming</strong>: You break a task into chunks and run them in parallel.</li><li><strong>Virtual threads</strong>: You write code normally, but it runs on lightweight threads that <strong>don’t hog OS resources</strong> — because the <strong>JVM</strong> fully manages them.</li></ul><blockquote><em>🔍 Note: Platform threads, although also managed by the JVM, still relied heavily on the </em><strong><em>OS for key tasks</em></strong><em> like scheduling and context switching. Virtual threads, on the other hand, keep it all inside the JVM — hence </em>virtual<em>.</em></blockquote><p>It’s not <em>either-or</em> — you choose what works best for your use case.</p><h3>✅ Final Thoughts</h3><ul><li>“Traditional thread” = now better referred to as a <strong>platform thread</strong></li><li><strong>Virtual threads</strong> are lightweight, scalable, and effective without async syntax</li><li><strong>Async programming</strong> is still powerful — but not always simpler</li><li>You can use <strong>virtual threads</strong> for both synchronous and asynchronous code</li></ul><p>If you’re curious about how <strong>Java 24</strong> improved virtual threads even more by <strong>solving the pinning problem</strong>, check out the official documentation:</p><p><a href="https://openjdk.org/jeps/491">📘 JEP 491: Unpinning Virtual Threads</a></p><p>Meanwhile, I’ll be working up the courage to write a breakdown article on that next 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3c076be2ac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Multi-Currency Support in Java: A Smarter Way to Handle Currency Symbols]]></title>
            <link>https://medium.com/@samuelgbenga972/simplifying-multi-currency-support-in-java-a-smarter-way-to-handle-currency-symbols-659535de61f4?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/659535de61f4</guid>
            <category><![CDATA[currency]]></category>
            <category><![CDATA[locale]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Fri, 09 May 2025 01:51:43 GMT</pubDate>
            <atom:updated>2025-05-09T01:51:43.202Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vZRLFFyYc_gdcHksxh23jA.jpeg" /><figcaption>Photo by Pixabay: <a href="https://www.pexels.com/photo/20-euro-bill-128878/">https://www.pexels.com/photo/20-euro-bill-128878/</a></figcaption></figure><h3>Introduction</h3><p>Some time ago, I was tasked to build a project that is currency-sensitive based on the user’s location — meaning the currency should change dynamically depending on where the user is accessing from.</p><p>This got me thinking about how best to approach the problem until I stumbled upon a simple and elegant solution using Java’s built-in features.</p><p><strong>Before we delve in, note this:</strong><br> Locale.getDefault() may not accurately detect the user&#39;s real-world location. It returns the system or JVM locale, which may be set manually or inherited from device settings.<br> So, in real-world scenarios, you’ll likely need a <strong>third-party API</strong> (like IP-based geolocation services) to get the user’s actual region and then <strong>set the locale manually</strong>.<br> However, for the sake of keeping this article short and focused, we’ll <strong>assume </strong><strong>Locale.getDefault() returns the correct location/region</strong>.</p><h3>Why Use Java’s Currency API?</h3><p>Java provides the Currency and Locale classes which let you display the appropriate <strong>currency symbol</strong> for a user&#39;s region without hardcoding or maintaining long mapping tables.</p><p>This makes your app cleaner, more maintainable, and ready for international users.</p><h3>🧪 Example: Getting the Currency Symbol by Locale</h3><p>Here’s a simple program that retrieves the correct currency symbol using the current locale:</p><pre>import java.util.Currency;<br>import java.util.Locale;</pre><pre>public class CurrencySymbolExample {<br>    public static void main(String[] args) {<br>        Locale currentLocale = Locale.getDefault(); // Assume this is accurate<br>        Currency currency = Currency.getInstance(currentLocale);<br>        String symbol = currency.getSymbol(currentLocale);</pre><pre>        System.out.println(&quot;User Region: &quot; + currentLocale.getCountry());<br>        System.out.println(&quot;Currency Symbol: &quot; + symbol);<br>    }<br>}</pre><p><strong>Sample Output:</strong></p><p>If Locale.getDefault() returns Locale(&quot;en&quot;, &quot;NG&quot;), the output would be:</p><pre>User Region: NG<br>Currency Symbol: ₦</pre><h3>🧭 Bonus: Manually Setting the Locale (for simulation/testing)</h3><p>If you want to simulate different regions manually:</p><pre>Locale usLocale = new Locale(&quot;en&quot;, &quot;US&quot;);<br>Currency usCurrency = Currency.getInstance(usLocale);<br>System.out.println(&quot;US Symbol: &quot; + usCurrency.getSymbol(usLocale)); // $</pre><p>You can repeat this for other countries like Germany (&quot;de&quot;, &quot;DE&quot;), India (&quot;en&quot;, &quot;IN&quot;), etc.</p><h3>✅ Benefits of This Approach</h3><ul><li><strong>Localization-friendly</strong>: Automatically adapts symbols based on region</li><li><strong>Clean code</strong>: Avoids manual mapping or string formatting</li><li><strong>Scalable</strong>: Supports all ISO-recognized currencies</li><li><strong>Built-in</strong>: No external libraries required (except if you want accurate geolocation)</li></ul><h3>Conclusion</h3><p>When dealing with currency-aware applications, especially those that serve users across multiple regions, it’s tempting to manually set symbols or build complex formatting logic. But Java already gives us the tools to handle this elegantly through the Currency and Locale classes.</p><p>For simple projects, assuming the locale is accurate might be good enough. For production-grade applications, pairing this with a geolocation API will give you precision and flexibility — while still using the same currency-handling logic shown above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=659535de61f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Custom Serialization in Java with Jackson]]></title>
            <link>https://medium.com/@samuelgbenga972/mastering-custom-serialization-in-java-with-jackson-e240ca00a7c3?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/e240ca00a7c3</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[jackson]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[objectmapper]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Thu, 08 May 2025 04:42:34 GMT</pubDate>
            <atom:updated>2025-05-08T04:42:34.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2Fax4TkixwEwqnZPmo1QQ.png" /></figure><p>Back when I started with Java, I used to write whole classes just to turn JSON into Java objects and back. I felt pretty proud — like I had really done something cool. Then I found Jackson’s ObjectMapper, and just one line of code did everything I had worked so hard on. It was a wake-up call. That moment made me wonder—what else have I been overthinking? Turns out, there’s a lot more you can do with Jackson, and it doesn’t have to be complicated.</p><p>When you’re dealing with JSON in Java, <strong>Jackson</strong>’s ObjectMapper does most of the heavy lifting. But what if you want full control over how your object is turned into JSON? Say hello to:</p><ul><li>@JsonFormat for quick formatting</li><li>@JsonSerialize for custom behavior</li><li>StdSerializer for the heavy customization</li><li>and of course, the one and only ObjectMapper</li></ul><p>Let’s walk through a real-world use case.</p><h3>🧑‍💻 Example Use Case</h3><p>Let’s say we want to customize how a User object with a LocalDate birth date is serialized.</p><h3>1. Define the Entity</h3><pre>public class User {<br>    private String name;<br>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = &quot;yyyy/MM/dd&quot;)<br>    private LocalDate birthDate;<br>    @JsonSerialize(using = RoleSerializer.class)<br>    private Role role;<br>    // getters and setters<br>}</pre><h3>2. Custom Role Enum + Serializer</h3><pre>public enum Role {<br>    ADMIN, USER<br>}</pre><p>Now let’s customize how Role appears in JSON.</p><pre>public class RoleSerializer extends StdSerializer&lt;Role&gt; {<br>public RoleSerializer() {<br>        super(Role.class);<br>    }<br>    @Override<br>    public void serialize(Role role, JsonGenerator gen, SerializerProvider provider) throws IOException {<br>        String value = switch (role) {<br>            case ADMIN -&gt; &quot;System Administrator&quot;;<br>            case USER -&gt; &quot;End User&quot;;<br>        };<br>        gen.writeString(value);<br>    }<br>}</pre><h3>3. Fire It Up with ObjectMapper</h3><pre>public class Main {<br>    public static void main(String[] args) throws JsonProcessingException {<br>        User user = new User();<br>        user.setName(&quot;Alice&quot;);<br>        user.setBirthDate(LocalDate.of(1990, 10, 5));<br>        user.setRole(Role.ADMIN);<br>ObjectMapper mapper = new ObjectMapper();<br>        mapper.registerModule(new JavaTimeModule()); // for LocalDate<br>        String json = mapper.writeValueAsString(user);<br>        System.out.println(json);<br>    }<br>}</pre><p>Assuming you’re serializing the User object from the example you provided:</p><pre><br>user.setName(&quot;Alice&quot;);<br>user.setBirthDate(LocalDate.of(1990, 10, 5));<br>user.setRole(Role.ADMIN);</pre><p>This would be the output:</p><pre>{<br>  &quot;name&quot;: &quot;Alice&quot;,<br>  &quot;birthDate&quot;: &quot;1990/10/05&quot;,<br>  &quot;role&quot;: &quot;System Administrator&quot;<br>}</pre><h3>🔍 What Just Happened?</h3><ul><li>@JsonFormat gave our LocalDate a readable format.</li><li>@JsonSerialize told Jackson to use our custom RoleSerializer.</li><li>RoleSerializer extended StdSerializer&lt;Role&gt; to define how Role appears in the output.</li><li>ObjectMapper brought it all together.</li></ul><h3>🧠 TL;DR</h3><p>Use:</p><ul><li>@JsonFormat to format dates and enums.</li><li>@JsonSerialize(using = YourCustomSerializer.class) for custom control.</li><li>Extend StdSerializer&lt;T&gt; when you want full serialization power.</li><li>ObjectMapper is your central JSON processor in Java.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e240ca00a7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Validators in Java]]></title>
            <link>https://medium.com/@samuelgbenga972/custom-validators-in-java-05b3632cdc40?source=rss-e791994f242------2</link>
            <guid isPermaLink="false">https://medium.com/p/05b3632cdc40</guid>
            <category><![CDATA[humorous]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[custom-validator]]></category>
            <dc:creator><![CDATA[Samuelgbenga]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 18:59:50 GMT</pubDate>
            <atom:updated>2025-04-05T18:59:50.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F23fuhse2R3jDmZGRK6yzQ.jpeg" /><figcaption>neat</figcaption></figure><p>So, you’ve got a signup form, and someone tries to register as kingkong123 for the 14th time. What do you do? Throw the whole server away? Nope. You create a <strong>custom validator</strong> to ensure usernames are unique.</p><p>Let’s go step by step — short, sweet, and practical.</p><h3>1. Entity Setup</h3><pre>@Entity<br>public class User {<br>@Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    @UniqueUsername // &lt;- Our custom annotation<br>    private String username;<br>    private String email;<br>    private String password;<br>    // Getters and setters<br>}</pre><h3>2. Custom Annotation</h3><pre>@Constraint(validatedBy = UniqueUsernameValidator.class)<br>@Target({ ElementType.FIELD })<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface UniqueUsername {<br>    String message() default &quot;Username already exists&quot;;<br>    Class&lt;?&gt;[] groups() default {};<br>    Class&lt;? extends Payload&gt;[] payload() default {};<br>}</pre><h3>3. Validator Class</h3><pre>@Component<br>@RequiredArgsConstructor<br>public class UniqueUsernameValidator implements ConstraintValidator&lt;UniqueUsername, String&gt; {<br><br>    private final UserRepository userRepository;<br><br>    @Override<br>    public boolean isValid(String username, ConstraintValidatorContext context) {<br>        return username != null &amp;&amp; !userRepository.existsByUsername(username);<br>    }<br>}</pre><h3>4. Repository Layer</h3><pre>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    boolean existsByUsername(String username);<br>}</pre><h3>5. Controller Layer</h3><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>@RequiredArgsConstructor<br>public class UserController {<br><br>private final UserService userService;<br><br>    @PostMapping(&quot;/register&quot;)<br>    public ResponseEntity&lt;String&gt; registerUser(@Valid @RequestBody User user) {<br>        userService.saveUser(user);<br>        return ResponseEntity.ok(&quot;User registered successfully!&quot;);<br>    }<br>}</pre><h3>6. Service Layer</h3><pre>@Service<br>@RequiredArgsConstructor<br>public class UserService {<br><br>    private final UserRepository userRepository;<br>    public void saveUser(User user) {<br>        userRepository.save(user);<br>    }<br>}</pre><h3>7. Global Exception Handling (Make it Reusable)</h3><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br>@ExceptionHandler(MethodArgumentNotValidException.class)<br>    public ResponseEntity&lt;Object&gt; handleValidationException(MethodArgumentNotValidException ex) {<br>        Map&lt;String, Object&gt; errors = new HashMap&lt;&gt;();<br>        ex.getBindingResult().getFieldErrors().forEach(error -&gt;<br>                errors.put(error.getField(), error.getDefaultMessage()));<br>        return buildErrorResponse(HttpStatus.BAD_REQUEST, &quot;Validation failed&quot;, errors);<br>    }<br>    private ResponseEntity&lt;Object&gt; buildErrorResponse(HttpStatus status, String message, Map&lt;String, Object&gt; errors) {<br>        Map&lt;String, Object&gt; response = new HashMap&lt;&gt;();<br>        response.put(&quot;status&quot;, status.value());<br>        response.put(&quot;message&quot;, message);<br>        response.put(&quot;errors&quot;, errors);<br>        return new ResponseEntity&lt;&gt;(response, status);<br>    }<br>}</pre><h3>Final Words</h3><p>There you go. You now have a working <strong>custom validator</strong> in Java. Say goodbye to duplicate usernames and hello to clean data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05b3632cdc40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>