<?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 Avishka Akalanka on Medium]]></title>
        <description><![CDATA[Stories by Avishka Akalanka on Medium]]></description>
        <link>https://medium.com/@avishkabiz123?source=rss-c06281554326------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QaWE-IKW6G9bdBFhVDzT6w.jpeg</url>
            <title>Stories by Avishka Akalanka on Medium</title>
            <link>https://medium.com/@avishkabiz123?source=rss-c06281554326------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:37:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@avishkabiz123/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[When 1,000 Requests Hit at Once: Solving a Flash Sale Race Condition with Java]]></title>
            <link>https://medium.com/@avishkabiz123/when-1-000-requests-hit-at-once-solving-a-flash-sale-race-condition-with-java-85f9234bcde7?source=rss-c06281554326------2</link>
            <guid isPermaLink="false">https://medium.com/p/85f9234bcde7</guid>
            <category><![CDATA[shared-lock]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[thread-synchronization]]></category>
            <category><![CDATA[java-concurrency]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[Avishka Akalanka]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 09:31:57 GMT</pubDate>
            <atom:updated>2026-09-11T17:18:19.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrSXsbbd31CzWUBSRWwD0g.png" /></figure><p>Imagine an e-commerce platform launching a flash sale with <strong>only 10 units</strong> of a highly demanded product, while hundreds of customers try to purchase it at the same time.</p><p>The logic seems simple:</p><ul><li><strong>Check the stock -&gt; reduce the stock -&gt; create the order.</strong></li></ul><p>But what happens when hundreds of requests execute this logic concurrently? Could multiple customers purchase the same last item? Could the system accept more successful orders than the available inventory?</p><p>This is where <strong>concurrency and race conditions</strong> become real-world problems.</p><p>To explore this, I built a Flash Sale application using Java and Spring Boot that simulates concurrent purchase requests and demonstrates inventory overselling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvPErpRoA-4HcO3k2NKn-A.png" /><figcaption>Flash Sale application</figcaption></figure><p>In this article, we’ll understand Java multithreading and concurrency, reproduce the race condition, and explore different approaches to make the system <strong>thread-safe</strong>.</p><h3>1. What Is Multithreading?</h3><p>Before looking at the Flash Sale problem, let’s briefly understand <strong>multithreading</strong>.</p><p>A <strong>thread</strong> is a unit of execution within a process. A Java application can have multiple threads working on different tasks at the same time.</p><p>For example</p><pre>Java Application<br>│<br>├── Main Thread<br>├── Thread 1<br>├── Thread 2<br>└── Thread 3</pre><p>Instead of processing every task sequentially, multiple threads can make progress concurrently. This is especially useful in applications such as <strong>web servers</strong>, where many requests may need to be handled at the same time.</p><p>However, multiple threads can also <strong>share application resources and data</strong>. This becomes a problem when more than one thread tries to access or modify the same mutable data at the same time.</p><blockquote><strong><em>What happens when multiple threads try to access and modify the same data concurrently?</em></strong></blockquote><p>That question is at the heart of our Flash Sale problem.</p><p>In the next section, we’ll briefly look at <strong>concurrency and parallelism</strong>, and then see how shared data can lead to a <strong>race condition</strong>.</p><h3>2. Concurrency vs Parallelism</h3><p>The terms <strong>concurrency</strong> and <strong>parallelism</strong> are often used together, but they describe different ideas.</p><h3>Concurrency</h3><p><strong>Concurrency</strong> means multiple tasks can make progress during overlapping periods of time.</p><p>In our Flash Sale application, multiple customers may send purchase requests at nearly the same time</p><pre>Customer 1 ──► Purchase Request<br>Customer 2 ──► Purchase Request<br>Customer 3 ──► Purchase Request<br>Customer 4 ──► Purchase Request</pre><p>These requests can be handled concurrently by different threads.</p><h3>Parallelism</h3><p><strong>Parallelism</strong> means multiple tasks are actually executing at the same time, typically on different CPU cores.</p><pre>CPU Core 1 ──► Task A</pre><pre>CPU Core 2 ──► Task B</pre><p>The distinction is important, but for our Flash Sale problem, <strong>concurrency is the key concept</strong>.</p><p>The problem isn’t simply that multiple requests are running at the same time. The real problem begins when those requests <strong>access and modify the same inventory data concurrently</strong>.</p><p>That brings us to the next question</p><blockquote><strong><em>What happens when multiple threads access the same mutable data?</em></strong></blockquote><h3>3. The Problem with Shared Mutable State</h3><p>Creating multiple threads is relatively easy. The real challenge begins when those threads need to <strong>access and modify the same data</strong>.</p><p>Consider our Flash Sale application.</p><p>Suppose a product has</p><pre>Product<br>----------------<br>Name  : Gaming Laptop<br>Stock : 1<br>----------------</pre><p>Now imagine two customers trying to purchase the last item at almost exactly the same time</p><pre>Customer A ──┐<br>             ├──► Product<br>Customer B ──┘</pre><p>Both requests need to</p><ol><li>Check the available stock.</li><li>Reduce the stock.</li><li>Save the updated product.</li><li>Create the order.</li></ol><p>The logic seems straightforward.</p><p>But because these requests can be processed by different threads, both threads may access the same inventory before either one has finished updating it.</p><p>This creates a <strong>race condition</strong>.</p><p>And this is exactly the problem we want to reproduce with our Flash Sale application.</p><h3>4. Where the Race Condition Begins</h3><p>Let’s look at the order-processing logic in our Flash Sale application.</p><p>When a customer places an order, the application first retrieves the product</p><pre>Product product = productRepository.findById(<br>        createOrderRequest.getProductId()<br>).orElseThrow(...);</pre><p>It then checks whether enough stock is available</p><pre>if (product.getStock() &gt;= createOrderRequest.getQuantity()) {<br>    product.setStock(<br>        product.getStock() - createOrderRequest.getQuantity()<br>    );<br><br>productRepository.save(product);<br>    status = &quot;SUCCEEDED&quot;;<br>}</pre><p>In a single-threaded environment, this logic appears perfectly reasonable</p><pre>Read Stock<br>    ↓<br>Check Stock<br>    ↓<br>Reduce Stock<br>    ↓<br>Save Product<br>    ↓<br>Create Order</pre><p>The problem appears when <strong>multiple requests execute this logic concurrently</strong>.</p><p>Imagine the product has only <strong>1 item remaining</strong>, and two customers send purchase requests at nearly the same time</p><pre>              Product Stock = 1<br>                     │<br>             ┌───────┴───────┐<br>             ↓               ↓<br>        Customer A       Customer B<br>             │               │<br>             ↓               ↓<br>        Read stock = 1   Read stock = 1<br>             │               │<br>             ↓               ↓<br>          Check OK          Check OK<br>             │               │<br>             ↓               ↓<br>        Reduce to 0       Reduce to 0<br>             │               │<br>             └───────┬───────┘<br>                     ↓<br>              Both succeed</pre><p>Both threads read the same stock value <strong>before either update becomes visible to the other</strong>.</p><p>As a result, both requests can be marked as successful even though only one item was available.</p><p>This is a classic <strong>race condition</strong>: the final result depends on the timing and interleaving of concurrent operations.</p><p>The dangerous part is not the individual getStock() or save() calls. It is the entire <strong>read → check → modify → save</strong> sequence being executed concurrently without a mechanism to coordinate access.</p><p>And this is exactly what our Flash Sale application is designed to demonstrate.</p><h3>5. Reproducing the Race Condition</h3><p>To see the race condition in action, I ran a high-concurrency purchase test against the Flash Sale application.</p><p>For the test, a product started with <strong>100 units of inventory</strong>, while <strong>1,000 purchase requests</strong> were processed concurrently.</p><p>The dashboard allows us to observe the results in real time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*SFzF6HxJHXG7wsVz5LjcHA.png" /><figcaption>Load Test Results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTiJTSnHg9K2FpIOCMnA3w.png" /><figcaption>Dashboard Results</figcaption></figure><p>The expected behavior is straightforward</p><blockquote><em>If only </em><strong><em>100 units</em></strong><em> are available, at most </em><strong><em>100 orders</em></strong><em> should succeed.</em></blockquote><p>However, our naive implementation produced 646 <strong>successful orders</strong>.</p><p>That means</p><pre>Initial Stock       = 100<br>Successful Orders   = 646<br><br>Oversold            = 646 - 100<br>                    = 546</pre><p>This is exactly what we wanted to demonstrate.</p><p>The application isn’t failing because the stock calculation itself is incorrect. The problem is that <strong>multiple concurrent requests can read the same inventory state before the previous update has been safely coordinated</strong>.</p><p>This gives us a concrete example of why the following code is unsafe under high concurrency</p><pre>if (product.getStock() &gt;= quantity) {<br>    product.setStock(product.getStock() - quantity);<br>    productRepository.save(product);<br>}</pre><h3>6. Making the Flash Sale Thread-Safe</h3><p>Now that we’ve reproduced the problem, the next question is</p><blockquote><strong><em>How can we safely handle multiple requests trying to modify the same inventory?</em></strong></blockquote><p>The goal is simple</p><pre>Initial Stock = 100</pre><pre>Successful Orders ≤ 100</pre><p>Regardless of whether we receive 10, 100, or 1,000 concurrent purchase requests, the system must never allow more orders than the available inventory.</p><p>There isn’t a single solution to concurrency problems. The right approach depends on <strong>where the shared state exists and how the application is deployed</strong>.</p><p>For our Flash Sale application, we can explore several approaches</p><pre>                  Thread Safety<br>                         │<br>        ┌────────────────┼─────────────────┐<br>        ↓                ↓                 ↓<br>   Java-level       Database-level    Distributed<br>   Synchronization  Concurrency       Coordination<br>        │                │                 │<br>   synchronized      DB Locks          Redis Lock<br>                     @Version<br>                     Atomic UPDATE</pre><p>We’ll start with the simplest approach: <strong>Java’s </strong><strong>synchronized keyword</strong>.</p><h3>6.1 Using synchronized</h3><p>The synchronized keyword allows us to protect a critical section so that only one thread can execute it at a time for the same lock.</p><p>For example:</p><pre>public synchronized void purchase() {<br>    // Check stock<br>    // Reduce stock<br>    // Save product<br>}</pre><p>Conceptually:</p><pre>Thread A ──►  🔒   Critical Section ──► Release<br>Thread B ──►        WAIT            ──► Execute<br>Thread C ──►        WAIT            ──► Execute</pre><p>This can prevent multiple threads from modifying shared state at the same time and therefore helps eliminate the race condition.</p><p>However, <strong>thread safety comes with a performance trade-off</strong>.</p><p>When one thread holds the lock, other threads attempting to enter the same synchronized section have to wait</p><pre>Thread A ──► Processing ──► Release Lock<br>                              │<br>Thread B ──► Waiting ─────────┘<br>Thread C ──► Waiting ─────────┘<br>Thread D ──► Waiting ─────────┘</pre><p>If the critical section takes a long time or receives a large number of concurrent requests, this waiting can increase <strong>request response time</strong> and reduce overall throughput.</p><p>In our Flash Sale scenario, imagine hundreds of customers trying to purchase products simultaneously. If every purchase has to wait for a single lock, requests may form a queue</p><pre>100 concurrent requests<br>          ↓<br>   ┌─────────────┐<br>   │ synchronized│<br>   └──────┬──────┘<br>          ↓<br>   One thread at a time<br>          ↓<br>   Increased waiting<br>          ↓<br>   Higher response time</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAjInzSNv5cmWtJK3kCHlw.png" /><figcaption>Flash Sale Load Test Results with Synchronized keyword</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ni4rLH5Gdu4ttOi0LhHXcA.png" /><figcaption>FlashSale Dashboard Results Synchronized keyword</figcaption></figure><p>So while synchronized can solve the race condition at the JVM level, it may not be the most efficient solution for a high-concurrency application.</p><p>There is also another important limitation.</p><p>Our Spring Boot application could eventually run as multiple instances</p><pre>Load Balancer<br>                  │<br>       ┌──────────┼──────────┐<br>       ↓          ↓          ↓<br>   Instance 1  Instance 2  Instance 3<br>      JVM          JVM         JVM</pre><p>A Java synchronized lock exists <strong>inside a single JVM</strong>. It cannot coordinate access between separate application instances.</p><p>Therefore, synchronized is useful for understanding and controlling <strong>JVM-level concurrency</strong>, but for shared inventory in a distributed application, we may need a solution at the <strong>database or distributed-system level</strong>.</p><p>This leads us to our next approach: <strong>database locking</strong>.</p><h3>6.2 Database-Level Concurrency Control</h3><p>The synchronized approach protects the critical section <strong>inside a single JVM</strong>, but our inventory is ultimately stored in <strong>PostgreSQL</strong>.</p><p>That raises an important question</p><blockquote><em>What happens when multiple application threads try to update the same database record at the same time?</em></blockquote><p>For an inventory system, we need the database to help maintain consistency.</p><p>There are several ways to approach this, including:</p><ul><li><strong>Pessimistic locking</strong></li><li><strong>Optimistic locking</strong></li><li><strong>Atomic database updates</strong></li></ul><p>Let’s start with <strong>pessimistic locking</strong>.</p><h3>6.2.1 Pessimistic Locking</h3><p>Pessimistic locking assumes that concurrent conflicts are likely, so the database <strong>locks the record while it is being processed</strong>.</p><p>In our Flash Sale application, we can use JPA’s</p><pre>@Lock(LockModeType.PESSIMISTIC_WRITE)</pre><p>The locked read should execute within a transaction so that the database lock is held for the required duration of the operation.</p><p>The flow becomes</p><pre>Thread A<br>   │<br>   ↓<br>Acquire Product Lock<br>   │<br>   ↓<br>Read Stock<br>   │<br>   ↓<br>Check &amp; Update Stock<br>   │<br>   ↓<br>Commit Transaction<br>   │<br>   ↓<br>Release Lock<br>   │<br>   ▼<br>Thread B can continue</pre><p>While Thread A holds the lock, another transaction trying to modify the same product must wait.</p><p>This prevents two transactions from simultaneously modifying the same inventory record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*d8SeVNqP-6PjnxvjDED1oA.png" /><figcaption>Flash Sale Load Test Results with Pessimistic Locking</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyeJdf0bk1idLZXzUwV74A.png" /><figcaption>Flash Sale Dashboard Results with Pessimistic Lock</figcaption></figure><h3>The Trade-off</h3><p>Pessimistic locking provides strong protection against concurrent updates, but it also introduces <strong>waiting and contention</strong>.</p><p>If hundreds of customers try to purchase the same product</p><pre>       100 Requests<br>             │<br>             ↓<br>      ┌──────────────┐<br>      │ Product Lock │<br>      └───────┬──────┘<br>              │<br>       One transaction<br>          at a time<br>              │<br>              ↓<br>       Other transactions<br>            WAIT</pre><p>Therefore, while pessimistic locking can prevent overselling, excessive contention can increase <strong>response time and reduce throughput</strong>.</p><p>This is an important trade-off</p><blockquote><strong><em>The stronger the coordination, the more carefully we need to consider its performance impact.</em></strong></blockquote><p>Next, we’ll look at a different strategy that doesn’t immediately block competing transactions: <strong>optimistic locking with </strong><strong>@Version</strong>.</p><h3>6.2.2 Optimistic Locking with @Version</h3><p>Pessimistic locking assumes that conflicts are likely and prevents them by locking the database row while it is being processed.</p><p>But what if we don’t want every request to wait for a database lock?</p><p>This is where <strong>optimistic locking</strong> comes in.</p><p>Instead of locking the row when it is read, optimistic locking allows multiple transactions to read the same data. Before updating, the database checks whether another transaction has already modified that record.</p><h3>How @Version Works</h3><p>With JPA, optimistic locking can be implemented using the @Version annotation.</p><pre>@Entity<br>public class Product {<br>    @Id<br>    private Long id;<br>    private String name;<br>    private int stock;<br>    @Version<br>    private Long version;<br>}</pre><p>The version field is automatically managed by JPA.</p><p>Suppose the product initially has</p><pre>Stock   = 100<br>Version = 5</pre><p>Two requests can read the same product</p><pre>Product<br>          Stock = 100<br>          Version = 5<br>              │<br>        ┌─────┴─────┐<br>        ↓           ↓<br>    Thread A     Thread B<br>   Version 5     Version 5</pre><p>Thread A updates the product first</p><pre>Stock   → 99<br>Version → 6</pre><p>When Thread B tries to update the product using the old version 5, the update no longer matches the current version.</p><p>Conceptually, the database update behaves like</p><pre>UPDATE product<br>SET stock = 99,<br>    version = 6<br>WHERE id = 1<br>  AND version = 5;</pre><p>Because the current version is already 6, the update affects <strong>zero rows</strong>.</p><p>When the transaction attempts to update the entity using the stale version, JPA detects that the version no longer matches and can throw an OptimisticLockException.</p><h3>Why Is This Useful?</h3><p>Optimistic locking allows multiple requests to proceed without immediately blocking each other.</p><p>Instead of</p><pre>Request A → Lock<br>Request B → Wait<br>Request C → Wait<br>Request D → Wait</pre><p>requests can work concurrently, and conflicts are detected when an update is attempted.</p><h3>Trade-off</h3><p>Optimistic locking does not prevent conflicts. It <strong>detects</strong> them.</p><p>Therefore, the application needs a strategy for handling the failed update, such as</p><ul><li>Retrying the operation</li><li>Returning an appropriate failure response</li><li>Re-reading the latest inventory and trying again</li><li>Handling the conflict according to the business requirement</li></ul><p>For a flash sale with extremely high contention on a single product, many requests may still conflict. Therefore, optimistic locking can be useful, but it is not automatically the best solution for every high-concurrency inventory system.</p><p>The important difference is</p><blockquote><strong><em>Pessimistic locking prevents conflicts by making requests wait. optimistic locking allows concurrent work and detects conflicts when updating.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTtr0kMH11x4JlnHo00KzA.png" /><figcaption>Flash Sale Load Test Results with optimistic Locking</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_z27-t03UG2L2iuY64nT9w.png" /><figcaption>Flash Sale Dashboard Results with optimistic locking</figcaption></figure><p>Now let’s look at another approach that is particularly interesting for inventory systems: <strong>atomic database updates</strong>.</p><h3>6.2.3 Atomic Database Updates</h3><p>Optimistic locking detects conflicts after they occur, but there is another approach that can be very effective for inventory operations: <strong>atomic database updates</strong>.</p><p>The main problem with our original implementation is that the stock check and stock update happen as separate operations</p><pre>Read Stock<br>    ↓<br>Check Stock<br>    ↓<br>Reduce Stock<br>    ↓<br>Save Product</pre><p>Under high concurrency, multiple requests can read the same stock value before any of them updates it.</p><p>Instead, we can ask the database to perform the <strong>stock check and decrement as one atomic operation</strong>.</p><p>For example:</p><pre>UPDATE product<br>SET stock = stock - 1<br>WHERE id = 1<br>  AND stock &gt;= 1;</pre><p>The important part is:</p><pre>AND stock &gt;= 1</pre><p>The database will only perform the update if enough inventory is available.</p><h3>Using This with Spring Data JPA</h3><p>We can define an update query in our repository</p><pre>@Modifying<br>@Query(&quot;&quot;&quot;<br>    UPDATE Product p<br>    SET p.stock = p.stock - :quantity<br>    WHERE p.id = :productId<br>      AND p.stock &gt;= :quantity<br>&quot;&quot;&quot;)<br>int decreaseStock(<br>        @Param(&quot;productId&quot;) Long productId,<br>        @Param(&quot;quantity&quot;) int quantity<br>);</pre><p>The return value tells us whether the update actually happened.</p><pre>int updatedRows = productRepository.decreaseStock(<br>        productId,<br>        quantity<br>);</pre><p>If</p><pre>updatedRows = 1</pre><p>the stock was successfully decreased.</p><p>If</p><pre>updatedRows = 0</pre><p>there was not enough stock, or the product could not be updated.</p><p>The important difference is that we no longer need to separately read the stock and then decide whether we can reduce it.</p><p>Instead, the database performs the operation atomically</p><pre>            Purchase Request<br>                    │<br>                    ↓<br>        ┌──────────────────────┐<br>        │ Atomic UPDATE        │<br>        │                      │<br>        │ stock &gt;= quantity ?  │<br>        │        │             │<br>        │    ┌───┴───┐         │<br>        │   YES      NO        │<br>        │    │        │        │<br>        │    ↓        ↓        │<br>        │ Decrease   Reject    │<br>        │ Stock      Request   │<br>        └──────────────────────┘</pre><p>This is particularly useful for a Flash Sale because the inventory operation is reduced to a single database statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bva4VLLfwAQot31LLnv5SQ.png" /><figcaption>Flash Sale Dashboard Results with Atomic Database updates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gezhiZiIAS_c-3fQ0bPSrw.png" /><figcaption>Load testing results with Atomic updates</figcaption></figure><h3>Why Is This Better?</h3><p>Consider an inventory of 100 units and 1,000 concurrent purchase requests.</p><p>The database ensures that the condition</p><pre>stock &gt;= requested quantity</pre><p>is evaluated as part of the update itself.</p><p>Once the stock reaches zero, subsequent updates cannot decrease it further.</p><p>Therefore:</p><pre>Initial Stock       = 100<br>Maximum Successful  = 100<br>Oversold            = 0</pre><p>This approach avoids the application-level <strong>read → check → modify → save</strong> race that caused our original implementation to oversell.</p><h3>Trade-offs</h3><p>Atomic updates are powerful, but they are not a universal solution.</p><p>They work particularly well when the business operation can be expressed as a single atomic database statement.</p><p>However, more complex business logic may require additional operations or transaction handling.</p><p>For example, a purchase may involve</p><pre>Decrease Inventory<br>       ↓<br>Create Order<br>       ↓<br>Process Payment<br>       ↓<br>Publish Event</pre><p>The inventory update itself can be atomic, but the entire business workflow may require additional concurrency and transaction considerations.</p><p>This leads to an important distinction</p><blockquote><strong><em>An atomic database update can make a specific inventory operation thread-safe, but it does not automatically make the entire business workflow thread-safe.</em></strong></blockquote><p>For our Flash Sale application, however, this approach gives us a very important property: <strong>the database itself decides whether inventory can be consumed.</strong></p><h3>6.3 Distributed Locking with Redis</h3><p>So far, we’ve mainly looked at concurrency control within a single application instance or through the database.</p><p>But consider a production environment where our Spring Boot application is running on multiple servers</p><pre>Load Balancer<br>                         │<br>             ┌───────────┼───────────┐<br>             ↓           ↓           ↓<br>        Instance 1   Instance 2   Instance 3<br>             │           │           │<br>             └───────────┼───────────┘<br>                         ↓<br>                     Database</pre><p>A Java synchronized lock only exists inside one JVM.</p><p>For example, a request handled by Instance 1 cannot see a synchronized lock held by Instance 2.</p><p>This means application-level synchronization cannot provide coordination across multiple instances.</p><p>One solution is to use a <strong>distributed lock</strong>.</p><h3>Using Redis for Distributed Locking</h3><p>Redis is an in-memory data store that can also be used to coordinate access between multiple application instances.</p><p>The idea is to create a shared lock in Redis</p><pre>Redis<br>         ┌─────────────┐<br>         │ Flash Lock  │<br>         └──────┬──────┘<br>                │<br>       ┌────────┼────────┐<br>       ↓        ↓        ↓<br> Instance 1  Instance 2  Instance 3</pre><p>Suppose Instance 1 acquires the lock</p><pre>Instance 1 → Acquire Lock<br>Instance 2 → Wait / Retry<br>Instance 3 → Wait / Retry</pre><p>Instance 1 can then perform the protected operation and release the lock afterward.</p><p>Because the lock is stored in a shared system, all application instances can coordinate around the same resource.</p><h3>Why Is This Different from synchronized?</h3><p>With synchronized:</p><pre>JVM 1<br> └── synchronized lock</pre><p>With a distributed lock:</p><pre>JVM 1 ──┐<br>JVM 2 ──┼──→ Redis Lock<br>JVM 3 ──┘</pre><p>The important difference is <strong>where the lock lives</strong>.</p><p>A JVM-level lock belongs to one application instance, while a distributed lock is stored in a system shared by multiple instances.</p><h3>Trade-offs</h3><p>Distributed locking introduces additional complexity.</p><p>The system needs to consider</p><ul><li>Lock expiration</li><li>Network failures</li><li>Lock ownership</li><li>Retry behavior</li><li>What happens if an instance crashes while holding the lock</li><li>Additional infrastructure and operational overhead</li></ul><p>It can also become a bottleneck if too many requests compete for the same lock.</p><p>For example, if thousands of customers are trying to purchase the same product</p><pre>1,000 Requests<br>      ↓<br>Distributed Lock<br>      ↓<br>One request at a time<br>      ↓<br>Potential contention</pre><p>Therefore, distributed locking should not automatically be the first solution for every concurrency problem.</p><p>For our Flash Sale application, the database already owns the inventory state. That makes <strong>database-level atomic operations and locking particularly relevant</strong>.</p><p>Redis becomes more useful when we need coordination that extends beyond a single database operation, for example, coordinating distributed application processes or protecting a larger critical workflow.</p><p>The key lesson is</p><blockquote><strong><em>When an application is distributed across multiple JVMs, concurrency control must be shared across those instances.</em></strong></blockquote><p>At this point, we’ve seen several ways to protect shared state. Let’s see how this works in our Flash Sale application.</p><h3>6.3.1 Flash Sale Implementation</h3><p>To test this approach, I ran two Spring Boot instances locally. Both instances share the same Redis lock manager and PostgreSQL database.</p><p>The lock is acquired for a specific product before processing the order and released after the operation is completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oz8wOSjXJfpp-A84-PoCbw.png" /><figcaption>System Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4R9FKHcOvhX3JLdzvBQIA.png" /><figcaption>Execution Work Flow</figcaption></figure><p>We then ran the same 1,000 request concurrent load test. The result was</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D46gGkv0FmwuIo9T1ax9wQ.png" /><figcaption>Load Test Results over multiple instance with Redis locking</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coBcWglIsBgpqu_ctjr42A.png" /><figcaption>Dashboard overall results</figcaption></figure><p>The dashboard also confirmed that all <strong>100 available units were sold without overselling</strong>.</p><p>The load test took longer because concurrent requests had to wait for the shared lock, but the inventory remained consistent across both application instances.</p><p>This demonstrates that a <strong>shared distributed lock can coordinate concurrent access across multiple JVMs</strong>, unlike a JVM-level synchronized lock.</p><h3>11. Conclusion</h3><p>Building this Flash Sale application showed how a simple operation like</p><pre>Check Stock → Reduce Stock → Create Order</pre><p>can become a serious problem when multiple requests execute concurrently.</p><p>Our initial implementation resulted in significant overselling under high concurrency. By exploring different approaches, including synchronized, pessimistic locking, optimistic locking, atomic database updates, and distributed locking, we saw how concurrency can be controlled at different levels.</p><p>The key takeaway is that <strong>thread safety is not only about managing Java threads</strong>. When multiple threads or application instances access shared state, we need to carefully consider where that state lives and choose the appropriate synchronization mechanism.</p><p>For applications running across multiple JVMs, a local lock such as synchronized is not sufficient. Shared database mechanisms or distributed locks can be used when cross-instance coordination is required.</p><p>Most importantly, concurrency should be considered as a <strong>correctness problem</strong>, not just a performance problem.</p><blockquote><strong><em>The goal isn’t to eliminate concurrency. The goal is to control it correctly.</em></strong></blockquote><h3>Explore the Project</h3><p>You can explore the complete Flash Sale application, including the concurrency implementations and load-testing code, on GitHub</p><blockquote><strong><em>GitHub Repository: </em></strong><a href="https://github.com/AvishkaWPA/Flash-Sale-Demo"><strong><em>Flash Sale Concurrency &amp; Multi-Threading Demo</em></strong></a></blockquote><p>Feel free to clone the project, run the application, and experiment with the different concurrency-control approaches discussed in this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85f9234bcde7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powering PWAs with Web Push Notifications: A Complete Guide Using React, Firebase & Spring Boot]]></title>
            <link>https://medium.com/@avishkabiz123/powering-pwas-with-web-push-notifications-a-complete-guide-using-react-firebase-spring-boot-0b40011fbb19?source=rss-c06281554326------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b40011fbb19</guid>
            <dc:creator><![CDATA[Avishka Akalanka]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 18:48:03 GMT</pubDate>
            <atom:updated>2025-06-03T18:48:03.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAP-lCVTVnWnl-jta9st-g.png" /></figure><h3><strong>PWA - Progressive web application</strong></h3><p><em>It’s a web application built using standard web technologies (HTML, CSS, JavaScript) that behaves like a native mobile app.</em><strong><em> </em></strong><em>It enables,</em></p><ul><li><em>Work offline</em></li><li><em>Be installed on the user’s device (like an app)</em></li><li><em>Send push notifications</em></li><li><em>Load fast, even on slow networks</em></li><li><em>Run in full screen, without a browser UI</em></li></ul><h3><strong>Web Push Notifications</strong></h3><p><em>Web Push Notifications are messages sent from your server to a user’s browser, even when the user is </em><strong><em>not actively using your site</em></strong><em>.</em></p><p><em>When paired with a PWA, push notifications become a superpower</em></p><ul><li><em>Users get real-time updates, like a mobile app would send.</em></li><li><em>Your app stays top of mind, even after the tab is closed.</em></li></ul><blockquote><strong>Use Cases ??</strong></blockquote><p><em>E-Commerce platforms : notify users about order status, payments updates, or flash sales.</em></p><p><em>News and Content Platforms : alert users about breaking news or trending topics.</em></p><p><em>Social Platforms : let users know when they get a message, like, or comment.</em></p><blockquote><strong>Services for Web Push Notifications ??</strong></blockquote><p><em>Firebase Cloud Messaging (FCM)</em></p><p><em>Amazon SNS (Simple Notification Service)</em></p><p><em>Manual Push (VAPID + Service Workers</em><strong><em>)</em></strong></p><blockquote><strong>Why Firebase Cloud Messaging ??</strong></blockquote><p><em>Firebase Cloud Messaging (FCM) is a free, reliable service for sending push notifications across web and mobile platforms. It’s easy to integrate with React and Spring Boot, supports background delivery through service workers, and scales well for large user bases. FCM also integrates seamlessly with other Firebase tools, making it a solid choice for real-time, cross-platform notifications, especially in PWAs.</em></p><blockquote><strong>How this works ??</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTS-g0-F_C9-LCqQXisBWA.png" /></figure><p><em>When a user accesses the PWA, their browser registers with Firebase and receives a unique device token. This token is then sent to the backend application, which stores it for future use. Whenever the backend needs to send a notification ,such as for a new message, update, or alert, it sends a request to Firebase along with the message and the user’s token. Firebase then delivers the notification directly to the user’s browser. If the app is not open, the PWA’s service worker takes over and displays the notification.</em></p><h3><strong>How Can We Implement This</strong></h3><p><strong>Part 1: Initialize Firebase</strong></p><blockquote><a href="https://firebase.google.com/docs/web/setup#create-firebase-project-and-app">Create a Firebase project and register your app</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJUmEaOxIZr0K8d0DY8n6w.png" /><figcaption>Firebase console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BAgT2cgqFk_0KI_sd5QlmQ.png" /><figcaption>create project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWODG3xrL_ak5mWEtO5ufw.png" /><figcaption>Project console</figcaption></figure><p><em>click the </em><strong><em>Web</em></strong><em> icon (&lt;/&gt;) to launch the setup workflow.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lw1D4oSPyU8fc1fVpMDuMg.png" /><figcaption>register your app with project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuJ5XA8G0HVPkgJK0BKPKw.png" /><figcaption>here you will guide to setup your front end</figcaption></figure><h3><strong>Part 2: Setup Frontend with React</strong></h3><blockquote><a href="https://firebase.google.com/docs/web/setup#add-sdks-initialize">Install the SDK and initialize Firebase</a></blockquote><ol><li>install firebase client SDK using your package manager</li></ol><pre>npm install firebase</pre><p>In Progressive Web Apps (PWAs), web push notifications typically fall into two categories:</p><blockquote><strong>Background Notifications</strong>: Delivered when the app is closed or not active. These rely on <strong>Service Workers</strong> to show system-level notifications, even when the browser isn’t open.</blockquote><blockquote><strong>Foreground Notifications</strong>: Received while the user is actively using the app. These are usually shown as custom in-app alerts or toast messages</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYNjZhuZnJv92OvGazohew.png" /></figure><h3>2. Setup Foreground Notifications : in-app notifications</h3><blockquote><a href="https://firebase.google.com/docs/cloud-messaging/js/client#add-initialize-sdk">Add firebase configuration file</a> -src/config/firebase.js</blockquote><pre>import { initializeApp } from &quot;firebase/app&quot;;<br>import { getMessaging, getToken, onMessage } from &quot;firebase/messaging&quot;;<br><br>export const firebaseConfig = {<br>  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,<br>  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,<br>  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,<br>  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,<br>  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,<br>  appId: process.env.REACT_APP_FIREBASE_APP_ID,<br>  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID,<br>};<br><br><br>const app = initializeApp(firebaseConfig);<br>const messaging = getMessaging(app);<br><br>//handle foreground messages<br>onMessage(messaging, ({ data, fcmOptions }) =&gt; {<br>  console.log(&quot;Message received in foreground:&quot;, data);<br><br>  const link = data?.url || &quot;/&quot;; // fallback link<br><br>  const notif = new Notification(data.title, {<br>    body: data.body,<br>    icon: &quot;/logo192.jpg&quot;,//give any image url which availabele on frontend side <br>    image: data.image,<br>    data: { url: link }, // store URL inside notification<br>  });<br><br>//handling notification click event<br>  notif.onclick = (event) =&gt; {<br>    event.preventDefault(); // prevent default behavior<br>    window.open(link, &quot;_blank&quot;);<br>  };<br>});<br><br><br>//send request for FCM token<br>export const RequestFCMtoken = async () =&gt; {<br>  return await getToken(messaging, {<br>    vapidKey: process.env.REACT_APP_VAPID_PUBLIC_KEY,<br>  })<br>    .then((currentToken) =&gt; {<br>      if (currentToken) {<br>        console.log(&quot;FCM:token received&quot;, { token: currentToken });<br>        return currentToken;<br>      } else {<br>        console.log(&quot;FCM:token receiving failed&quot;);<br>        return null;<br>      }<br>    })<br>    .catch((err) =&gt; {<br>      console.log(&quot;FCM:token receiving failed due to &quot;, err);<br>      return null;<br>    });<br>};<br></pre><p><em>The </em><em>getToken() method from Firebase registers the current browser instance with your Firebase Cloud Messaging (FCM) project and returns a unique FCM token to the frontend. This token identifies the device and is required to send push notifications to it</em></p><p><em>The </em><em>onMessage() method from Firebase allows you to handle incoming notifications </em><strong><em>when the app is in the foreground</em></strong><em>. Unlike background messages (which are automatically shown via the service worker), foreground notifications must be manually handled. Inside </em><em>onMessage(), we create a new browser notification using the Web Notifications API and can also define a custom </em><em>onclick behavior to handle user interactions when the notification is clicked.</em></p><blockquote><strong>where you can find these firebase configuration data</strong></blockquote><p><em>Firebase project console -&gt; project settings -&gt; general -&gt;your app</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2XeBzRdQ4x7PnKVIdG3ow.png" /></figure><blockquote><strong>Now front-end have registered FCM token but How Does the Backend Know the Device Token?</strong></blockquote><p><em>Once the frontend registers the browser instance with Firebase Cloud Messaging (FCM) using </em><em>getToken(), it receives a unique FCM token that identifies that specific device or browser. However, the backend doesn’t automatically know this token. To enable the backend to send targeted notifications, the frontend must </em><strong><em>explicitly send the FCM token to the backend</em></strong><em>, typically along with a user identifier. This is commonly done via a </em><em>/subscribe API endpoint, where the token is stored in a database associated with the user.</em></p><p><em>This mechanism allows the backend to later fetch all tokens tied to a user and send notifications to their devices as needed.</em></p><blockquote><strong>Register device with FCM and subscribe notification service with backend</strong></blockquote><p><em>Now that Firebase is set up, the next step is to integrate the logic within your application to handle user permissions and device registration.</em></p><p><em>Start by </em><strong><em>asking the user for notification permission</em></strong><em> using the browser’s Notifications API. If the user </em><strong><em>grants permission</em></strong><em>, proceed to register the device with Firebase Cloud Messaging (FCM) using the </em><em>getToken() method. This returns a unique FCM token that identifies the current browser instance.</em></p><p><em>Once the token is successfully retrieved, you should </em><strong><em>send it to your backend via a </em></strong><strong><em>/subscribe API endpoint</em></strong><em>, along with the user’s ID or other identifier. This allows the backend to store the token for future use and send notifications specifically to that user’s devices.</em></p><pre> //setup push notifications inside the app<br>const [userId,setUserId] = useState(&quot;&quot;);//keep user id<br>const listnerRef = useRef();// keeep reference to notifcation listner<br><br>  useEffect(() =&gt; {<br>    <br>    //first ask user permission for notification, if it is granted then get FCM token<br>    const getToken = async () =&gt; {<br>      if (Notification.permission !== &quot;granted&quot;) {<br>        const permission = await Notification.requestPermission();<br>        if (permission !== &quot;granted&quot;) {<br>          console.log(&quot;FCM:notification permission denied or dismissed&quot;);<br>          return;<br>        }<br>      }<br> <br>      const token = await RequestFCMtoken(); //request FCM token<br> <br>      if (token) {<br>        //subscribe for notification service with backend <br>        try {<br>         //make sure to update your endpoint url here<br>         const response = await axios.post(&#39;/api/notifications/subscribe&#39;, {<br>           userId,<br>           token,<br>          <br>      });<br>         console.log(&#39;Subscribed successfully:&#39;, response.data);<br>      } catch (error) {<br>         console.error(&#39;Subscription failed:&#39;, error);<br>      }<br>        });<br>      } else {<br>        console.log(&quot;FCM:notification subscription failed&quot;);<br>      }<br>    };<br> <br>    //if appSetting and useList updated then setup notification<br>    if (<br>      typeof Notification !== &quot;undefined&quot; &amp;&amp; //this will check does browser support notifications<br>      (Notification.permission === &quot;default&quot; || Notification.permission === &quot;granted&quot;)<br>    ) {<br>      getToken();<br> <br>      if (!listnerRef.current) {<br>        // Setup foreground notification listener<br>        listnerRef.current = onMessage(messaging, ({ data }) =&gt; {<br>          console.log(&quot;Message received in foreground:&quot;, data);<br> <br>          const link = data?.url || &quot;/&quot;;<br> <br>          const notif = new Notification(data?.title, {<br>            body: data?.body,<br>            icon: &quot;../../../public/logo192.png&quot;,<br>            image: data?.image,<br>            data: { url: link },<br>          });<br> <br>          notif.onclick = (event) =&gt; {<br>            event.preventDefault();<br>             window.open(link, &quot;_blank&quot;);<br>          };<br>        });<br>      }<br>    }<br> <br>//if component unmount remove listner,this will avoiding create multiple listners<br>    return () =&gt; {<br>      if (listnerRef.current) {<br>        // If onMessage returns an unsubscribe function, call it here<br>        listnerRef.current();<br>        listnerRef.current = null;<br>      }<br>    };<br>  }, [appSettings]);</pre><h3>3.Setup Background Notifications</h3><p><em>Background notifications can’t be handled inside the app itself when the user isn’t actively using it. That’s where </em><strong><em>service workers</em></strong><em> come in. they run in the background and take care of displaying notifications even when the app is closed or inactive.</em></p><h4>Service Workers??</h4><p><em>A </em><strong><em>service worker</em></strong><em> is a background script that works separately from your web app. It helps your app work offline and show push notifications, even when the app isn’t open. For web push, we’ll create a </em><em>firebase-messaging-sw.js file that listens for messages and displays them as notifications.</em></p><blockquote>Add <em>firebase-messaging-sw.js inside public folder</em></blockquote><pre>importScripts(&quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js&quot;);<br>importScripts(<br>  &quot;https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js&quot;<br>);<br><br>// Replace these with your own Firebase config keys...<br>const firebaseConfig = {<br>  apiKey: xxxxxxxxxxxxxxxxxxxxx,<br>  authDomain: xxxxxxxxxxxxxxxxx,<br>  projectId: xxxxxxxxxxxxxxxxxxxxx,<br>  storageBucket:xxxxxxxxxxxxxxxxxxxx,<br>  messagingSenderId: xxxxxxxxxxxxxxxxxx,<br>  appId: xxxxxxxxxxxxxx,<br>  measurementId: xxxxxxxxxxxxx,<br>};<br><br>firebase.initializeApp(firebaseConfig);<br><br>const messaging = firebase.messaging();<br><br>//handle backgound notifications manually<br>messaging.onBackgroundMessage(function (payload) {<br>  console.log(<br>    &quot;[firebase-messaging-sw.js] Received background message &quot;,<br>    payload<br>  );<br>  // Customize notification here<br>  const notificationTitle = payload.data?.title;<br>  const notificationOptions = {<br>    body: payload.data?.body,<br>    icon: &quot;/logo192.jpg&quot;,<br>    image: payload.data?.image,<br>    data: {<br>      url: payload.data?.url || &quot;/&quot;,<br>    },<br>  };<br> <br>  self.registration.showNotification(notificationTitle, notificationOptions);<br>});<br> <br>self.addEventListener(&quot;notificationclick&quot;, (event) =&gt; {<br>  event.notification.close();<br> <br>  console.log(&quot;clicked trigered..............&quot;, event);<br> <br>  // URL to open when notification clicked<br>  const urlToOpen = event.notification.data.url || &quot;/&quot;;<br> <br>  event.waitUntil(<br>    clients<br>      .matchAll({ type: &quot;window&quot;, includeUncontrolled: true })<br>      .then((clientList) =&gt; {<br>        console.log(&quot;clientList&quot;, clientList);<br>        for (const client of clientList) {<br>          if (client.url === urlToOpen &amp;&amp; &quot;focus&quot; in client) {<br>            return client.focus();<br>          }<br>        }<br>        if (clients.openWindow) {<br>          return clients.openWindow(urlToOpen);<br>        }<br>      })<br>  );<br>});</pre><p><em>In the </em><em>firebase-messaging-sw.js file, we import Firebase libraries and initialize the app using our Firebase config. This service worker listens for </em><strong><em>background messages</em></strong><em> using </em><em>onBackgroundMessage(), allowing it to display custom push notifications even when the app is closed.</em></p><p><em>We customize the notification’s title, body, icon, and image based on the message payload. We also handle </em><strong><em>notification click events</em></strong><em>, so when a user clicks the notification, it opens the relevant URL or brings the app window into focus, creating a smooth and engaging user experience</em>.</p><h3>Part 3. Setting Up Firebase with Spring Boot</h3><p><em>To send push notifications from your backend, we need to connect Spring Boot with </em><strong><em>Firebase Cloud Messaging (FCM)</em></strong><em>. This allows your backend to send messages directly to devices using their FCM tokens.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bihqNCi9z8IxqJ8Dz9mKag.png" /></figure><blockquote><strong>1. Add Firebase Admin SDK to Your Project</strong></blockquote><p><em>add the Firebase Admin dependency to your </em><em>pom.xml ( inside the dependencies tag )</em></p><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.google.firebase&lt;/groupId&gt;<br>   &lt;artifactId&gt;firebase-admin&lt;/artifactId&gt;<br>   &lt;version&gt;8.1.0&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><blockquote><strong>2. Download and Add Firebase Admin SDK Key</strong></blockquote><p><em>Firebase project -&gt; project settings -&gt; service accounts -&gt; select java -&gt; click Generate new private key( will download json file )</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELEeLgoz8X4jZwaTY4ZiZw.png" /></figure><p><em>place it in your project’s </em><em>src/main/resources folder</em>.</p><blockquote><strong>3. Initialize Firebase in Spring Boot</strong></blockquote><p><em>Now, create a config class to initialize Firebase using the downloaded JSON file</em></p><p><em>/ src / main / java / com / example / web_push_notifications / config / Firebaseonfig.java</em></p><pre>package com.example.web_push_notifications.config;<br><br>import org.springframework.context.annotation.Configuration;<br>import com.google.auth.oauth2.GoogleCredentials;<br>import com.google.firebase.FirebaseApp;<br>import com.google.firebase.FirebaseOptions;<br><br>import javax.annotation.PostConstruct;<br>import java.io.IOException;<br>import java.io.InputStream;<br><br><br>@Configuration<br>public class FirebaseConfig {<br>    @PostConstruct<br>    public void initialize() {<br>        try {<br>            InputStream serviceAccount = getClass()<br>                    .getClassLoader()<br>                     //below you have to replace service file name with your service file which is added to resource folder<br>                    .getResourceAsStream(&quot;pwa-web-push-notification-firebase-adminsdk-fbsvc-e7b74af4f6.json&quot;);<br><br>            if (serviceAccount == null) {<br>                throw new RuntimeException(&quot;Firebase service account file not found in resources&quot;);<br>            }<br><br>            FirebaseOptions options = FirebaseOptions.builder()<br>                    .setCredentials(GoogleCredentials.fromStream(serviceAccount))<br>                    .build();<br><br>            FirebaseApp.initializeApp(options);<br><br>        } catch (IOException e) {<br>            throw new RuntimeException(&quot;Failed to initialize Firebase&quot;, e);<br>        }<br>    }<br>}</pre><blockquote><strong>4. Defining the Notification Subscribe Endpoint</strong></blockquote><p><em>Once Firebase is set up, the next step is to </em><strong><em>store the user’s FCM token</em></strong><em> in your backend. Why? Because when we want to send a notification later, we need to know </em><strong><em>where to send it</em></strong><em> and that’s what the token is for.</em></p><p><em>So we’ll build an API endpoint that receives the </em><strong><em>FCM token</em></strong><em> and </em><strong><em>client ID</em></strong><em> from the frontend and saves it in the database.</em></p><p><strong><em>i) Create a Data Class to Store Subscriptions</em></strong></p><p><em>This will create a table to store each user’s </em><em>clientId and </em><em>fcmToken</em></p><pre>import lombok.Data;<br>import jakarta.persistence.*;<br><br>@Entity<br>@Data<br>public class Subscription {<br><br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int id;<br><br>    private String clientId;<br>    private String fcmToken;<br>}</pre><p><strong><em>ii) Create a DTO for the Incoming Request</em></strong></p><pre>import lombok.Data;<br><br>@Data<br>public class SubscriptionRequest {<br>    private String clientId;<br>    private String fcmToken;<br>}</pre><p><strong><em>iii) Add the Repository and Service</em></strong></p><p><em>This is a Spring Data JPA repository interface for your </em><em>Subscription entity</em></p><pre><br>@Repository<br>public interface SubscriptionRepo extends JpaRepository&lt;Subscription, int&gt; {<br>    Optional&lt;PushSubscription&gt; findByClientId(String clientId);<br>}</pre><p><em>Service to Save Token</em></p><pre>@Service<br>public class NotificationService {<br><br>    @Autowired<br>    private SubscriptionRepo repository;<br><br>    public void subscribe(SubscriptionRequest request) {<br>        Optional&lt;Subscription&gt; existing = repository.findByClientId(request.getClientId());<br><br>        Subscription subscription = existing.orElse(new PushSubscription());<br>        subscription.setClientId(request.getClientId());<br>        subscription.setFcmToken(request.getFcmToken());<br><br>        repository.save(subscription);<br>    }<br>}</pre><p><strong><em>iv) Create the Subscribe API Endpoint</em></strong></p><p><em>Now your frontend can call this </em><em>/api/notification/subscribe endpoint whenever a user allows notifications.</em></p><pre>@RestController<br>@RequestMapping(&quot;/api/notifications&quot;)<br>public class NotificationController {<br><br>    @Autowired<br>    private NotificationService notificationService;<br><br>    @PostMapping(&quot;/subscribe&quot;)<br>    public ResponseEntity&lt;String&gt; subscribe(@RequestBody SubscriptionRequest request) {<br>        notificationService.subscribe(request);<br>        return ResponseEntity.ok(&quot;Subscribed successfully.&quot;);<br>    }<br>}</pre><blockquote><strong>5. Sending a Push Notification from Backend</strong></blockquote><p><em>Once tokens are stored, you can use them to send notifications using Firebase’s SDK.<br>i) create notification message model</em></p><pre>package com.example.web_push_notifications.model;<br>import lombok.Data;<br><br>@Data<br>public class NotificationMessage {<br>    private String title;<br><br>    private String body;<br><br>    private String image;<br><br>    private String url;<br><br>}</pre><p><em>Create a Notification Sending method inside the notification service class</em></p><pre><br>@Service<br>public class NotificationService{<br><br>    public String sendNotification(String token, NotificationMessage notificationMessage){<br>        Message message = Message.builder()<br>                .setToken(token)<br>//                .setNotification(<br>//                   Notification.builder()<br>//                    .setTitle(notificationMessage.getTitle())<br>//                    .setBody(notificationMessage.getBody())<br>//                    .setImage(&quot;https://th.bing.com/th/id/OIP.YIvdAmFFnWe9RePVR02r-wHaHa?cb=iwp2&amp;rs=1&amp;pid=ImgDetMain&quot;)<br>//                    .build())<br>                .putData(&quot;title&quot;,notificationMessage.getTitle())<br>                .putData(&quot;body&quot;,notificationMessage.getBody())<br>                .putData(&quot;image&quot;,notificationMessage.getImage())<br>                .putData(&quot;url&quot;,notificationMessage.getUrl())<br>                .build();<br>        try{<br>            System.out.println(&quot;Message sending&quot;+ token +&quot; &quot;+ notificationMessage.getTitle() + notificationMessage.getBody());<br>            return FirebaseMessaging.getInstance().send(message);<br>        }catch (Exception e){<br>            System.out.println(&quot;Error: &quot;+ e);<br>            return null;<br>        }<br>    }<br>}</pre><p><em>You can later trigger this service from another controller or scheduled task, passing the token(s) from your database.</em></p><h3>!! Sending FCM Notifications: notification vs data !!</h3><p><em>When sending push notifications using Firebase Cloud Messaging (FCM), you have two main options to include the payload</em></p><h4><strong>1. Using the </strong><strong>notification Key</strong></h4><pre>{<br>  &quot;notification&quot;: {<br>    &quot;title&quot;: &quot;Hello&quot;,<br>    &quot;body&quot;: &quot;This is a background alert&quot;<br>  },<br>  &quot;token&quot;: &quot;user-device-token&quot;<br>}</pre><blockquote>This is the simplest way to send a notification.</blockquote><blockquote>The FCM SDK automatically handles this and displays the notification when the app is in the background or terminated.</blockquote><blockquote>You don’t need to write any custom logic to show it.</blockquote><blockquote><strong>Don’t manually handle notifications in the service worker if you use this method, it can cause duplicate notifications in the background.</strong></blockquote><h4>2. <strong>Using the </strong><strong>data Key</strong></h4><pre>{<br>  &quot;data&quot;: {<br>    &quot;title&quot;: &quot;Custom Notification&quot;,<br>    &quot;body&quot;: &quot;Click to navigate&quot;,<br>    &quot;url&quot;: &quot;/custom-page&quot;<br>  },<br>  &quot;token&quot;: &quot;user-device-token&quot;<br>}</pre><blockquote>With data, you gain full control over how notifications behave.</blockquote><blockquote>The <strong>message won’t be automatically displayed</strong>. You must handle it manually in your <strong>service worker</strong>, both in foreground and background.</blockquote><blockquote>Ideal if you want to</blockquote><blockquote><em>Customize how the notification looks.</em></blockquote><blockquote><em>Handle notification click behavior (e.g., navigate to a dynamic route).</em></blockquote><blockquote><em>Add custom fields (e.g., </em><em>image, </em><em>url, etc.).</em></blockquote><h3>!! Never Push Firebase Config or Service Files to Git !!</h3><p>When working with Firebase Cloud Messaging (or any Firebase service), it’s <strong>crucial</strong> to keep your configuration files and service account credentials <strong>secure</strong>.</p><ul><li>❌ <strong>Do NOT commit</strong> your firebase-adminsdk-*.json (service account key) or your Firebase config object to a public GitHub repository.</li><li>✅ Instead, use environment variables or secure secrets management tools to store and access them.</li><li>If you’re working in a team or open-source project, add these files to your .gitignore</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b40011fbb19" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>