<?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 Dileepa Prabhath on Medium]]></title>
        <description><![CDATA[Stories by Dileepa Prabhath on Medium]]></description>
        <link>https://medium.com/@d.prabath115?source=rss-8cd80b3227a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*auHcn0De8cddhhmyt3WV4w.jpeg</url>
            <title>Stories by Dileepa Prabhath on Medium</title>
            <link>https://medium.com/@d.prabath115?source=rss-8cd80b3227a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:12:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d.prabath115/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[Building Real-Time Features the Right Way: WebSockets + STOMP + SockJS in a Restaurant Management…]]></title>
            <link>https://medium.com/@d.prabath115/building-real-time-features-the-right-way-websockets-stomp-sockjs-in-a-restaurant-management-e70e189855ad?source=rss-8cd80b3227a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e70e189855ad</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[real-time-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Dileepa Prabhath]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 11:56:01 GMT</pubDate>
            <atom:updated>2026-09-12T11:56:01.288Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Real-Time Features the Right Way: WebSockets + STOMP + SockJS in a Restaurant Management System</h3><p><em>How we eliminated polling with a zero-trust, resilient, multi-tenant real-time push architecture using Spring Boot 3 and React 18.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*is1uTk81dc1J6oTRXFpdSw.jpeg" /><figcaption>AI Genarated Image</figcaption></figure><h3>1. The Problem Every Real-Time System Faces</h3><p>Imagine running a high-volume multi-branch restaurant system. On any given evening:</p><ul><li><strong>Diners</strong> are watching their phones waiting for live delivery or kitchen progress updates.</li><li><strong>Line chefs</strong> are standing at station tablets waiting for incoming orders to prepare.</li><li><strong>Receptionists</strong> are seating walk-in guests while online reservations constantly lock and clear physical tables.</li><li><strong>Store managers</strong> are monitoring live revenue and critical inventory alerts.</li></ul><p>The classic, naive engineering solution to keep this data fresh is <strong>HTTP polling</strong>: having client browsers bombard the backend with periodic requests every 2 to 3 seconds:</p><blockquote>“Is order #105 cooked yet?”<em><br> </em>“Any new orders for the kitchen?”<em><br> </em>“Has Table 4 settled their bill yet?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rF4koma7HtthiKri3B04Sg.jpeg" /><figcaption>AI Genarated Image</figcaption></figure><p>We needed an architecture where <strong>the server speaks only when an event actually happens</strong>, delivering updates with sub-second latency while keeping database queries at near zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGSxUSDOB7932c6h0WfrPA.jpeg" /><figcaption>AI Generated Image</figcaption></figure><h3>2. The Three-Layer Real-Time Stack</h3><p>To build a production-grade push engine, we combined three complementary technologies into a layered stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_i256u4RsN9nywzDafM0g.png" /></figure><h3>Layer 1: WebSocket — The Persistent Connection</h3><p>Standard HTTP is half-duplex: the client asks, the server answers, and the connection closes.</p><p><strong>WebSocket (RFC 6455)</strong> changes the rules. It initiates over standard HTTP (port 80 or 443), then sends an Upgrade: websocket header. Once the server accepts with 101 Switching Protocols, the connection morphs into a persistent, full-duplex TCP tunnel that stays open indefinitely. Both sides can send data at any moment with virtually zero frame overhead (as little as 2 bytes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxNKQ-4noFI1wQOPXn3ZLw.png" /></figure><h3>Layer 2: SockJS — The Reliability Safety Net</h3><p>While pure WebSockets work seamlessly on localhost, they often break in the real world:</p><ul><li><strong>Mobile networks (4G/5G)</strong> frequently drop persistent TCP connections during cell tower handoffs.</li><li><strong>Restaurant guest Wi-Fi</strong> often runs restrictive captive portal proxies that block non-HTTP traffic.</li><li><strong>Corporate firewalls and antivirus software</strong> often intercept and terminate long-lived WebSocket handshakes.</li></ul><p><strong>SockJS</strong> acts as a progressive fallback engine. When connecting, it first tests server capabilities via /ws/info. It tries native WebSockets first; if blocked, it seamlessly downgrades through alternative HTTP transports without breaking your application code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nUUDsQLnKo7gRNeNphB0ng.png" /></figure><h3>Layer 3: STOMP — The Messaging Protocol</h3><p>Raw WebSocket is just a dumb byte pipe — it has no built-in concept of <em>“send this only to the kitchen”</em> or <em>“subscribe to table 4”</em>.</p><p><strong>STOMP (Simple Text Oriented Messaging Protocol)</strong> introduces pub/sub semantics on top of WebSockets. It defines standard text frames modeled after HTTP:</p><pre>CONNECT<br>accept-version:1.2<br>Authorization:Bearer eyJhbGciOi...<br>heart-beat:10000,10000<br>^@j</pre><pre>SUBSCRIBE<br>id:sub-0<br>destination:/topic/branch/1/kitchen-orders<br>^@</pre><pre>MESSAGE<br>subscription:sub-0<br>destination:/topic/branch/1/kitchen-orders<br>content-type:application/json<br><br>{&quot;orderNumber&quot;:&quot;ORD-105&quot;,&quot;status&quot;:&quot;PLACED&quot;}<br>^@</pre><h3>3. High-Level System Architecture</h3><p>Here is how our React 18 frontend and Spring Boot 3 backend are structured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BytEygCXrSVHpNU4uDGrRQ.png" /></figure><h3>4. Backend Implementation (Spring Boot 3)</h3><h3>A. Broker Configuration &amp; The 10-Second Heartbeat</h3><p>In WebSocketConfig.java, we configure the STOMP broker, enable SockJS fallback, and attach a dedicated single-threaded task scheduler for heartbeats:</p><pre>@Configuration<br>@EnableWebSocketMessageBroker<br>@RequiredArgsConstructor<br>public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {<br>private final WebSocketAuthInterceptor webSocketAuthInterceptor;<br>    @Override<br>    public void registerStompEndpoints(StompEndpointRegistry registry) {<br>        // Handshake endpoint supporting SockJS fallback<br>        registry.addEndpoint(&quot;/ws&quot;)<br>                .setAllowedOriginPatterns(&quot;*&quot;)<br>                .withSockJS();<br>    }<br>    @Override<br>    public void configureMessageBroker(MessageBrokerRegistry registry) {<br>        // In-memory message router for server-to-client broadcasts<br>        registry.enableSimpleBroker(&quot;/topic&quot;)<br>                .setHeartbeatValue(new long[]{10000, 10000}) // 10s incoming, 10s outgoing<br>                .setTaskScheduler(webSocketHeartbeatScheduler());<br>        registry.setApplicationDestinationPrefixes(&quot;/app&quot;);<br>    }<br>    @Override<br>    public void configureClientInboundChannel(ChannelRegistration registration) {<br>        // Intercept all inbound STOMP frames before they reach the broker<br>        registration.interceptors(webSocketAuthInterceptor);<br>    }<br>    @Bean<br>    public ThreadPoolTaskScheduler webSocketHeartbeatScheduler() {<br>        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();<br>        scheduler.setPoolSize(1);<br>        scheduler.setThreadNamePrefix(&quot;ws-heartbeat-&quot;);<br>        scheduler.initialize();<br>        return scheduler;<br>    }<br>}</pre><blockquote><em>[!TIP]<br> </em><strong><em>Why the 10-Second Heartbeat Matters:</em></strong><em><br> Cloud load balancers (such as AWS ALB, Render, or Nginx) automatically kill TCP sockets if they detect 30–60 seconds of silence. Sending a lightweight heartbeat frame every 10 seconds guarantees that idle connections remain open indefinitely without dropping.</em></blockquote><h3>B. Zero-Trust Security: WebSocketAuthInterceptor</h3><p>Standard Spring Security servlet filters (OncePerRequestFilter) <strong>do not run</strong> on persistent STOMP TCP frames. To prevent unauthorized connections and cross-tenant eavesdropping, we implemented a custom ChannelInterceptor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HF68VhIR1o0iuzTjWzHF_w.png" /></figure><p>Here is the core logic inside our WebSocketAuthInterceptor.java:</p><pre>@Component<br>@RequiredArgsConstructor<br>@Slf4j<br>public class WebSocketAuthInterceptor implements ChannelInterceptor {<br>private final JwtService jwtService;<br>    private final UserRepository userRepository;<br>    private final StaffRepository staffRepository;<br>    @Override<br>    public Message&lt;?&gt; preSend(Message&lt;?&gt; message, MessageChannel channel) {<br>        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);<br>        if (accessor == null || accessor.getCommand() == null) return message;<br>        // 1. Authenticate on CONNECT<br>        if (StompCommand.CONNECT.equals(accessor.getCommand())) {<br>            String authHeader = accessor.getFirstNativeHeader(&quot;Authorization&quot;);<br>            if (authHeader == null || !authHeader.startsWith(&quot;Bearer &quot;)) {<br>                throw new AuthenticationCredentialsNotFoundException(&quot;Missing Authorization header&quot;);<br>            }<br>            String token = authHeader.substring(7);<br>            if (!jwtService.validateToken(token)) {<br>                throw new BadCredentialsException(&quot;Invalid or expired JWT token&quot;);<br>            }<br>            Long userId = jwtService.getUserIdFromToken(token);<br>            User user = userRepository.findById(userId)<br>                    .orElseThrow(() -&gt; new BadCredentialsException(&quot;User does not exist&quot;));<br>            if (!Boolean.TRUE.equals(user.getIsActive())) {<br>                throw new AccessDeniedException(&quot;User account is deactivated&quot;);<br>            }<br>            JwtUserPrincipal principal = new JwtUserPrincipal(user);<br>            accessor.setUser(new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities()));<br>        }<br>        // 2. Authorize on SUBSCRIBE<br>        else if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {<br>            String destination = accessor.getDestination();<br>            User currentUser = extractUser(accessor.getUser());<br>            // Prevent customer eavesdropping on other users&#39; topics<br>            if (destination.startsWith(&quot;/topic/user/&quot;)) {<br>                Long targetUserId = extractTargetId(destination, &quot;/topic/user/&quot;);<br>                if (!currentUser.getId().equals(targetUserId)) {<br>                    throw new AccessDeniedException(&quot;Unauthorized subscription attempt&quot;);<br>                }<br>            }<br>            // Prevent customers from subscribing to staff/kitchen topics<br>            else if (destination.startsWith(&quot;/topic/branch/&quot;)) {<br>                if (isCustomer(currentUser)) {<br>                    throw new AccessDeniedException(&quot;Customers cannot subscribe to staff channels&quot;);<br>                }<br>            }<br>        }<br>        return message;<br>    }<br>}</pre><h3>5. Multi-Tenant Topic Architecture</h3><p>To prevent cross-branch and cross-user data leakage, we partitioned our topics into strict isolation boundaries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x822QuBm7X3uuwpwtT7wIw.png" /></figure><h3>6. Frontend Implementation (React 18)</h3><h3>A. The Global Push Listener (GlobalNotificationProvider.jsx)</h3><p>Mounted at the root layout of the customer application. It connects once and stays active across all pages:</p><pre>export default function GlobalNotificationProvider() {<br>  const clientRef = useRef(null);<br>  const navigate = useNavigate();<br>useEffect(() =&gt; {<br>    const token = localStorage.getItem(&#39;customer_jwt&#39;);<br>    if (!token) return;<br>    const payload = decodeJwtPayload(token);<br>    const userId = payload?.userId;<br>    if (!userId) return;<br>    const client = new Client({<br>      webSocketFactory: () =&gt; new SockJS(`${API_BASE}/ws`),<br>      connectHeaders: { Authorization: `Bearer ${token}` },<br>      reconnectDelay: 5000, // Reconnect automatically if connection drops<br>      onConnect: () =&gt; {<br>        client.subscribe(`/topic/user/${userId}/orders`, (message) =&gt; {<br>          const { orderStatus, paymentStatus, orderNumber, orderId } = JSON.parse(message.body);<br>          // Real-Time Stripe Refund Toast<br>          if (paymentStatus === &#39;REFUNDED&#39;) {<br>            toast.success(`Order #${orderNumber}: Payment has been refunded!`, {<br>              onClick: () =&gt; navigate(&#39;/order-confirmation&#39;, { state: { orderId } })<br>            });<br>            return;<br>          }<br>          // Real-Time Kitchen Served Toast<br>          if (orderStatus === &#39;SERVED&#39;) {<br>            toast.success(`Order #${orderNumber}: Your meal has been served! Enjoy!`, {<br>              onClick: () =&gt; navigate(&#39;/order-confirmation&#39;, { state: { orderId } })<br>            });<br>          }<br>        });<br>      }<br>    });<br>    client.activate();<br>    clientRef.current = client;<br>    // Clean socket teardown on unmount<br>    return () =&gt; client.deactivate();<br>  }, []);<br>  return null;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ak4nQyjGQQEsu-5lu9eGQ.png" /></figure><h3>7. The End-to-End Real-Time Event Flow</h3><p>Here is what happens when a chef marks a dish as prepared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYmlIc0n4mI4BV1kYcY-3Q.png" /></figure><h3>8. Production Lessons Learned</h3><p>Building real-time systems in high-volume hospitality taught us several non-negotiable rules:</p><ol><li><strong>Never Skip Heartbeats:</strong> Cloud platforms (Render, AWS ALB, Nginx) drop silent TCP sockets after 30 seconds. A 10-second heartbeat keeps sockets alive 24/7.</li><li><strong>Authenticate on CONNECT, Authorize on SUBSCRIBE:</strong> Never allow anonymous connections, and never allow a user to subscribe to a foreign topic.</li><li><strong>Always Clean Up (client.deactivate()):</strong> Unmounted React components that do not deactivate their STOMP client leave orphan TCP connections, leaking server memory.</li><li><strong>Isolate Notification Failures:</strong> Always wrap WebSocket broadcasts in try-catch inside service methods. A transient network glitch should never roll back an order placement or database transaction.</li><li><strong>Always Keep SockJS as a Fallback:</strong> Raw WebSockets will fail on 5–10% of real-world mobile and guest Wi-Fi networks. SockJS ensures zero downtime.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_e8bInAeHGkjBh63l_1N0g.jpeg" /></figure><h3>Final Architecture Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJhPFTbBdw0fdn-CPiDcXw.jpeg" /></figure><h3>Conclusion</h3><p>By replacing polling with a structured <strong>WebSocket + SockJS + STOMP</strong> architecture, we transformed our restaurant system from a heavy, database-straining polling app into a responsive, real-time operating platform.</p><p>Whether tracking an online delivery, alerting the kitchen station, or notifying a diner of a Stripe refund, updates now flow across our stack in milliseconds — securely, resiliently, and effortlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e70e189855ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Payment Gateway Security: Building the Payment & Refund Gateway for Our Restaurant…]]></title>
            <link>https://medium.com/@d.prabath115/modern-payment-gateway-security-building-the-payment-refund-gateway-for-our-restaurant-19d72f8075c7?source=rss-8cd80b3227a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d72f8075c7</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Dileepa Prabhath]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 20:44:16 GMT</pubDate>
            <atom:updated>2026-09-07T20:44:16.657Z</atom:updated>
            <content:encoded><![CDATA[<h3>Modern Payment Gateway Security: Building the Payment &amp; Refund Gateway for Our Restaurant Management System</h3><p><em>How we tackled zero-trust checkout, tamper-proof webhooks, automated partial refunds, and real-time order sync across high-volume dining workflows.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RaheVKrMzHeHOjaz7BmUMA.jpeg" /><figcaption>Gemini Generated Ai Image</figcaption></figure><h3>1. The “Happy Path” Illusion in Payment Engineering</h3><p>Every engineer who has integrated a payment gateway has seen the tutorial version: import an SDK, mount a pre-built card form, listen for onSubmit, send a token to the backend, and display a cheerful green checkmark that says <em>“Payment Successful!”</em></p><p>In tutorials, that happy path works like magic.</p><p>In production — especially in high-volume hospitality platforms processing online delivery, QR dine-in, and advance table reservations — that simplistic mental model collapses.</p><pre>+----------------------------------------------------------------------------------------------------+<br>| THE &quot;HAPPY PATH&quot; MENTAL MODEL                                                                      |<br>| [User Clicks Pay] → [Frontend Tokenizes Card] → [Backend Charges Card] → [Order Placed]            |<br>|                                                                                                    |<br>| WHAT ACTUALLY HAPPENS IN PRODUCTION                                                                |<br>| • Customer’s phone battery dies mid-handshake right after the card is charged                      |<br>| • 3D-Secure SMS OTP delays cause the browser HTTP connection to time out                           |<br>| • An impatient diner double-clicks “Pay” during a cellular network spike                           |<br>| • The kitchen starts cooking a $60 meal before the bank settles the transaction                    |<br>| • A customer cancels a reservation two hours prior and requires an instant partial refund          |<br>| • Network packet drops trigger automatic HTTP retries that threaten to double-refund the customer  |<br>+----------------------------------------------------------------------------------------------------+</pre><p>When building <strong>ServeSync (CraveHouse)</strong>, our multi-branch restaurant system, we learned that a payment is never an isolated financial event. It is the triggering nexus of a distributed state machine:</p><ul><li>A successful delivery order must deduct raw inventory, alert the Kitchen Display System (KDS), dispatch a driver, and award loyalty points.</li><li>A table reservation must atomically lock physical tables across overlapping time windows and calculate non-refundable handling fees.</li><li>A cancellation must refund through banking APIs, roll back reward points, restock promotional coupons, and push real-time updates to kitchen tablets and customer phones — all in <strong>sub-second latency without requiring a page refresh</strong>.</li></ul><p>If your architecture trusts the client for fulfillment, you will eventually face <strong>phantom charges</strong> (customer billed, but no order created) or <strong>unpaid fulfillment</strong> (food prepared and delivered, but money never captured).</p><p>This article shares the architectural patterns, security boundaries, and failure-recovery mechanisms we implemented using <strong>Spring Boot 3</strong>, <strong>Stripe</strong>, <strong>React</strong>, and <strong>STOMP WebSockets</strong>.</p><h3>2. The Security Perimeter: Why Three Cryptographic Keys Exist</h3><p>A common question when developers first integrate Stripe is: <em>Why do we need three different cryptographic keys just to charge a card?</em></p><p>Think of it as a high-security bank vault. You would never give the lobby receptionist the master vault key, nor let the armored-car driver change the combination. Each key serves a strictly bounded security domain with zero privilege overlap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bC_I0OspDm5JkxfClcYZzA.png" /></figure><h3>The Principle of Least Privilege</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcbuocsRHM8T_C_gHj0kQQ.jpeg" /><figcaption>Gemini Generated Ai Image</figcaption></figure><h3>3. Zero-Trust Frontend: PCI-DSS, DOM Isolation &amp; the Iframe Shield</h3><h3>The Catastrophic Mistake of Native Card Inputs</h3><p>Consider what happens if you build a standard card form using native HTML inputs in React:</p><pre>// ❌ CRITICAL SECURITY FLAW: NEVER DO THIS<br>&lt;input<br>  type=&quot;text&quot;<br>  placeholder=&quot;16-Digit Card Number&quot;<br>  value={cardNumber}<br>  onChange={(e) =&gt; setCardNumber(e.target.value)}<br>/&gt;</pre><p>The moment credit card numbers enter React component state, they pass into browser DOM memory. If sent to your backend, those digits traverse HTTP server buffers, JVM heap memory, garbage collection roots, and log files.</p><p>Under payment card industry regulations, this innocent form immediately subjects your entire company to <strong>PCI-DSS Level 1 Audit Scrutiny</strong>:</p><ul><li>Mandatory annual on-site forensic audits costing $50,000+.</li><li>Continuous vulnerability scans and penetration testing across every microservice.</li><li>Severe legal liability in the event of any data or server compromise.</li></ul><h3>How Stripe Elements Enforces DOM Isolation</h3><p>We use <strong>Stripe Elements (&lt;PaymentElement /&gt;)</strong>. It embeds an isolated &lt;iframe&gt; hosted directly on js.stripe.com.</p><p>The browser’s <strong>Same-Origin Policy</strong> makes it physically impossible for JavaScript in our parent application to inspect, scrape, keylog, or read card data inside that iframe. Keystrokes travel directly to Stripe’s encrypted edge proxies. Neither our React app nor our Spring Boot servers ever touch, see, or log raw Primary Account Numbers (PAN), drastically reducing our audit scope to <strong>SAQ-A</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nL1OzCUXzxiYJiNKd0cvDw.jpeg" /><figcaption>Gemini Generated AI Image</figcaption></figure><pre>+------------------------------------------------------------------------------------+<br>| Customer&#39;s Browser (Hosted on: https://your-restaurant-domain.com)                 |<br>|                                                                                    |<br>|  +----------------------------------------------------------------------------+    |<br>|  | Your React Form Container                                                  |    |<br>|  |                                                                            |    |<br>|  |  +--------------------------------------------------------------------+    |    |<br>|  |  | IFRAME Shield (Hosted on: https://js.stripe.com)                   |    |    |<br>|  |  |                                                                    |    |    |<br>|  |  |  [ Card Number: **** **** **** 4242 ]  (Sandboxed DOM)             |    |    |<br>|  |  |  [ MM / YY ]          [ CVC: *** ]     (Encrypted Memory)          |    |    |<br>|  |  |                                                                    |    |    |<br>|  |  +--------------------------------------------------------------------+    |    |<br>|  |                                                                            |    |<br>|  |  [ Pay Securely Button ]                                                   |    |<br>|  +----------------------------------------------------------------------------+    |<br>+------------------------------------------------------------------------------------+</pre><h3>Seamless SPA Experience with redirect: ‘if_required’</h3><p>Standard checkout implementations force an unnecessary full-page browser reload by redirecting users to a static return URL. In modern single-page applications (SPAs), this causes jarring page flashes and breaks client state.</p><p>By configuring redirect: ‘if_required’, Stripe resolves payment confirmation in-memory whenever 3D-Secure redirects are not mandatory:</p><pre>// Frontend Checkout Component<br>const handleSubmit = async (event) =&gt; {<br>  event.preventDefault();<br>  if (!stripe || !elements) return;<br>  setIsProcessing(true);<br>  setErrorMessage(null);<br>  try {<br>    // 1. Confirm payment directly with Stripe servers<br>    const { error, paymentIntent } = await stripe.confirmPayment({<br>      elements,<br>      redirect: &#39;if_required&#39;, // Stay in-memory when 3DS redirects aren&#39;t mandatory<br>    });<br>    if (error) {<br>      setErrorMessage(error.message);<br>      return;<br>    }<br>    // 2. Trust the Webhook for DB updates, but transition the SPA smoothly<br>    if (paymentIntent?.status === &#39;succeeded&#39;) {<br>      // 2-second grace period: gives backend webhook time to commit before navigation<br>      await new Promise((resolve) =&gt; setTimeout(resolve, 2000));<br>      navigate(&#39;/order-confirmation&#39;, { state: { orderId } });<br>    }<br>  } catch (err) {<br>    setErrorMessage(&#39;Payment execution failed. Please try again.&#39;);<br>  } finally {<br>    setIsProcessing(false);<br>  }<br>};</pre><h3>4. The Core Handshake: Payment Intent Lifecycle</h3><p>The client should never dictate prices to the backend. Checkout follows a strict two-step server-client negotiation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XxrB75b0K67z5FoRs-54g.png" /></figure><h3>Why BigDecimal Is Non-Negotiable</h3><p>Stripe expects all monetary amounts in the <strong>smallest currency unit</strong> (e.g., cents for USD or LKR).</p><p>Using native floating-point types (double or float) for currency multiplication is an unforgivable engineering mistake. Because computers represent floating-point numbers in binary (IEEE 754), fractional numbers cannot be represented with perfect decimal precision:</p><p>text</p><pre>19.99 × 100 = 1998.9999999999998 → 1998 cents</pre><p>A charge of $19.99 silently becomes $19.98. In high-volume systems, this generates thousands of 1-cent reconciliation discrepancies during accounting audits.</p><p>We mandate safe conversion using BigDecimal:</p><pre>// Convert to smallest currency unit (cents) safely without IEEE-754 precision loss<br>long amountInCents = amount.multiply(new BigDecimal(&quot;100&quot;)).longValue();</pre><h3>5. The Asynchronous Webhook Engine: Immutable Source of Truth</h3><p><strong>Never trust the frontend redirect to mark an order as paid.</strong></p><p>The customer’s phone battery can die the millisecond after their card is charged. Their browser tab can crash, or their cellular network can drop before your React callback reaches your backend.</p><p>Stripe’s webhook is the immutable, background source of truth. Stripe’s servers talk directly to your server over an encrypted backchannel, guaranteeing at-least-once event delivery.</p><h3>1. Cryptographic HMAC-SHA256 Verification</h3><p>Because the webhook endpoint is publicly exposed to the internet, it must verify that incoming HTTP POST requests genuinely originated from Stripe.</p><p>Stripe signs every payload using your whsec_ secret and includes the timestamp and signature in the Stripe-Signature header. Our server verifies this mathematically:</p><p>Java</p><pre>Event event;<br>try {<br>    event = Webhook.constructEvent(payload, sigHeader, endpointSecret);<br>} catch (SignatureVerificationException e) {<br>    log.warn(&quot;Webhook signature verification failed! Possible tampering attempt.&quot;);<br>    throw new PaymentGatewayException(&quot;Invalid signature&quot;);<br>}</pre><blockquote><strong><em>Engineering Tip:</em></strong><em> Make sure your logging filters do not read HttpServletRequest.getInputStream() before the controller receives it. In standard Java Servlet containers, the input stream can only be read once. If a filter consumes it, Spring binds an empty payload, causing all signature checks to fail.</em></blockquote><h3>2. Resilience Against API Version Drift</h3><p>Relying solely on the typed Stripe Java SDK deserializer is a production trap:</p><pre>// ⚠️ HIGH RISK IN PRODUCTION<br>PaymentIntent intent = (PaymentIntent) event.getDataObjectDeserializer().getObject().orElseThrow();</pre><p>When Stripe updates their global API version in the Dashboard (e.g., introducing a new parameter), older stripe-java libraries fail to map the new schema and throw an unhandled EventDataObjectDeserializationException. <strong>Your webhooks crash, and fulfillment halts.</strong></p><p>To make our backend <strong>100% resilient to third-party API changes</strong>, we parse the cryptographically verified raw JSON string using Spring’s Jackson ObjectMapper:</p><pre>if (&quot;payment_intent.succeeded&quot;.equals(event.getType())) {<br>    try {<br>        ObjectMapper mapper = new ObjectMapper();<br>        JsonNode root = mapper.readTree(payload);<br>        JsonNode objectNode = root.path(&quot;data&quot;).path(&quot;object&quot;);<br>        String transactionId = objectNode.path(&quot;id&quot;).asText(null);<br>                JsonNode metadata = objectNode.path(&quot;metadata&quot;);<br>                if (transactionId != null &amp;&amp; !metadata.isMissingNode()) {<br>                    String orderIdStr = metadata.path(&quot;orderId&quot;).asText(null);<br>                    String reservationIdStr = metadata.path(&quot;reservationId&quot;).asText(null);<br>                    if (orderIdStr != null &amp;&amp; !orderIdStr.isBlank()) {<br>                        handleSuccessfulOrderPayment(orderIdStr, transactionId, event.getId());<br>                    } else if (reservationIdStr != null &amp;&amp; !reservationIdStr.isBlank()) {<br>                        handleSuccessfulReservationPayment(reservationIdStr, transactionId, event.getId());<br>                    }<br>                }<br>         } catch (Exception e) {<br>                log.error(&quot;Failed to parse raw Stripe webhook payload&quot;, e);<br>            }<br>        }</pre><h3>6. Concurrency &amp; Atomic State Transitions</h3><p>Naive in-memory entity mutation (findById → setter → save) is vulnerable to <strong>Lost Update Anomalies</strong> if multiple threads or duplicate webhook retries process the same record simultaneously.</p><p>We enforce database-level atomic updates via custom JPQL @Modifying queries:</p><pre>@Repository<br>public interface PaymentRepository extends JpaRepository&lt;Payment, Long&gt; {<br>@Modifying<br>    @Transactional<br>    @Query(&quot;UPDATE Payment p SET p.paymentStatus = :status WHERE p.transactionReference = :txnRef&quot;)<br>    int updatePaymentStatusByTransactionReference(<br>            @Param(&quot;txnRef&quot;) String txnRef,<br>            @Param(&quot;status&quot;) PaymentStatus status<br>    );<br>    @Modifying<br>    @Transactional<br>    @Query(&quot;UPDATE Order o SET o.paymentStatus = :status WHERE o.id IN (SELECT p.order.id FROM Payment p WHERE p.transactionReference = :txnRef)&quot;)<br>    int updateOrderPaymentStatusByTxnRef(<br>            @Param(&quot;txnRef&quot;) String txnRef,<br>            @Param(&quot;status&quot;) PaymentStatus status<br>    );<br>}</pre><p>Executing the state transition directly inside the database engine guarantees thread-safety and completely eliminates Hibernate object dirty-checking race conditions.</p><h3>7. The Refund Pipeline: Partial Fees, Idempotency &amp; Side-Effect Reversal</h3><p>A payment system is only as mature as its refund pipeline. In restaurant operations, cancellations are frequent: an online order cancelled before kitchen prep starts, or a dining table booking cancelled days in advance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9dqW8Lp_BsCQmpw-_sNzw.png" /></figure><h3>Idempotency Keys Prevent Double Refunds</h3><p>What happens if your server calls Stripe to refund $50, Stripe executes the debit, but a network blip severs the connection before Stripe’s response reaches your server?</p><p>If your backend catches a socket timeout and automatically retries the HTTP request, Stripe might execute <strong>two successive $50 refunds</strong>, draining $100 from your merchant account.</p><p>We solve this using <strong>Stripe Idempotency Keys</strong>:</p><pre>// Pass a deterministic IdempotencyKey to ensure single financial execution<br>RequestOptions requestOptions = RequestOptions.builder()<br>    .setIdempotencyKey(&quot;order-cancel-&quot; + order.getId())<br>    .build();<br>Refund refund = Refund.create(builder.build(), requestOptions);</pre><p>Even if our server retries the refund five times across network drops, Stripe recognizes the identical key, executes the financial transaction <strong>exactly once</strong>, and returns the cached result for all subsequent requests.</p><h3>Reversing Side Effects: Loyalty, Coupons &amp; Lifetime Spend</h3><p>A monetary refund without reversing side-effect state opens massive fraud vectors. A malicious customer could place a $100 order to earn loyalty tier points, cancel the order, keep the points, and walk away with free food.</p><p>Our cancellation workflow enforces strict accounting reversals:</p><ol><li><strong>Restore Redeemed Points</strong> — Any reward points used to discount the bill are immediately refunded back to the customer’s balance.</li><li><strong>Claw Back Earned Points</strong> — Any loyalty points provisionally granted for the purchase are deducted.</li><li><strong>Restock Coupon Quotas</strong> — The usage count of any applied promo code is safely decremented.</li><li><strong>Decrement Lifetime Spend</strong> — The refunded amount is subtracted from customer.totalSpent so VIP loyalty tier qualifications remain mathematically accurate.</li></ol><h3>8. Real-Time Push with STOMP WebSockets</h3><p>Polling a REST API every 2 seconds to check whether an asynchronous payment or refund has finished is an anti-pattern: it thrashes database connection pools, spikes server CPU, and drains mobile batteries.</p><p>We built a real-time push engine using <strong>STOMP over SockJS</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgL12x92UjfGV1wNtJ_8IQ.png" /></figure><h3>Multi-Channel Push Architecture</h3><p>When a payment or refund status changes, our WebSocketNotificationService fans out updates across targeted topics:</p><ul><li>/topic/order/{orderId}/status — Subscribed by the customer actively viewing the order confirmation screen.</li><li>/topic/user/{userId}/orders — Subscribed globally across all customer devices and active browser tabs.</li><li>/topic/branch/{branchId}/admin-notifications — Subscribed by the branch manager and kitchen staff dashboards.</li></ul><p>On the frontend, our global notification listener intercepts these push events and renders actionable, interactive toast alerts:</p><pre>// React Global WebSocket Listener<br>client.subscribe(`/topic/user/${userId}/orders`, (message) =&gt; {<br>  try {<br>    const update = JSON.parse(message.body);<br>    const { paymentStatus, orderNumber, orderId } = update;<br>    const displayOrder = orderNumber || `#${orderId}`;<br>if (paymentStatus === &#39;REFUNDED&#39;) {<br>      toast.success(`Order ${displayOrder}: Payment has been refunded!`, {<br>        icon: &lt;Package size={20} /&gt;,<br>        onClick: () =&gt; navigate(&#39;/order-confirmation&#39;, { state: { orderId } }),<br>        style: { cursor: &#39;pointer&#39; },<br>      });<br>    }<br>  } catch (err) {<br>    console.error(&#39;Failed to parse WebSocket message&#39;, err);<br>  }<br>});</pre><h3>9. Battle-Tested Lessons</h3><ol><li><strong>Floating-point math is financial poison</strong> — Always use BigDecimal on the backend and integer cents in transit.</li><li><strong>Never consume the request InputStream twice</strong> — In Spring filters, reading the body consumes the stream and silently breaks cryptographic webhook signature verification.</li><li><strong>Webhooks are at-least-once</strong> — Expect events to arrive twice, out of order, or hours late. Design every handler to be strictly idempotent.</li><li><strong>Cold starts happen</strong> — On cloud platforms with container sleep cycles, rely on Stripe’s exponential-backoff retry policy (retries for up to 72 hours) to ensure zero dropped events.</li></ol><h3>10. Production Checklist</h3><ul><li><strong>Zero Raw Card Data:</strong> Are all card inputs isolated inside secure iframes? (Stripe Elements)</li><li><strong>Key Isolation:</strong> Are secret keys and webhook secrets restricted exclusively to backend environment variables?</li><li><strong>Asynchronous Fulfillment:</strong> Is your database status updated exclusively via verified webhooks, never via client redirects?</li><li><strong>Cryptographic Validation:</strong> Does the webhook listener verify HMAC-SHA256 signatures before reading JSON payloads?</li><li><strong>Version Resilience:</strong> Does your webhook parser gracefully tolerate new, unmapped fields from upstream API upgrades?</li><li><strong>Idempotent Financial Calls:</strong> Are all refund calls tagged with deterministic idempotency keys?</li><li><strong>Atomic DB Mutations:</strong> Are state updates handled via atomic database queries rather than in-memory dirty-checking?</li><li><strong>Side-Effect Reversals:</strong> Does your cancellation pipeline properly reverse coupons, reward points, and lifetime customer spend?</li></ul><p>Building payment systems means designing for the worst case: dropped connections, replayed events, race conditions, and flaky mobile clients. When you combine zero-trust frontends, cryptographic verification, and asynchronous eventual consistency, the system stays reliable even when the rest of the internet is having a bad day.</p><p><em>Found this architectural deep-dive useful? Drop your thoughts or payment war stories in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d72f8075c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Transfer Learning Helped Me Train a Currency Note Classifier for Raspberry Pi]]></title>
            <link>https://medium.com/@d.prabath115/how-transfer-learning-helped-me-train-a-currency-note-classifier-for-raspberry-pi-e7d9b9db41f6?source=rss-8cd80b3227a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7d9b9db41f6</guid>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Dileepa Prabhath]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 10:44:43 GMT</pubDate>
            <atom:updated>2026-08-28T12:55:55.195Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started working on <strong>CashMaster6688</strong>, a microcontroller-based currency sorting system for our 1st year hardware project, one of the biggest challenges was teaching a machine to recognize different Sri Lankan banknotes in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPFiYF2MxrRuWw6XrhyQPg.jpeg" /><figcaption>CASHMASTER 6688 System</figcaption></figure><p>We used Pi Camera Module 3 to detect notes and needed the system to run on a <strong>Raspberry Pi 4B 4GB</strong>, which meant the model had to be accurate <em>and</em> lightweight. Training a deep learning model from scratch was not practical within the time period. That’s where <strong>transfer learning</strong> became a gamechanger.</p><p>In this article, I’ll walk you through how I approached the training process, why I chose transfer learning, and what I learned along the way.</p><h3>The Problem</h3><p>I needed to classify the following classes:</p><ul><li>20 Rupee note</li><li>50 Rupee note</li><li>100 Rupee note</li><li>500 Rupee note</li><li>1000 Rupee note</li></ul><p>additionally, I used No note (empty compartment) to help for physical sorting system.</p><p>The images were captured using a Raspberry Pi Camera Module 3 under real hardware conditions. The dataset was relatively small (around 200–250 images per class), which made training a model from scratch risky due to overfitting.</p><h3>Why Transfer Learning?</h3><p>Training a convolutional neural network from scratch usually requires:</p><ul><li>Tens of thousands of images</li><li>Significant computational resources</li><li>A lot of time for hyperparameter tuning</li></ul><p>I didn’t have those luxuries.</p><p><strong>Transfer learning</strong> allowed me to start with a model that already understood basic visual features (edges, textures, shapes) from the large ImageNet dataset. I only needed to adapt the final layers to recognize banknotes.</p><p>This approach saved a huge amount of time and gave me much better results with limited data.</p><h3>Model Selection</h3><p>I experimented with two architectures:</p><ol><li><strong>MobileNetV2</strong> — Extremely lightweight and designed for mobile/edge devices</li><li><strong>EfficientNetB0</strong> — Slightly more accurate while still remaining efficient</li></ol><p>Both models are excellent choices for Raspberry Pi deployment because they balance accuracy and speed. I eventually converted the trained models to <strong>TensorFlow Lite</strong> for real-time inference.</p><p>As our Final Model <strong>MobileNetV2 </strong>was chosen which worked best with our hardware setup.</p><h3>Dataset Preparation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*eAexpupL0T7q5kGbVOz0PQ.png" /></figure><p>The dataset was organized in a simple folder structure:</p><pre>dataset/<br>├── 20/<br>├── 50/<br>├── 100/<br>├── 1000/<br>└── no_note/</pre><p>Before training, I applied several preprocessing steps:</p><ul><li>Resized all images to <strong>224×224</strong></li><li>Normalized pixel values</li><li>Applied data augmentation (rotation, zoom, shifts, brightness changes, horizontal flips)</li></ul><p>Data augmentation was crucial. Since the notes would be placed in slightly different positions and lighting conditions in the real system, augmentation helped the model generalize better.</p><h3>Training Process</h3><p>I used <strong>Google Colab</strong> for training. The process was divided into two stages:</p><figure><img alt="Google Colab screenshot 1" src="https://cdn-images-1.medium.com/max/1024/1*qpfTwaJmnIMEUdq10yAb8Q.png" /></figure><h4>Stage 1: Feature Extraction</h4><ul><li>Froze the base model (MobileNetV2 / EfficientNetB0)</li><li>Added a custom classification head:</li><li>Global Average Pooling</li><li>Dense layer (128 units)</li><li>Softmax output layer (5 classes)</li><li>Trained only the new layers with a higher learning rate</li></ul><h4>Stage 2: Fine-Tuning</h4><ul><li>Unfroze the later layers of the base model</li><li>Used a very small learning rate (1e-5)</li><li>Continued training with Early Stopping to prevent overfitting</li></ul><p>This two-stage approach is one of the most effective ways to apply transfer learning on small datasets.</p><h3>Challenges I Faced</h3><p>Even with transfer learning, I ran into several practical issues:</p><ul><li><strong>Overfitting</strong> <strong><br></strong><em>Applied strong data augmentation + early stopping.</em></li><li><strong>Class imbalance / small dataset</strong><br><em>Used transfer learning instead of training from scratch.</em></li><li><strong>Color differences (training vs. Pi camera)</strong> <br><em>Matched preprocessing carefully <br>Use real image captured from same camera use to detect notes.</em></li><li><strong>Large model size for Raspberry Pi</strong><br><em>Converted final model to TensorFlow Lite which is light version of TensorFlow Model.</em></li></ul><h3>Results</h3><p>With transfer learning, I was able to reach <strong>over 90% validation accuracy</strong> in a relatively short time. Training from scratch with the same dataset would have been much less effective.</p><p>The final model was converted to .tflite format and successfully ran on the Raspberry Pi with acceptable inference speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*r9riLB3FWIdN8Wna93v8Mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*VfhvDrB-V9GA2GH5bRxqbw.png" /></figure><h3>Key Takeaways</h3><ul><li>Transfer learning is extremely powerful when you have limited data and time.</li><li>Choosing the right architecture (MobileNet / EfficientNet) is important for edge deployment.</li><li>Data augmentation and careful preprocessing matter just as much as the model itself.</li><li>Always match the preprocessing between training and inference.</li></ul><h3>Final Thoughts</h3><p>Building the note recognition system for CashMaster6688 taught me that you don’t always need massive datasets or powerful GPUs to create useful AI applications. With transfer learning and careful engineering, even a small dataset can power a real hardware product.</p><p>If you’re working on a similar edge AI project, I highly recommend starting with transfer learning, it can save you weeks of work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7d9b9db41f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>