<?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 Mohammad Sajib Miah on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Sajib Miah on Medium]]></description>
        <link>https://medium.com/@sajib.cuetcse10?source=rss-1543aac61b6a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vXyaQf_KoLcaWk55</url>
            <title>Stories by Mohammad Sajib Miah on Medium</title>
            <link>https://medium.com/@sajib.cuetcse10?source=rss-1543aac61b6a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:23:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sajib.cuetcse10/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[The Transactional Outbox Pattern: From Theory to Production-Ready Implementation]]></title>
            <link>https://medium.com/@sajib.cuetcse10/the-transactional-outbox-pattern-from-theory-to-production-ready-implementation-65d67ff1cacc?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d67ff1cacc</guid>
            <category><![CDATA[transactional-outbox]]></category>
            <category><![CDATA[acid]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 13:05:01 GMT</pubDate>
            <atom:updated>2026-09-08T13:05:01.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to guarantee that critical events survive crashes, network splits, and Kafka outages.</h3><p>A user cashed out 1,000 BDT. Our MFS core updated the wallet balance, but crashed just before publishing the CashOutCompleted event. The result? A ghost transaction—the agent missed their commission, the user never got a confirmation SMS, and the partner bank&#39;s settlement reconciliation broke overnight.</p><p>In mobile money, these failures mean angry agents, panicked users, and regulatory fines. This is the Dual-Write Problem — the primary source of data inconsistency in fintech.</p><p>Let’s dissect the solution — the Transactional Outbox Pattern — down to the network packet level, with clear diagrams for every moving part.</p><h3>Part 1: The Core Problem — The “Dual Write” Trap</h3><p>In a typical microservices payment flow, a single POST /payments request triggers two separate actions:</p><ol><li>Database Write: Update the payments table status to COMPLETED and deduct the user&#39;s balance.</li><li>Message Publish: Send a PaymentCompletedEvent to Kafka for downstream services (Ledger, Notification, Fraud).</li></ol><p>If you perform these sequentially (the infamous “dual-write”), you face a coin-flip of partial failures:</p><pre>┌─────────┐     ┌─────────────┐     ┌─────────┐     ┌─────────┐<br>│ Client  │ ──&gt; │ Application │ ──&gt; │  DB (1) │ ──&gt; │ Kafka   │<br>└─────────┘     └─────────────┘     └─────────┘     └─────────┘<br>                                      │                    ▲<br>                                      ▼                    │<br>                                   [SUCCESS]   ❌ CRASH!   │<br>                                      │                    │<br>                                      └─── (Event lost!) ──┘</pre><p>Failure Modes:</p><ul><li>Scenario A: DB commits, but the network hangs before Kafka receives the message. The payment is taken, but the customer never gets a receipt, and the ledger is never updated.</li><li>Scenario B: Kafka publishes successfully, but the DB transaction rolls back due to a constraint violation. Downstream services receive a “Payment Success” event for a transaction that does not exist in your source of truth — creating “ghost money.”</li></ul><p>You cannot solve this with a distributed transaction (like 2PC) across a database and a message broker — they don’t share a transaction context, and 2PC kills performance.</p><p>The Solution: The Transactional Outbox pattern ensures that the database write and the event generation happen inside a single local ACID transaction.</p><h3>Part 2: The Anatomy of the Pattern</h3><p>Here is the high-level architecture. Notice how the application never talks to Kafka directly during the request cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fZaoFDRq_AUtK57-x3pVA.png" /></figure><h3>Step 1: The Atomic Database Transaction</h3><p>Your application begins a database transaction. Inside this single transaction, it executes two inserts:</p><pre>BEGIN;<br>  -- 1. Core Business Logic<br>  INSERT INTO payments (id, user_id, amount, status, updated_at) <br>  VALUES (&#39;pay_123&#39;, &#39;user_456&#39;, 99.99, &#39;COMPLETED&#39;, NOW());</pre><pre>  -- 2. Outbox Record (The &quot;Buffer&quot;)<br>  INSERT INTO outbox (id, aggregate_id, event_type, payload, status, created_at) <br>  VALUES (uuid(), &#39;pay_123&#39;, &#39;PaymentCompleted&#39;, <br>          &#39;{&quot;paymentId&quot;:&quot;pay_123&quot;, &quot;amount&quot;:99.99, &quot;userId&quot;:&quot;user_456&quot;}&#39;, <br>          &#39;PENDING&#39;, NOW());<br>COMMIT;</pre><p>The Guarantee: Because this is a single ACID transaction, either both inserts succeed, or both fail. The outbox is now the source of truth for events.</p><h3>Step 2: The Asynchronous Relay</h3><p>A separate, asynchronous process continuously monitors the outbox table for records with status = &#39;PENDING&#39;. This Relay is the engine that moves messages from the database to the Broker.</p><p>Implementation Strategies:</p><ul><li>Polling: A scheduler runs every 100ms executing SELECT * FROM outbox WHERE status = &#39;PENDING&#39; ORDER BY id ASC LIMIT 100. Simple, but adds load to your primary DB.</li><li>Change Data Capture (CDC — Production Standard): Tools like Debezium read the database’s native transaction logs (WAL/Binlog). As soon as the COMMIT happens, CDC streams the insert to the Relay. This moves the read overhead off your primary database.</li></ul><h3>Part 3: The Million-Dollar Question — How does the Relay know when to DELETE?</h3><p>This was the crux of our deep-dive. The Relay doesn’t “just know.” It explicitly relies on the Producer ACK sent by the Kafka Broker over the network.</p><p>When the Relay calls producer.send(), it blocks its execution (or registers a callback) until a TCP packet containing the ACK arrives back from Kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq_C4bbmta1d1K5Rlyi5_w.png" /></figure><h3>Strategy A: Synchronous (Blocking) — Simple, but slow</h3><p>The thread stops dead and waits for the network packet.</p><pre>public void processOutbox(OutboxRecord record) {<br>    try {<br>        // .get() BLOCKS the thread until Kafka sends the ACK packet.<br>        RecordMetadata metadata = kafkaProducer.send(message).get(5, TimeUnit.SECONDS);<br>        <br>        // ---------- THIS LINE ONLY RUNS IF THE ACK PACKET ARRIVES ----------<br>        // Kafka confirmed it is on disk. We are SAFE to delete.<br>        outboxRepository.deleteById(record.getId());<br>        <br>    } catch (TimeoutException e) {<br>        // ACK never arrived. DO NOT delete the record.<br>        // The next polling cycle will retry.<br>        log.error(&quot;Keeping outbox record for retry&quot;);<br>    }<br>}</pre><h3>Strategy B: Asynchronous (Callback) — Production Standard</h3><p>The Relay sends the message and instantly moves to the <em>next</em> outbox record. This allows processing of thousands of messages per second.</p><pre>public void processOutbox(OutboxRecord record) {<br>    // .send() returns IMMEDIATELY. No blocking.<br>    kafkaProducer.send(message, new Callback() {<br>        @Override<br>        public void onCompletion(RecordMetadata metadata, Exception exception) {<br>            if (exception == null) {<br>                // ACK Packet received on a background thread.<br>                outboxRepository.deleteById(record.getId());<br>            } else {<br>                // ACK failed. Keep as PENDING for retry.<br>                log.error(&quot;Broker rejected message, keeping record&quot;);<br>            }<br>        }<br>    });<br>}</pre><h3>The Critical Edge Case: What if the DELETE fails?</h3><p>Imagine the ACK arrives, but the database is temporarily down when the Relay tries to DELETE the outbox row. Now the Broker has the message, but the DB still shows PENDING.</p><p>Solution 1: Idempotency (The Savior) — The downstream Ledger Service uses the Inbox Pattern. When it receives the duplicate message, it checks its local processed_events table, sees the ID exists, and silently drops it.</p><p>Solution 2: Soft Delete — Never delete the record. Instead: UPDATE outbox SET status = &#39;SENT&#39; WHERE id = &#39;x&#39;. The polling query ignores SENT records. The row stays for audit compliance.</p><h3>Part 4: The Consumer Side — Offsets and the Inbox Pattern</h3><p>A crucial misconception we clarified: The Upstream Relay NEVER receives the Consumer’s ACK.</p><ul><li>The Producer ACK is between the Relay and Kafka. (Message is stored).</li><li>The Consumer Offset Commit is between the Ledger Service and Kafka. (Message is processed).</li></ul><p>The Ledger Service must commit its Kafka offset only after its local database transaction succeeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wxYhIIA02zLY8smzrLs8A.png" /></figure><p>Here is the code implementation:</p><pre>@KafkaListener(topics = &quot;payment-events&quot;, groupId = &quot;ledger-group&quot;)<br>@Transactional(rollbackFor = Exception.class)<br>public void consume(ConsumerRecord record, Acknowledgment ack) {<br>    // 1. Idempotency Check (Inbox Pattern)<br>    if (inboxRepository.existsById(eventId)) {<br>        ack.acknowledge(); return; // Duplicate, skip but commit offset<br>    }<br>    // 2. Update Balance (Business Logic)<br>    ledgerService.debitUserBalance(payload);<br>    // 3. Store processed ID<br>    inboxRepository.save(new InboxRecord(eventId));<br>    // 4. DB commits here (@Transactional)<br>    // 5. ONLY NOW commit the Kafka offset.<br>    ack.acknowledge();<br>}</pre><p>Failure Scenario: If the Ledger DB is down, the @Transactional rolls back. ack.acknowledge() is never called. The consumer throws an exception. The container retries with exponential backoff. After max retries, the message goes to a Dead Letter Queue (DLQ) for manual inspection. The Relay producing <em>new</em> messages for other payments remains completely unaffected.</p><h3>Part 5: Fanning Out to Multiple Services</h3><p>How does one outbox record become three separate actions (Ledger, Notification, Audit)?</p><p>The Golden Rule: The Outbox Relay does <em>not</em> deliver to multiple services. It only delivers once to the Kafka Topic (payment-events). Kafka handles the broadcast via independent Consumer Groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFFhTyBmpn7ui0xpJ28CXw.png" /></figure><p>How Each Service Handles It Differently:</p><p>ServiceStrategyIdempotencyBehaviourLedger (Financial)Inbox table with unique constraintMandatoryCommits offset only after DB commitNotification (Email/SMS)Lightweight Redis cache (24h TTL)RecommendedIf SMS provider fails, push to DLQAudit (Fire-and-forget)No inbox neededOptionalCommits offset aggressively, writes to Elasticsearch</p><h3>Part 6: The Missing Piece — Orchestration-Based Sagas</h3><p>The Outbox pattern doesn’t just handle single events; it is the engine for Orchestration-based Sagas.</p><p>In a Saga, an Orchestrator dictates the flow: Charge Payment → Reserve Inventory → Ship Order. If Inventory fails, the Orchestrator must send a Refund Payment command (Compensation).</p><p>How they work together:<br>Both the Orchestrator and the downstream services use the Outbox. Furthermore, the Orchestrator uses the Inbox to consume replies.</p><h3>The “Pay &amp; Ship” Saga Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bc2lpFvUVZwT-c5wdhVh_w.png" /></figure><h3>Handling the Crash (The “Superpower”)</h3><p>What if the Orchestrator crashes <em>exactly</em> after updating its state to PAYMENT_CHARGED but <em>before</em> the Relay sends the RESERVE_INVENTORY_COMMAND?</p><ul><li>Without Outbox: The system is stuck in a half-finished state. You need manual intervention.</li><li>With Outbox: The RESERVE_INVENTORY_COMMAND sits safely in the database as PENDING. When Kubernetes restarts the pod, the Relay polls the DB, finds the record, and sends it. The Saga seamlessly continues exactly where it left off.</li></ul><h3>Part 7: Industry Best Practices &amp; Pitfalls</h3><p>Based on real-world implementations (including those used by major fintechs), here are the rules to live by:</p><h3>1. Optimize the Polling Index</h3><p>Polling on status = &#39;PENDING&#39; can become a bottleneck. Use a composite index:</p><pre>-- Bad: Index on created_at only (becomes inefficient as table grows)<br>CREATE INDEX idx_outbox_created ON outbox(created_at);</pre><pre>-- Good: Composite index on status and the sorting column<br>CREATE INDEX idx_outbox_status_id ON outbox(status, id);</pre><h3>2. Never Sort by created_at Alone</h3><p>Different pods have different clocks. Use a monotonic sequence ID (auto-incrementing primary key) to maintain strict event ordering.</p><h3>3. Handle “Poison Pills”</h3><p>If a specific message causes the Relay to fail (e.g., malformed JSON), it will block all subsequent messages. Implement a Dead Letter Queue — move to a separate table after 3 retries to let the pipeline continue.</p><h3>4. Use SKIP LOCKED for Multi-Instance Relays</h3><p>If you have two Relay instances to prevent downtime, use SELECT ... FOR UPDATE SKIP LOCKED so they don&#39;t steal the same records from each other:</p><p>sql</p><pre>SELECT * FROM outbox <br>WHERE status = &#39;PENDING&#39; <br>ORDER BY id ASC <br>LIMIT 100 <br>FOR UPDATE SKIP LOCKED;</pre><h3>5. Partition the Outbox Table</h3><p>For massive throughput (millions of events/day), partition the outbox table by date range. This prevents index bloat and keeps DELETE operations fast.</p><h3>6. Schema Versioning</h3><p>Include a version field in your event payload. Downstream services might update their schemas faster than upstream. Versioning ensures backward compatibility.</p><h3>7. The “Lease” or “Claim Check” Mechanism</h3><p>To prevent two Relay instances from double-pickup, use an atomic update to “claim” the record:</p><p>sql</p><pre>UPDATE outbox <br>SET status = &#39;PROCESSING&#39;, locked_by = &#39;instance-1&#39;, locked_at = NOW() <br>WHERE status = &#39;PENDING&#39; <br>ORDER BY created_at ASC <br>LIMIT 1 <br>RETURNING *;</pre><p>A watchdog job resets stale PROCESSING records back to PENDING after a timeout.</p><h3>Part 8: The Final Architecture Overview</h3><p>Here is the complete production-grade system, combining all the pieces we’ve discussed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjUO-MAlmWv9Ug89U0YEyA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d67ff1cacc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate No-Doubt Guide to HTTPS & TLS: How the Internet Keeps Your Secrets Safe]]></title>
            <link>https://medium.com/@sajib.cuetcse10/the-ultimate-no-doubt-guide-to-https-tls-how-the-internet-keeps-your-secrets-safe-96ee75f545eb?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/96ee75f545eb</guid>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 10:22:16 GMT</pubDate>
            <atom:updated>2026-08-05T10:22:16.588Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever seen a padlock icon in your browser and wondered, <em>“How does this actually work?”</em> — you are in the right place.</p><p>This guide is built from the ground up to leave zero doubt in your mind. We will cover certificates, keys, signatures, session keys, mobile apps, and even what happens if a hacker steals your certificate.</p><p>Let’s dive into the invisible bodyguard of the internet.</p><h3>1. The Cast of Characters</h3><p>Before we start, let’s meet the players in our story:</p><p>RoleName in Tech TermsSimple DescriptionYouClient (Browser or App)The one trying to access a website securely.The WebsiteServerThe computer hosting the website you want to visit.The Trusted StamperCertificate Authority (CA)A globally trusted company (like Let’s Encrypt or DigiCert) that issues ID cards to websites.The Bad GuyAttacker / HackerThe one trying to steal your password by listening in.</p><h3>2. The Core Problem</h3><p>The internet is a giant public hallway. When you send a message to a website, the hacker is standing right next to you, listening to everything you say.</p><p>The Solution: HTTPS (which uses TLS) creates a secure, encrypted tunnel through that hallway. Here is how we build it.</p><h3>3. The Handshake: A Step-by-Step Journey</h3><p>Here is the visual map of our journey. Follow the arrows!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhPfvzMnE0hzIdZ3sZkP5A.png" /></figure><p>Many people think the browser calls the CA to verify the certificate. It does not. That would be too slow. Instead, it happens 100% locally on your device in milliseconds.</p><p>Here is the exact math:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdS0WsHBW02S0p8nNQj0Zw.png" /></figure><p>The Crucial Takeaway: Your device already has the Public Keys of all major CAs built into the operating system. It uses these to decrypt the signature and verify it locally.</p><h3>5. The “Stolen Certificate” Trap (Can the Attacker fake it?)</h3><p>Question: <em>If a hacker grabs the website’s Certificate and sends it to me, can they fool me?</em></p><p>Answer: NO! And here is exactly why.</p><p>The Certificate is just a public ID card. The hacker can photocopy it a million times, but they still can’t speak to you securely. Why? Because of Proof of Possession.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GpZ-tDzN5DPsd_o6U6lMNQ.png" /></figure><p>The Golden Rule: The Private Key never, ever leaves the original server. As long as the private key is safe, a stolen certificate is useless firewood.</p><h3>6. Who Makes the Secret Session Key?</h3><p>You might be confused about <em>who</em> creates the final key. Here is the clear breakdown:</p><ol><li>Client creates the “Seed”: The browser randomly generates a huge secret number called the Pre-Master Secret.</li><li>Client sends it: The browser locks this seed with the server’s Public Key and sends it over.</li><li>Server reads it: The server unlocks it with the Private Key.</li><li>Both bake the keys: Now, both the browser AND the server take this Pre-Master Secret and put it through an identical mathematical blender.</li><li>Result: Both ends spit out the exact same Session Keys (one for sending, one for receiving).</li></ol><p><em>(Modern Note: In the newest TLS 1.3, both sides throw in their own ingredients simultaneously (Diffie-Hellman), so the secret is never fully sent over the internet — giving “Perfect Forward Secrecy”.)</em></p><h3>7. Can a Hacker Change the Data While It Travels?</h3><p>Question: <em>If the attacker can’t read my data, can they just change the numbers (e.g., change “$100” to “$0”)?</em></p><p>Answer: No. Your data has a Tamper-Proof Seal.</p><p>Every time the server sends a message (e.g., “Your balance is $100”), it doesn’t just scramble the text. It also takes the scrambled text and runs it through a machine with the Session Key to create a unique “digital fingerprint” (called a MAC) and attaches it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ACAEuuECaphdMekNlaCxQ.png" /></figure><p>The hacker can’t fix the fingerprint because they don’t have the Session Key to recalculate it.</p><h3>8. Mobile Apps vs. Web Browsers (Does it change?)</h3><p>Does this whole process change when you use a banking app instead of a browser?</p><p>No. The math (TLS) is exactly the same. Mobile apps use internal networking libraries (like OkHttp on Android) that do the exact same handshake.</p><p>However, there is ONE big difference:</p><p>FeatureBrowserMobile AppCertificate CheckThe browser shows YOU a red warning if something is wrong.The app throws a coding error. If the developer handles it poorly, the app crashes.Extra SecurityStandard checks.Apps often use Certificate Pinning (hardcoding the exact server key into the app). If the key changes, the app rejects the connection, making it nearly impossible for hackers to use fake certificates.The Danger ZoneUsers often click “Proceed” on red warnings out of habit.Lazy developers can disable the SSL check. If they do, the app is 100% insecure and will talk to any hacker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65wk6QoEFCK2iejakyKkvQ.png" /></figure><h3>9. Final Closing Thoughts (Your “No Doubt” Checklist)</h3><ul><li>HTTPS = HTTP inside a TLS security tunnel.</li><li>Certificate = A public ID card containing a padlock (Public Key) and a stamp.</li><li>Digital Signature = Made by the CA’s Private Key; verified by the CA’s Public Key already on your device.</li><li>Private Key = The actual master password. Never leaves the server. If stolen, the server is compromised.</li><li>Session Keys = Temporary keys created <em>during</em> the handshake. Used for the actual high-speed encryption of your data.</li><li>Integrity = If a hacker changes your data, the digital fingerprint breaks, and your browser kills the connection.</li><li>Apps = Use the same TLS, but rely on developers to implement it correctly (and use Pinning for extra safety).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96ee75f545eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Reactive vs Virtual Threads: The Ultimate Backend Engineering Guide (Senior-Level Deep Dive)]]></title>
            <link>https://medium.com/@sajib.cuetcse10/reactive-vs-virtual-threads-the-ultimate-backend-engineering-guide-senior-level-deep-dive-47972c46cd82?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/47972c46cd82</guid>
            <category><![CDATA[non-blocking-io]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[java-virtual-threads]]></category>
            <category><![CDATA[java-reactive-programming]]></category>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Sat, 09 May 2026 18:11:41 GMT</pubDate>
            <atom:updated>2026-05-09T18:11:41.362Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern backend systems are evolving fast. If you’re building scalable systems today, you’re almost certainly facing this question:</p><p>👉 <strong>Should I use Reactive Programming (RxJava/WebFlux) or Virtual Threads (Project Loom)?</strong></p><p>This is not just a coding choice — it’s an <strong>architectural decision</strong>.</p><p>Let’s break it down deeply.</p><h3>🔥 Core Difference (One Line That Matters)</h3><ul><li><strong>Reactive (RxJava)</strong> → Async + Non-blocking + Event-driven</li><li><strong>Virtual Thread</strong> → Write blocking code, JVM makes it scalable internally</li></ul><h3>🧠 1. Reactive Programming — What Actually Happens?</h3><p>Reactive programming is built around <strong>data streams and event propagation</strong>.</p><h3>Concept:</h3><ul><li>Data flows as a stream</li><li>You subscribe to it</li><li>Processing happens when data arrives</li></ul><pre>Observable.fromList(users)<br>    .filter(user -&gt; user.isActive())<br>    .map(user -&gt; user.getName())<br>    .subscribe(System.out::println);</pre><h3>🔑 Key Characteristics</h3><ul><li>✅ Non-blocking (thread idle থাকে না)</li><li>✅ Event-driven</li><li>✅ Backpressure support (critical for streaming)</li><li>✅ Functional composition (map, flatMap, etc.)</li></ul><h3>🧩 Problem Reactive Solves</h3><p>Reactive shines when:</p><ul><li>High concurrency (e.g., 1M+ requests)</li><li>IO-heavy systems (DB, API, Kafka)</li><li>Continuous streaming systems</li></ul><h3>😵‍💫 The Hidden Cost</h3><p>Let’s be real (senior truth):</p><ul><li>❌ Debugging is painful</li><li>❌ Stack trace becomes meaningless</li><li>❌ Callback hell 2.0</li><li>❌ Learning curve is steep</li></ul><p>👉 অনেক team production এ reactive নিয়ে ঢুকে পরে পরে regret করে</p><h3>🧵 2. Virtual Threads — The Game Changer</h3><p>With <strong>Project Loom</strong>, Java changed the game.</p><h3>Concept:</h3><p>👉 Write normal blocking code<br> 👉 JVM manages scalability internally</p><pre>Thread.startVirtualThread(() -&gt; {<br>    String data = apiCall(); // blocking<br>    System.out.println(data);<br>});</pre><h3>🔑 Key Characteristics</h3><ul><li>✅ Looks synchronous</li><li>✅ Internally async scheduling</li><li>✅ Millions of threads possible</li><li>✅ No reactive chain, no callback</li></ul><h3>🧠 What Actually Happens Internally?</h3><p>👉 When thread blocks:</p><ul><li>JVM <strong>parks the virtual thread</strong></li><li>Releases underlying OS thread</li><li>Resumes when IO completes</li></ul><p>🔥 This is called:</p><p>👉 <strong>“Cheap Blocking”</strong></p><h3>🧠 Blocking vs Non-blocking — The Foundation</h3><h3>1. “Thread block” মানে কী?</h3><p>👉 সহজ ভাষায়:</p><blockquote><strong><em>Thread block = thread বসে অপেক্ষা করছে, কিন্তু কোনো কাজ করছে না</em></strong></blockquote><h3>🔥 Example (Blocking)</h3><pre>String data = apiCall(); // takes 2 seconds<br>System.out.println(data);</pre><h3>ভিতরে কী হচ্ছে?</h3><ol><li>Thread API call দিল</li><li>Response আসতে 2 sec লাগবে</li><li>এই 2 sec → thread কিছুই করছে না ❌</li><li>শুধু বসে আছে ⏳</li></ol><p>👉 এটাকেই বলে <strong>blocking</strong></p><h3>🎯 Real Life Analogy</h3><p>👉 তুমি ব্যাংকে গেলে:</p><ul><li>টোকেন নিয়ে বসে আছো</li><li>তোমার নাম ডাকবে → তখন কাজ হবে</li></ul><p>এই waiting time = <strong>blocking</strong></p><h3>🧠 2. “Non-blocking” মানে কী?</h3><p>👉 সহজ ভাষায়:</p><blockquote><strong><em>Thread অপেক্ষা না করে অন্য কাজ করে, result এলে handle করে</em></strong></blockquote><h3>🔥 Example (Non-blocking style)</h3><pre>apiCallAsync(data -&gt; {<br>    System.out.println(data);<br>});<br>System.out.println(&quot;I am not waiting&quot;);</pre><h3>ভিতরে কী হচ্ছে?</h3><ol><li>API call দিল</li><li>Thread বলল: “আমি wait করবো না” ✅</li><li>অন্য কাজ করতে লাগলো</li><li>Response আসলে callback execute হবে</li></ol><p>👉 এটাকেই বলে <strong>non-blocking</strong></p><h3>🎯 Real Life Analogy</h3><p>👉 তুমি রেস্টুরেন্টে:</p><ul><li>অর্ডার দিলে</li><li>বসে না থেকে বন্ধুদের সাথে গল্প করছো</li><li>খাবার এলে খাচ্ছো</li></ul><p>👉 তুমি idle না → productive ✔️</p><h3>🧠 3. Technical Deep Dive</h3><h3>Blocking IO (Traditional)</h3><p>👉 Example: JDBC call</p><pre>ResultSet rs = statement.executeQuery();</pre><p>👉 What happens:</p><ul><li>OS call দেয়</li><li>DB response না আসা পর্যন্ত thread hold থাকে</li></ul><h3>Non-blocking IO</h3><p>👉 Example: NIO / Reactive</p><pre>channel.read(buffer, null, completionHandler);</pre><p>👉 What happens:</p><ul><li>OS কে বলে: “data ready হলে notify করো”</li><li>Thread free হয়ে যায়</li></ul><h3>🧵 4. Thread State View</h3><h3>Blocking:</h3><pre>Thread → RUNNING → WAITING → RUNNING</pre><h3>Non-blocking:</h3><pre>Thread → RUNNING → FREE → callback triggered later</pre><h3>🚨 Important Misconception</h3><p>👉 অনেকেই ভাবে:</p><blockquote><em>Non-blocking মানে faster</em></blockquote><p>❌ ভুল</p><p>👉 আসলে:</p><ul><li>Non-blocking = better <strong>resource utilization</strong></li><li>Speed same হতে পারে</li></ul><h3>🧠 5. Virtual Thread কোথায় আসে?</h3><p>👉 Virtual Thread blocking code লিখতে দেয়:</p><pre>Thread.startVirtualThread(() -&gt; {<br>    String data = apiCall(); // blocking<br>});</pre><p>👉 কিন্তু ভিতরে:</p><ul><li>JVM thread suspend করে</li><li>OS thread free করে দেয়</li></ul><p>👉 So:</p><p>👉 <strong>Looks blocking, behaves non-blocking internally</strong></p><p>🔥 এটাকে বলে:<br> 👉 <em>“cheap blocking”</em></p><h3>🔄 6. RxJava কোথায় আসে?</h3><p>👉 RxJava fully non-blocking:</p><pre>Mono.fromCallable(() -&gt; apiCall())</pre><p>👉 এখানে:</p><ul><li>Thread wait করে না</li><li>event loop handle করে</li></ul><h3>🧠 7. Most Important Visualization</h3><h3>Blocking world:</h3><p>👉 1000 request → 1000 thread needed 😬</p><h3>Non-blocking world:</h3><p>👉 1000 request → 10 thread enough 😎</p><h3>🎯 Final Mental Model</h3><p>👉 Blocking:</p><blockquote><em>“আমি কাজ শেষ না হওয়া পর্যন্ত বসে থাকবো”</em></blockquote><p>👉 Non-blocking:</p><blockquote><em>“আমি কাজ দিয়ে দিলাম, result এলে আমাকে জানিও”</em></blockquote><h3>🔥 Event Loop vs Thread-per-Request vs Virtual Thread</h3><p>এখানে আমরা compare করবো:</p><ul><li>Reactive server (Netty style)</li><li>Traditional server (Tomcat)</li><li>Virtual Thread (Loom)</li></ul><h3>🧠 1. Thread-per-Request Model (Traditional — Tomcat)</h3><p>👉 Used in: <strong>Apache Tomcat</strong></p><h3>🔥 Flow:</h3><pre>Request → Thread assigned → Process → Response → Thread free</pre><h3>Example:</h3><pre>@GetMapping(&quot;/data&quot;)<br>public String getData() {<br>    String data = apiCall(); // blocking<br>    return data;<br>}</pre><h3>😵 Problem:</h3><p>👉 Suppose:</p><ul><li>1000 request</li><li>1000 thread needed</li></ul><p>👉 Issues:</p><ul><li>Memory heavy</li><li>Context switching high</li><li>Thread exhaustion 😬</li></ul><h3>🧠 2. Event Loop Model (Reactive — Netty)</h3><p>👉 Used in: <strong>Netty</strong></p><h3>🔥 Flow:</h3><pre>Request → Event Loop → Register callback → Thread free<br>         → Response ready → Callback executed</pre><h3>Example (Reactive):</h3><pre>Mono&lt;String&gt; getData() {<br>    return webClient.get()<br>        .retrieve()<br>        .bodyToMono(String.class);<br>}</pre><h3>🚀 Key Idea:</h3><p>👉 Few threads (like 4–8) handle thousands of requests</p><h3>😵‍💫 Problem:</h3><ul><li>Callback chain 😵</li><li>Debugging tough</li><li>Hard mental model</li></ul><h3>🧵 3. Virtual Thread Model (Project Loom)</h3><p>👉 Java introduces:</p><p><strong>Project Loom</strong></p><h3>🔥 Flow:</h3><pre>Request → Virtual Thread → Blocking code → Suspend → Resume → Response</pre><h3>Example:</h3><pre>@GetMapping(&quot;/data&quot;)<br>public String getData() {<br>    return apiCall(); // blocking but efficient<br>}</pre><p>👉 BUT internally:</p><ul><li>Virtual thread suspend হয়</li><li>OS thread free হয়</li></ul><h3>🧠 5. Visualization (Most Important)</h3><h3>🔴 Tomcat</h3><pre>[Req1] → Thread1 (blocked)<br>[Req2] → Thread2 (blocked)<br>[Req3] → Thread3 (blocked)</pre><p>👉 Thread waste 😬</p><h3>🟡 Netty (Event Loop)</h3><pre>Thread1:<br>  Req1 → register → free<br>  Req2 → register → free<br>  Req3 → register → free</pre><p>👉 Super efficient 😎</p><h3>🟢 Virtual Thread</h3><pre>VT1 → Req1 (paused)<br>VT2 → Req2 (paused)<br>VT3 → Req3 (paused)</pre><p>👉 Looks like blocking<br> 👉 Actually efficient 😎</p><h3>🔥 6. Critical Insight (Architect Level)</h3><p>👉 Netty vs Virtual Thread difference:</p><h3>Netty:</h3><ul><li>Control flow = framework</li><li>তুমি async লিখতে বাধ্য</li></ul><h3>Virtual Thread:</h3><ul><li>Control flow = your code</li><li>তুমি normal blocking লিখতে পারো</li></ul><h3>🚨 7. When to use what?</h3><h3>✅ Use Netty / Reactive when:</h3><ul><li>Streaming (Kafka, WebSocket)</li><li>Backpressure critical</li><li>Ultra high throughput</li></ul><h3>✅ Use Virtual Thread when:</h3><ul><li>REST API backend</li><li>DB heavy system</li><li>Microservices</li></ul><h3>❌ Avoid:</h3><p>👉 Overengineering with reactive when not needed</p><h3>🚀 Virtual Thread enable in Spring Boot 3</h3><p>Spring Boot 3.2+ থেকে এটা almost plug-and-play 😎</p><h3>✅ Option 1: application.properties (সবচেয়ে সহজ)</h3><pre>spring.threads.virtual.enabled=true</pre><p>👉 এটুকু দিলেই:</p><ul><li>প্রতিটা request → virtual thread এ চলবে</li><li>Tomcat internally virtual thread use করবে</li></ul><h3>✅ Option 2: Custom Executor (more control)</h3><pre>@Bean<br>public Executor taskExecutor() {<br>    return Executors.newVirtualThreadPerTaskExecutor();<br>}</pre><h3>🧠 2. Real Controller Example</h3><h3>🔴 Traditional (blocking + platform thread)</h3><pre>@GetMapping(&quot;/user&quot;)<br>public String getUser() {<br>    return userService.getUser(); // DB/API call<br>}</pre><p>👉 Problem:</p><ul><li>Thread block হয়</li><li>High load এ thread শেষ হয়ে যায়</li></ul><h3>🟢 Virtual Thread enabled</h3><p>👉 Same code 😎</p><pre>@GetMapping(&quot;/user&quot;)<br>public String getUser() {<br>    return userService.getUser(); // same blocking call<br>}</pre><p>👉 BUT:</p><ul><li>Virtual thread pause হবে</li><li>OS thread free হয়ে যাবে</li></ul><h3>🔥 3. Proof: Thread Check</h3><pre>@GetMapping(&quot;/thread&quot;)<br>public String checkThread() {<br>    return Thread.currentThread().toString();<br>}</pre><p>👉 Output:</p><pre>VirtualThread[#45]/runnable@ForkJoinPool-1-worker-1</pre><p>👉 বুঝবে virtual thread চলছে ✔️</p><h3>⚔️ 4. Performance Scenario (Realistic)</h3><p>ধরো:</p><ul><li>1000 concurrent request</li><li>প্রতিটা request → 200ms DB/API wait</li></ul><h3>🔴 Traditional Tomcat</h3><ul><li>Need ~1000 threads 😬</li><li>Memory high</li><li>Context switch heavy</li></ul><h3>🟡 Reactive (Netty)</h3><ul><li>~10 thread enough 😎</li><li>BUT complex code</li></ul><h3>🟢 Virtual Thread</h3><ul><li>1000 virtual thread 😎</li><li>BUT lightweight</li><li>OS thread ~10–20 only</li></ul><p>👉 Best balance 🔥</p><h3>🧠 5. Important Configuration (Production)</h3><h3>✅ Increase connection pool (very important)</h3><p>👉 Virtual thread fast → DB bottleneck হয়ে যাবে</p><pre>spring.datasource.hikari.maximum-pool-size=50</pre><h3>❌ Mistake 1: CPU-heavy task</h3><pre>while(true) {<br>    // heavy computation<br>}</pre><p>👉 Virtual thread helpful না ❌<br> 👉 CPU-bound = still limited</p><h3>❌ Mistake 2: DB pool ছোট রাখা</h3><p>👉 Result:</p><ul><li>Thread fast</li><li>DB slow → bottleneck</li></ul><h3>❌ Mistake 3: Reactive + Virtual mix (wrongly)</h3><p>👉 unnecessary complexity</p><h3>🔥 6. Advanced Insight</h3><p>👉 Virtual Thread works best when:</p><ul><li>IO-heavy (DB, API, file)</li><li>Latency-bound system</li></ul><p>👉 Because:</p><blockquote><em>waiting time → virtual thread suspend → resource save</em></blockquote><h3>🎯 7. Real Production Architecture (Modern Trend)</h3><p>👉 Most companies now:</p><ul><li>REST APIs → Virtual Thread</li><li>Streaming → Reactive (WebFlux / Kafka)</li></ul><p>👉 Hybrid architecture 🔥</p><h3>Reactive vs Virtual Thread in Gateway &amp; Microservices — Decision Guide</h3><p>Modern distributed systems-এ একটা খুব common কিন্তু critical architectural প্রশ্ন:</p><blockquote><strong><em>“API Gateway reactive রাখবো, কিন্তু সব microservice-ও কি reactive হওয়া উচিত?”</em></strong></blockquote><p>এই প্রশ্নের ভুল উত্তর দিলে system over-engineered হয়ে যায়, team productivity কমে যায়, আর production issue handle করা কঠিন হয়ে যায়।</p><p>এই পোস্টে আমরা deep dive করবো — real-world architecture, trade-offs, এবং senior-level decision framework সহ।</p><h3>🧠 1. API Gateway আসলে কী করে?</h3><p>প্রথমে বুঝতে হবে gateway layer-এর nature।</p><h3>Gateway responsibilities:</h3><ul><li>Request receive করা</li><li>Routing (Service A, B, C)</li><li>Authentication / JWT validation</li><li>Rate limiting</li><li>Logging / tracing</li><li>মাঝে মাঝে aggregation</li></ul><p>👉 <strong>Key insight:</strong></p><blockquote><em>Gateway = </em><strong><em>IO-bound + high concurrency + low business logic</em></strong></blockquote><p>এটা কোনো heavy business logic layer না — বরং ultra-efficient traffic handler।</p><h3>⚔️ 2. Gateway-এ Reactive vs Virtual Thread</h3><h3>🟡 Option 1: Reactive Gateway (e.g. Spring Cloud Gateway)</h3><h3>✅ Pros:</h3><ul><li>Very low thread usage (event loop)</li><li>Handles <strong>10k–100k concurrent requests</strong></li><li>Built-in <strong>backpressure</strong></li><li>Streaming (SSE/WebSocket) friendly</li></ul><h3>❌ Cons:</h3><ul><li>Debugging complex</li><li>Context propagation tricky</li><li>Custom logic লেখা কঠিন</li></ul><h3>🟢 Option 2: Virtual Thread Gateway (Java Loom)</h3><h3>✅ Pros:</h3><ul><li>Simple blocking code</li><li>Easy debugging</li><li>No reactive learning curve</li><li>Good enough performance (most cases)</li></ul><h3>❌ Cons:</h3><ul><li>Logical thread-per-request model</li><li>No built-in backpressure ❌</li><li>Extreme load-এ limitation</li></ul><h3>🔥 3. Gateway Context-এ সবচেয়ে গুরুত্বপূর্ণ পার্থক্য</h3><p>👉 Gateway = <strong>High fan-in system</strong></p><h3>Example:</h3><ul><li>1 Gateway</li><li>50 Microservices</li><li>50K concurrent users</li></ul><h3>Reactive behavior:</h3><ul><li>Few threads → handle all requests efficiently</li><li>No thread explosion</li></ul><h3>Virtual Thread behavior:</h3><ul><li>50K request → 50K virtual threads</li></ul><p>👉 যদিও lightweight, তবুও:</p><ul><li>Memory overhead</li><li>Scheduling overhead</li></ul><h3>🧠 4. Backpressure — Game Changer 🚨</h3><p>Gateway layer-এ এটা সবচেয়ে underestimated concept।</p><h3>Reactive:</h3><p>✔ Built-in backpressure<br> ✔ Slow downstream → intake automatically slow</p><h3>Virtual Thread:</h3><p>❌ No automatic backpressure</p><p>👉 Result:</p><ul><li>Traffic spike হলে overload risk</li><li>Downstream slow হলে cascading failure</li></ul><h3>🏭 5. Real Industry Practice</h3><p>Most production-grade systems use:</p><ul><li>Reactive Gateways (e.g. Spring Cloud Gateway)</li><li>অথবা event-driven proxies like NGINX / Kong</li></ul><p>👉 কারণ:</p><blockquote><em>Edge layer must be </em><strong><em>non-blocking এবং resilient</em></strong></blockquote><h3>🧠 6. তাহলে Microservices-এ কী করবো?</h3><p>এখানেই বেশিরভাগ engineer ভুল করে।</p><h3>🎯 Key Answer:</h3><blockquote><em>❌ সব microservice reactive হওয়া দরকার নেই</em></blockquote><h3>⚔️ 7. Reactive vs Virtual Thread @ Microservices</h3><h3>🟡 Reactive Microservice</h3><h3>✅ Pros:</h3><ul><li>High throughput</li><li>Non-blocking</li><li>Streaming friendly</li></ul><h3>❌ Cons:</h3><ul><li>Complex code 😵</li><li>Debugging nightmare</li><li>Learning curve high</li></ul><h3>🟢 Virtual Thread Microservice</h3><h3>✅ Pros:</h3><ul><li>Simple blocking code</li><li>Easy debugging</li><li>Maintainable</li><li>Near reactive-level performance</li></ul><h3>❌ Cons:</h3><ul><li>Extreme scale-এ reactive slightly better</li></ul><h3>🔥 8. Most Important Insight</h3><p>LayerPriorityGatewayEfficiency &amp; concurrencyMicroserviceMaintainability &amp; clarity</p><p>👉 তাই:</p><blockquote><em>Gateway → performance critical<br> Microservice → developer productivity critical</em></blockquote><h3>🚨 9. যদি সব Reactive করে ফেলো?</h3><p>👉 Real-world problems:</p><ul><li>Overengineering 😬</li><li>Debugging hell</li><li>Developer onboarding slow</li><li>বেশি bug surface</li></ul><p>👉 Honest truth:</p><blockquote><strong><em>“Reactive everywhere” is usually a bad decision</em></strong></blockquote><h3>🧠 10. Hybrid Architecture (Industry Standard)</h3><h3>✅ Best Practice:</h3><pre>Client<br>   ↓<br>Reactive Gateway<br>   ↓<br>Virtual Thread Microservices</pre><p>👉 এটা এখন modern architecture trend 🔥</p><h3>🧠 11. Mixed Mode কি safe?</h3><blockquote><strong><em>Reactive Gateway + Blocking Service — perfectly fine ✔️</em></strong></blockquote><h3>Flow:</h3><ul><li>Gateway → non-blocking</li><li>Service → blocking (virtual thread)</li></ul><p>👉 কোনো সমস্যা নেই, কারণ:</p><ul><li>Gateway efficiently load handle করে</li><li>Service clean code maintain করে</li></ul><h3>🧠 12. কখন Microservice Reactive হওয়া উচিত?</h3><p>Only use reactive when:</p><ul><li>Kafka stream processing</li><li>Real-time system</li><li>WebSocket / SSE</li><li>Continuous data stream</li><li>Backpressure critical</li></ul><p>👉 তখন reactive justified ✔️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47972c46cd82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Spring AOP (Aspect-Oriented Programming)]]></title>
            <link>https://medium.com/@sajib.cuetcse10/deep-dive-into-spring-aop-aspect-oriented-programming-bac11f57465f?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bac11f57465f</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aop]]></category>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 19:47:28 GMT</pubDate>
            <atom:updated>2025-07-22T19:47:28.943Z</atom:updated>
            <content:encoded><![CDATA[<p>Aspect-Oriented Programming (AOP) is a powerful programming paradigm in Spring Framework that enables the separation of cross-cutting concerns (such as logging, security, transaction management, etc.) from the business logic.</p><h3>🔍 What is AOP?</h3><p><strong>Aspect-Oriented Programming (AOP)</strong> allows developers to modularize concerns that cut across multiple classes or methods, such as logging, exception handling, transaction management, etc.</p><p>For example, if you want to log the execution time of every method in your application, you can do that using AOP without writing logging code inside each method.</p><p>Example use cases:</p><ul><li>Logging</li><li>Security</li><li>Caching</li><li>Transactions</li><li>Exception handling</li></ul><h3>⚙️ Core AOP Concepts with Examples</h3><h3>1. Aspect</h3><p>An aspect is a module that encapsulates pointcuts and advices (i.e., it defines both where and what to do).</p><p><strong>Example:</strong></p><pre>@Aspect<br>@Component<br>public class LoggingAspect {<br>    @Before(&quot;execution(* com.example.service.*.*(..))&quot;)<br>    public void logBeforeMethod(JoinPoint joinPoint) {<br>        System.out.println(&quot;Method called: &quot; + joinPoint.getSignature().getName());<br>    }<br>}</pre><h3>2. Join Point</h3><p>A point during the execution of a program, such as a method call or exception thrown.</p><p><strong>Example:</strong></p><pre>@Before(&quot;execution(* com.example.service.UserService.*(..))&quot;)<br>public void beforeAdvice(JoinPoint joinPoint) {<br>    System.out.println(&quot;JoinPoint: &quot; + joinPoint.getSignature());<br>}</pre><h3>3. Advice</h3><p>Action taken at a join point. Types:</p><pre>@Before  // Run before method execution<br>@After   // Run after method (success or failure)<br>@AfterReturning // Run only if method succeeds<br>@AfterThrowing  // Run if method throws exception<br>@Around  // Wraps the method (can control execution)</pre><p><strong>Example of @Around Advice:</strong></p><pre>@Around(&quot;execution(* com.example.service.*.*(..))&quot;)<br>public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {<br>    long start = System.currentTimeMillis();<br>    Object result = joinPoint.proceed();<br>    long end = System.currentTimeMillis();<br>    System.out.println(&quot;Execution time: &quot; + (end - start) + &quot;ms&quot;);<br>    return result;<br>}</pre><h3>4. Pointcut</h3><p>Defines at which join points an advice should be executed.</p><p><strong>Example:</strong></p><pre>@Pointcut(&quot;execution(* com.example.service.UserService.*(..))&quot;)<br>public void userServiceMethods() {}</pre><pre>@Before(&quot;userServiceMethods()&quot;)<br>public void logBefore(JoinPoint joinPoint) {<br>    // This method will be called before every method in UserService<br>}</pre><h3>5. Weaving</h3><p>The process of linking aspects with other application types to create an advised object. Can be done at:</p><ul><li>Compile time</li><li>Load time</li><li>Runtime (Spring AOP uses runtime weaving with proxies)</li></ul><h3>🧬 Diagram: AOP Flow in Spring</h3><pre>+------------------+<br>| Target Object    |<br>+------------------+<br>        |<br>        v<br>+------------------+        +----------------+<br>| Proxy (JDK/CGLIB)| -----&gt; | Advice (Aspect)|<br>+------------------+        +----------------+<br>        |<br>        v<br>+------------------+<br>| Actual Method    |<br>+------------------+</pre><h3>🧩 Proxy in Spring AOP</h3><p>Spring AOP uses proxies to implement aspects:</p><ul><li><strong>JDK Dynamic Proxy</strong>: Used when the target implements at least one interface.</li><li><strong>CGLIB Proxy</strong>: Used when the target does not implement any interface. Creates a subclass at runtime.</li></ul><h3>🔍 JDK Dynamic Proxy Example:</h3><pre>public interface UserService {<br>    void serve();<br>}</pre><pre>@Service<br>public class UserServiceImpl implements UserService {<br>    public void serve() {<br>        System.out.println(&quot;Serving user...&quot;);<br>    }<br>}</pre><p>Spring will generate a proxy implementing the interface.</p><h3>🔍 CGLIB Proxy Example:</h3><pre>@Service<br>public class NotificationService {<br>    public void notifyUser() {<br>        System.out.println(&quot;Notifying user...&quot;);<br>    }<br>}</pre><p>If NotificationService has no interface, Spring uses CGLIB to subclass it.</p><h3>⚠️ Why Proxies are Necessary?</h3><p>Proxies are wrappers around the target object. They intercept method calls and execute additional logic (advices) before/after invoking the actual method.</p><h3>✅ Problems Proxies Solve:</h3><ul><li>Avoid code duplication for cross-cutting concerns.</li><li>Encapsulate reusable behaviors (e.g., logging, security, transactions).</li><li>Maintain clean business logic in services.</li></ul><h3>⚠️ Why Proxy Can Be Bypassed?</h3><p>If a method in the same class calls another method annotated with AOP advice, the proxy is bypassed because the call doesn’t go through the proxy — it’s a direct this call.</p><h3>❗ Example:</h3><pre>@Component<br>public class MyService {</pre><pre>    @LogExecutionTime<br>    public void methodA() {<br>        methodB(); // this call bypasses the proxy<br>    }</pre><pre>    @LogExecutionTime<br>    public void methodB() {<br>        System.out.println(&quot;Executing methodB&quot;);<br>    }<br>}</pre><p>Only external calls (from other beans) go through the proxy. This is a common caveat in Spring AOP.</p><h3>🏷️ Creating Custom Annotation for AOP</h3><h3>Step 1: Define annotation</h3><pre>@Target(ElementType.METHOD)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface LogExecutionTime {}</pre><h3>Step 2: Create aspect using this annotation</h3><pre>@Aspect<br>@Component<br>public class ExecutionTimeAspect {<br>    @Around(&quot;@annotation(com.example.LogExecutionTime)&quot;)<br>    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {<br>        long start = System.currentTimeMillis();<br>        Object result = joinPoint.proceed();<br>        long end = System.currentTimeMillis();<br>        System.out.println(&quot;Execution Time: &quot; + (end - start) + &quot; ms&quot;);<br>        return result;<br>    }<br>}</pre><h3>Why Use Custom Annotation?</h3><ul><li>Improves readability and reusability</li><li>Decouples the aspect from specific method signatures</li></ul><h3>🔄 How Proxy Wraps the Class Internally</h3><p>When Spring context loads the bean, it creates a proxy object that:</p><ol><li>Implements the same interface or extends the original class.</li><li>Delegates calls to the original bean.</li><li>Injects logic before/after method invocation using advice.</li></ol><h3>Simplified Flow:</h3><pre>UserService proxy = (UserService) Proxy.newProxyInstance(<br>    UserService.class.getClassLoader(),<br>    new Class[]{UserService.class},<br>    new InvocationHandler() {<br>        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<br>            System.out.println(&quot;Before method: &quot; + method.getName());<br>            Object result = method.invoke(actualUserService, args);<br>            System.out.println(&quot;After method: &quot; + method.getName());<br>            return result;<br>        }<br>    }<br>);</pre><h3>📌 When Pointcut is Not Used</h3><p>If a pointcut is not used, the aspect will not know where to apply advice.</p><h3>Example:</h3><pre>@Aspect<br>public class MyAspect {<br>    @Before(&quot;execution(* *(..))&quot;) // Without proper pointcut<br>    public void beforeAnyMethod() {<br>        // Could unintentionally apply to all methods in the app<br>    }<br>}</pre><p>Pointcuts help narrow down where exactly to apply your logic.</p><h3>⚠️ Limitations of Proxy-Based AOP</h3><ul><li><strong>Only public methods are proxied</strong></li><li><strong>Self-invocation</strong> bypasses proxy (this.method())</li><li><strong>Final methods/classes can’t be proxied via CGLIB</strong></li><li><strong>Proxies apply only where Spring manages the bean</strong></li></ul><h3>🧠 Conclusion</h3><p>Spring AOP provides a powerful way to modularize cross-cutting concerns cleanly and declaratively. Understanding proxies, join points, and custom annotations helps build maintainable, DRY, and testable Spring applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bac11f57465f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From JDBC to Hibernate to JPA: A Complete Evolution Guide with Deep Dive]]></title>
            <link>https://medium.com/@sajib.cuetcse10/from-jdbc-to-hibernate-to-jpa-a-complete-evolution-guide-with-deep-dive-77176a925c0c?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77176a925c0c</guid>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Sat, 24 May 2025 19:43:34 GMT</pubDate>
            <atom:updated>2025-05-24T19:43:34.618Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of Java-based backend development, the evolution from JDBC to Hibernate to JPA represents a journey toward <strong>simplicity, maintainability, and abstraction</strong>. This article will walk you through that evolution — complete with in-depth explanations, real code, and best practices.</p><h3>🏡 1. The Beginning — JDBC (Java Database Connectivity)</h3><p><strong>JDBC</strong> is the core API that allows Java applications to communicate directly with relational databases using SQL.</p><h3>🔧 Core Concepts:</h3><ul><li><strong>DriverManager</strong>: Loads and manages database drivers</li><li><strong>Connection</strong>: Interface for connecting to the DB</li><li><strong>PreparedStatement</strong>: Precompiled SQL queries</li><li><strong>ResultSet</strong>: Represents returned result set</li><li><strong>Transaction control</strong>: commit(), rollback()</li></ul><h3>Code Example: Insert and Fetch</h3><pre>Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);<br>conn.setAutoCommit(false);<br><br>PreparedStatement stmt = conn.prepareStatement(&quot;INSERT INTO users (name, email) VALUES (?, ?)&quot;);<br>stmt.setString(1, &quot;Alice&quot;);<br>stmt.setString(2, &quot;alice@example.com&quot;);<br>int rows = stmt.executeUpdate();<br>conn.commit();<br><br><br>PreparedStatement stmt = conn.prepareStatement(&quot;SELECT * FROM users&quot;);<br>ResultSet rs = stmt.executeQuery();<br>while (rs.next()) {<br>    System.out.println(rs.getString(&quot;name&quot;));<br>}</pre><h3>❓ JDBC Deep Dive:</h3><ul><li><strong>PreparedStatement</strong>: Prevents SQL injection, allows parameter binding</li><li><strong>executeUpdate()</strong>: Used for INSERT, UPDATE, DELETE (returns number of affected rows)</li><li><strong>executeQuery()</strong>: Used for SELECT (returns ResultSet)</li><li><strong>commit()</strong>: Finalizes changes. Without it (and with autoCommit set to false), changes remain in a pending state inside the <strong>DB session</strong>, not committed to the database file.</li></ul><h3>❌ What happens if you don’t call commit()?</h3><p>If you don’t call commit() in manual transaction mode (i.e., conn.setAutoCommit(false)), then:</p><ul><li>Changes are not permanently saved to the database.</li><li>They remain in the <strong>transaction buffer</strong> (internal memory of the DB engine) until committed.</li><li>If the application crashes or the connection is closed before committing, all changes are <strong>rolled back</strong>.</li></ul><h3>🧠 Where does this uncommitted data reside?</h3><p>Uncommitted changes are not persisted to disk or visible to other sessions. They reside in the <strong>database engine’s memory</strong>, inside the transaction logs or buffers.</p><h3>⚡ Problems with JDBC:</h3><ul><li>Verbose boilerplate code</li><li>Manual object-relational mapping</li><li>Manual transaction management</li><li>Tight coupling with SQL and DB logic</li></ul><h3>🔄 2. Enter Hibernate — Object-Relational Mapping (ORM)</h3><p><strong>Hibernate</strong> abstracts JDBC and automates object-to-table mapping. You work with <strong>Java objects</strong>, and Hibernate handles the SQL under the hood.</p><h3>✅ Key Benefits:</h3><ul><li>Maps Java classes to DB tables</li><li>Supports lazy loading, caching, cascading</li><li>Automates transactions and SQL generation</li><li>Offers HQL (Hibernate Query Language)</li></ul><h3>🧑‍🔬 Hibernate Entity Example</h3><pre>@Entity<br>public class User {<br>    @Id @GeneratedValue<br>    private Long id;<br><br>    private String name;<br>    private String email;<br>}</pre><h3>🚀 Hibernate Insert Example</h3><pre>Session session = sessionFactory.openSession();<br>Transaction tx = session.beginTransaction();<br><br>User user = new User();<br>user.setName(&quot;Bob&quot;);<br>user.setEmail(&quot;bob@example.com&quot;);<br><br>session.save(user);<br>tx.commit();<br>session.close();</pre><h3>🔍 Hibernate Internals:</h3><ul><li>Session ≈ JDBC&#39;s Connection</li><li>save() ≈ INSERT</li><li>get() / load() for fetching</li><li>HQL for querying: from User where name = :name</li></ul><h3>📚 Advanced Hibernate Example</h3><pre>@Entity<br>public class Author {<br>  @Id @GeneratedValue<br>  private Long id;<br>  private String name;<br><br>  @OneToMany(mappedBy = &quot;author&quot;, cascade = CascadeType.ALL, fetch = FetchType.LAZY)<br>  private List&lt;Book&gt; books;<br>}<br><br>@Entity<br>public class Book {<br>  @Id @GeneratedValue<br>  private Long id;<br>  private String title;<br><br>  @ManyToOne<br>  @JoinColumn(name = &quot;author_id&quot;)<br>  private Author author;<br>}</pre><p>Hibernate manages cascading and lazy loading relationships automatically.</p><h3>🔁 3. JPA — The Standard API</h3><blockquote><strong><em>JPA (Java Persistence API)</em></strong><em> is a specification, not an implementation.</em></blockquote><h3>⚙ What is JPA?</h3><ul><li>Defines a standard set of ORM annotations</li><li>Offers interfaces like EntityManager, persist(), merge()</li><li>Introduces JPQL (Java Persistence Query Language)</li></ul><h3>🚫 Why Hibernate Alone Isn’t Enough:</h3><ul><li>Tied to Hibernate-specific classes (e.g. Session)</li><li>Not portable to other vendors like EclipseLink</li><li>Not future-proof for evolving frameworks</li></ul><h3>👌 Why JPA Over Hibernate:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*HloWXhVQ5d7lSi2KxwNpjA.png" /></figure><h3>☕ Code Comparison</h3><pre>Session session = sessionFactory.openSession();<br>session.save(entity);</pre><p>▶️ <strong>JPA:</strong></p><pre>EntityManager em = emf.createEntityManager();<br>em.getTransaction().begin();<br>em.persist(entity);<br>em.getTransaction().commit();</pre><p>With JPA, you’re not tied to Hibernate — you can swap in <strong>EclipseLink</strong>, <strong>OpenJPA</strong>, etc.</p><h3>🌱 4. Modern Development — Spring Boot + JPA + Hibernate</h3><p>Spring Boot uses JPA annotations but delegates the actual implementation to Hibernate (by default).</p><h3>🚄 Spring Data JPA Repository Example</h3><pre>public interface BookRepository extends JpaRepository&lt;Book, Long&gt; {<br>    List&lt;Book&gt; findByTitleContaining(String keyword);<br>}</pre><p>Benefits:</p><ul><li>Zero boilerplate</li><li>Auto CRUD methods</li><li>JPQL/SQL queries</li><li>Seamless pagination, sorting, filtering</li></ul><h3>📌 Summary: When to Use What?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*8xp1WATqT4GrsUqESqB5fQ.png" /></figure><p>✅ <strong>Best Practice:</strong> Use JPA annotations and interfaces, and configure Hibernate as the provider.</p><h3>🧠 Final Thoughts</h3><p>The journey from JDBC to Hibernate to JPA shows the Java ecosystem’s commitment to <strong>cleaner, more maintainable, and scalable architecture</strong>.</p><ul><li>JDBC: Full control but verbose</li><li>Hibernate: Powerful abstraction with some vendor lock-in</li><li>JPA: The best of both worlds — standardized, portable, and integrated</li></ul><p>Modern enterprise apps thrive on the flexibility JPA provides with the power of Hibernate under the hood.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77176a925c0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency vs Parallelism in Java Spring Boot: A Deep Dive with Virtual Threads]]></title>
            <link>https://medium.com/@sajib.cuetcse10/concurrency-vs-parallelism-in-java-spring-boot-a-deep-dive-with-virtual-threads-2abe6ae30243?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2abe6ae30243</guid>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Fri, 09 May 2025 12:48:13 GMT</pubDate>
            <atom:updated>2025-05-09T13:46:49.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In modern software development, efficiently handling multiple tasks is crucial for performance and scalability. Two fundamental concepts — <strong>Concurrency</strong> and <strong>Parallelism</strong> — are often misunderstood but play distinct roles in optimizing applications.</p><p>This blog post explores:<br>✔ <strong>What Concurrency and Parallelism mean</strong> (with real-world examples)<br>✔ <strong>How they work in Java &amp; Spring Boot</strong> (with code examples)<br>✔ <strong>Scaling to 20,000 tasks on a 16-core system</strong> (with detailed comparisons)<br>✔ <strong>How Virtual Threads (Project Loom) revolutionize concurrency</strong></p><h3>1. Concurrency vs Parallelism — The Core Difference</h3><h3>Concurrency (Task Switching)</h3><ul><li><strong>Definition</strong>: Managing multiple tasks at once, but not necessarily executing them simultaneously.</li><li><strong>How it works</strong>: The CPU switches between tasks rapidly, giving the illusion of simultaneous execution.</li><li><strong>Best for</strong>: I/O-bound tasks (e.g., API calls, database queries, file operations).</li></ul><h3>Parallelism (True Simultaneous Execution)</h3><ul><li><strong>Definition</strong>: Executing multiple tasks at the same time using multiple CPU cores.</li><li><strong>How it works</strong>: Tasks run in parallel on separate cores.</li><li><strong>Best for</strong>: CPU-bound tasks (e.g., complex calculations, image processing).</li></ul><h3>Real-World Analogy</h3><p><strong>Scenario</strong>: An iOS developer (Asif) needs to:</p><ol><li>Upload an app to the App Store (30 mins).</li><li>Boil water for tea (20 mins).</li><li>Play foosball (20 mins).</li></ol><h4>Concurrency Approach</h4><ul><li>Asif starts the app upload (background task).</li><li>While waiting, he asks the tea boy (Rahat) to boil water.</li><li>While the water boils, he plays foosball.</li><li>After 20 mins, the tea is ready, and after 30 mins, the upload finishes.</li></ul><p>✅ <strong>Result</strong>: All tasks completed in <strong>30 mins</strong> (not 70 mins) due to smart task switching.</p><h4>Parallelism Approach</h4><ul><li>Asif uploads the app (on his laptop).</li><li>Rahat boils water (on a separate stove).</li><li>Tareque plays foosball (another person).</li></ul><p>✅ <strong>Result</strong>: All tasks finish at their own pace, truly running <strong>simultaneously</strong>.</p><h3>2. Concurrency in Java Spring Boot</h3><p>Concurrency is implemented in Spring Boot using:</p><ul><li>@Async (for background tasks)</li><li>CompletableFuture (for non-blocking operations)</li><li><strong>Thread pools (</strong>ThreadPoolTaskExecutor<strong>)</strong></li><li><strong>Reactive Programming (WebFlux)</strong></li></ul><h3>Example: @Async for Background Tasks</h3><pre>@Service  <br>public class NotificationService {  <br>    @Async  <br>    public void sendEmail(String email) {  <br>        // Simulate a slow email send  <br>        Thread.sleep(3000);  <br>        System.out.println(&quot;Email sent to &quot; + email);  <br>    }  <br>}  </pre><pre>@SpringBootApplication  <br>@EnableAsync  <br>public class App {  <br>    public static void main(String[] args) {  <br>        SpringApplication.run(App.class, args);  <br>    }  <br>}</pre><p>✅ <strong>How it works</strong>:</p><ul><li>The sendEmail() method runs in a <strong>separate thread</strong>, freeing the main thread.</li><li>The @EnableAsync annotation enables asynchronous execution.</li></ul><h3>Thread Pool Configuration</h3><pre>@Configuration  <br>public class AsyncConfig {  <br>    @Bean  <br>    public Executor taskExecutor() {  <br>        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();  <br>        executor.setCorePoolSize(10);  <br>        executor.setMaxPoolSize(50);  <br>        executor.initialize();  <br>        return executor;  <br>    }  <br>}</pre><p>✅ <strong>Why use a thread pool?</strong></p><ul><li>Avoids creating unlimited threads (which can crash the system).</li><li>Reuses threads efficiently.</li></ul><h3>3. Parallelism in Java Spring Boot</h3><p>Parallelism is achieved via:</p><ul><li>parallelStream() (for data processing)</li><li>CompletableFuture (for async task coordination)</li><li>ForkJoinPool (for recursive task splitting)</li></ul><h3>Example: parallelStream()</h3><pre>List&lt;Integer&gt; results = numbers.parallelStream()  <br>    .map(n -&gt; compute(n)) // CPU-intensive task  <br>    .collect(Collectors.toList());</pre><p>✅ <strong>How it works</strong>:</p><ul><li>Splits the list into chunks and processes them in parallel.</li><li>Uses ForkJoinPool.commonPool() by default.</li></ul><h3>Example: CompletableFuture</h3><pre>CompletableFuture&lt;String&gt; task1 = CompletableFuture.supplyAsync(() -&gt; fetchDataFromAPI());  <br>CompletableFuture&lt;String&gt; task2 = CompletableFuture.supplyAsync(() -&gt; queryDatabase());  </pre><pre>CompletableFuture.allOf(task1, task2).join(); // Wait for both</pre><p>✅ <strong>Best for</strong>: Running independent tasks in parallel.</p><h3>4. Scaling to 20,000 Tasks on a 16-Core System: Concurrency vs Parallelism vs Virtual Threads</h3><p>One of the most critical challenges in modern application development is efficiently processing large workloads with limited hardware resources. Let’s examine how three different approaches handle <strong>20,000 tasks on a 16-core system</strong>, where each task takes <strong>2 seconds</strong> to complete (mostly I/O-bound work like API calls or database operations).</p><h3>a. Traditional Concurrency Approach (Thread Pool)</h3><h3>How It Works</h3><ul><li>Uses a fixed-size thread pool (typically 50–100 threads)</li><li>Tasks are interleaved — when one task waits for I/O, the thread switches to another task</li><li>Managed by ThreadPoolExecutor or @Async in Spring</li></ul><h3>Performance Calculation</h3><ul><li><strong>Thread pool size</strong>: 50 threads</li><li><strong>Tasks per batch</strong>: 50</li><li><strong>Total batches</strong>: 20,000 / 50 = 400</li><li><strong>Time per batch</strong>: 2 seconds (since tasks overlap via I/O waiting)</li><li><strong>Total time</strong>: 400 × 2s = <strong>800 seconds (~13 minutes)</strong></li></ul><h3>Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XqFVWO5HQoekheCLWVzASw.png" /></figure><h3>b. Parallelism Approach (Maxing Out CPU Cores)</h3><h3>How It Works</h3><ul><li>Uses all 16 CPU cores</li><li>Tasks run in true parallel (16 at a time)</li><li>Implemented via parallelStream() or ForkJoinPool</li></ul><h3>Performance Calculation</h3><ul><li><strong>Parallel tasks</strong>: 16 (one per core)</li><li><strong>Tasks per batch</strong>: 16</li><li><strong>Total batches</strong>: 20,000 / 16 = 1,250</li><li><strong>Time per batch</strong>: 2 seconds</li><li><strong>Total time</strong>: 1,250 × 2s = <strong>2,500 seconds (~42 minutes)</strong></li></ul><h3>Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPipnr1Bmp6pHYdLgs1jNQ.png" /></figure><h3>c. Virtual Threads Approach (Java 21+)</h3><h3>How It Works</h3><ul><li>Creates <strong>20,000 lightweight virtual threads</strong> (managed by JVM)</li><li>When a task blocks (e.g., waiting for DB), the thread is “parked” and another runs</li><li>No manual thread pool tuning needed</li></ul><h3>Performance Calculation</h3><ul><li><strong>Virtual threads</strong>: 20,000 (one per task)</li><li><strong>Carrier threads</strong>: Matches CPU cores (16)</li><li><strong>Tasks complete as I/O responses arrive</strong></li><li><strong>Total time</strong>: ~2 seconds (for the slowest tasks)</li></ul><h3>Why It’s Faster</h3><ul><li>No thread pool queueing delay</li><li>Zero wasted threads on I/O waits</li><li>JVM optimally schedules work across 16 cores</li></ul><h3>Pros &amp; Cons</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rL80y5Rvj5hq63_SLPaAWA.png" /></figure><h3>Direct Comparison (20,000 Tasks on 16 Cores)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0CR8DwJ8Y849iwpZMyshEA.png" /></figure><h3>Key Takeaways</h3><ol><li><strong>Concurrency (Thread Pools)</strong></li></ol><ul><li>Decent for legacy systems</li><li>Requires careful tuning</li><li>Wastes some resources on idle threads</li></ul><p><strong>2. Parallelism (CPU-Bound)</strong></p><ul><li>Only helps if tasks are CPU-intensive</li><li>Terrible for I/O workloads</li><li>Hard limit at 16 parallel tasks</li></ul><p><strong>3. Virtual Threads</strong></p><ul><li><strong>Revolutionary for I/O-bound apps</strong></li><li>Simple programming model (no async/await)</li><li>Enables true “thread-per-request” at scale</li></ul><h3>When to Use Each?</h3><ul><li><strong>Stuck on Java 8–17?</strong> → Use thread pools carefully</li><li><strong>CPU-heavy processing?</strong> → Use parallelStream()</li><li><strong>Building modern microservices?</strong> → <strong>Virtual threads are the clear winner</strong></li></ul><h3>5. Virtual Threads (Java 21) — The Game Changer</h3><p><strong>Virtual Threads</strong> (Project Loom) solve the limitations of traditional threads:<br>✔ <strong>Lightweight</strong> (few KB per thread vs. 1MB for platform threads).<br>✔ <strong>Managed by JVM</strong> (not OS), allowing <strong>millions of threads</strong>.<br>✔ <strong>No thread pool needed</strong> — just spawn a new virtual thread per task!</p><h3>Example: 20,000 Tasks with Virtual Threads</h3><pre>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {  <br>    for (int i = 0; i &lt; 20000; i++) {  <br>        executor.submit(() -&gt; processTask(i));  <br>    }  <br>}</pre><p>✅ <strong>How it works</strong>:</p><ul><li>Each task gets its own <strong>virtual thread</strong>.</li><li>When a task waits (e.g., for I/O), the JVM <strong>parks</strong> it and runs another.</li><li><strong>No memory overload</strong> (unlike 20,000 platform threads).</li></ul><h3>Why Virtual Threads Win</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owHOzGv3Oe4mz2gdtBzQiw.png" /></figure><h3>6. Conclusion &amp; Recommendations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSHRT5t-go7pOAoHBv8hsA.png" /></figure><h3>Final Thoughts</h3><ul><li><strong>Use Concurrency</strong> when tasks involve waiting (I/O).</li><li><strong>Use Parallelism</strong> for CPU-heavy work (but respect core limits).</li><li><strong>Virtual Threads</strong> are the future for scalable, high-concurrency apps.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2abe6ae30243" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leading a High-Performing Engineering Team: A Guide for Software Team Leaders]]></title>
            <link>https://medium.com/@sajib.cuetcse10/leading-a-high-performing-engineering-team-a-guide-for-software-team-leaders-25814ca10892?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/25814ca10892</guid>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Thu, 08 May 2025 20:18:36 GMT</pubDate>
            <atom:updated>2025-05-08T20:39:45.453Z</atom:updated>
            <content:encoded><![CDATA[<p>Leading an engineering team is more than managing tasks — it’s about building trust, making critical decisions under pressure, and constantly growing yourself while nurturing others. In this guide, we address real-world leadership challenges, common mistakes, and how to navigate conflicting demands from both management and your team.</p><h3>Leadership Fundamentals for Engineering Teams</h3><h3>How Close Should a Leader Get to a Developer?</h3><p>A leader must balance <strong>accessibility</strong> and <strong>authority</strong>. Be close enough to:</p><ul><li>Understand blockers</li><li>Offer mentorship</li><li>Motivate and inspire</li></ul><p>But avoid micromanagement. Maintain enough distance to:</p><ul><li>Empower autonomy</li><li>Avoid dependency</li><li>Preserve your strategic focus</li></ul><p><strong><em>Approach</em></strong><em>: Be available, not overbearing.</em></p><h3>Should a Leader Be Hard or Soft?</h3><p>Neither extreme works long-term.</p><ul><li><strong>Too soft?</strong> You lose accountability and respect.</li><li><strong>Too hard?</strong> You kill morale and innovation.</li></ul><p><strong><em>Ideal</em></strong><em>: Firm with principles, flexible with people.</em></p><h3>Handling Common Team Dynamics</h3><h3>If a Team Member Demands an Unrealistic Promotion</h3><p>Be honest and supportive:</p><ul><li>Acknowledge ambition</li><li>Share a clear growth roadmap</li><li>Offer mentorship, but don’t promote prematurely</li></ul><p><em>“You’re valuable here, and I want to help you grow into that role — not just be placed into it.”</em></p><h3>If a Team Member Is More Skilled Than You</h3><p>Don’t compete — <strong>collaborate</strong>. Your job isn’t to be the smartest, but to:</p><ul><li>Build the best team</li><li>Facilitate decisions</li><li>Align talent with outcomes</li></ul><p><strong><em>Great leaders build leaders — not followers.</em></strong></p><h3>If a Team Member Argues</h3><p>Arguments aren’t always bad. Distinguish between:</p><ul><li><strong>Healthy challenge</strong>: Invite it, learn from it.</li><li><strong>Toxic pushback</strong>: Address it calmly and firmly</li></ul><p>Always:</p><ul><li>Stay calm</li><li>Refocus on facts and goals</li><li>Follow up privately if tension remains</li></ul><h3>Performance Management</h3><h3>How Much Mistake Should a Leader Tolerate?</h3><p>Tolerate <strong>honest mistakes that come with learning</strong>. But not:</p><ul><li>Repeated negligence</li><li>Refusal to take ownership</li></ul><p>Use a 3-strike mental model:</p><ol><li>Private conversation</li><li>Performance plan</li><li>Escalation or replacement</li></ol><h3>How to Handle an Unmotivated or Underperforming Member</h3><ol><li>Observe and confirm the behavior</li><li>Have a direct 1:1 conversation</li><li>Set clear expectations and timelines</li><li>Offer coaching or support</li><li>Follow up and take action if no progress</li></ol><p><em>Balance empathy with accountability.</em></p><h3>What If a Member Needs Constant Follow-Up?</h3><p>That’s a signal of either:</p><ul><li>Skill gap (train them)</li><li>Priority issue (coach them)</li><li>Attitude problem (warn them)</li></ul><p>Raise accountability without creating fear:</p><ul><li>Use deadline reminders</li><li>Track commitments</li><li>Reflect ownership in appraisals</li></ul><h3>Navigating Management Pressure</h3><h3>Should a Leader Always Side with Management or Team?</h3><p>Neither. A leader is a <strong>bridge</strong>, not a side-taker.</p><ul><li>To management: Represent team capacity and needs</li><li>To the team: Represent business urgency and goals</li></ul><h3>Should You Pass All Management Pressure to the Team?</h3><p>No. Act as a <strong>buffer</strong>:</p><ul><li>Translate urgency into focused goals</li><li>Shield the team from chaos</li><li>Deliver the message with clarity, not panic</li></ul><h3>Deadlines, Burnout, and Motivation</h3><h3>How to Deliver on a Short Deadline</h3><ul><li>Prioritize must-haves</li><li>Assign high-velocity engineers to critical tasks</li><li>Cut non-essential features</li><li>Communicate trade-offs to stakeholders</li><li>Create a war-room-like environment (short-term only)</li></ul><h3>How to Motivate the Team for Extra Work</h3><ul><li>Explain the bigger purpose</li><li>Recognize and reward effort</li><li>Join the hustle as a leader</li><li>Promise rest and appreciation after delivery</li></ul><p><em>People give their best when they feel seen, not squeezed.</em></p><h3>What If the Team Is Burned Out?</h3><ul><li>Reshuffle workloads temporarily</li><li>Have 1:1s to assess emotional fatigue</li><li>Negotiate scope with stakeholders</li><li>Reduce meetings and increase autonomy</li></ul><p>Burned-out teams don’t deliver high-quality output — <strong>they survive</strong>.</p><h3>Handling Favoritism and Priority Issues</h3><h3>When One Member Gets More Priority than Others</h3><p>This happens due to:</p><ul><li>Unique skills</li><li>Business urgency</li><li>Visibility</li></ul><p>If it creates resentment:</p><ul><li>Be transparent about role differences</li><li>Rotate high-visibility tasks</li><li>Make all contributions visible to stakeholders</li></ul><h3>Handling Unrealistic Timelines from Management</h3><ol><li>Understand the urgency and scope</li><li>Negotiate features, resourcing, or timelines</li><li>Offer trade-offs or phased delivery</li><li>Communicate data-driven constraints</li><li>Document risks and compromises</li></ol><p><em>Say: “To hit that date, we’ll need to drop X or add Y.”</em></p><h3>Leadership Styles &amp; When to Use Them</h3><h3>1. Autocratic Leadership (Directive)</h3><h3>What it is:</h3><p>An <strong>autocratic leader</strong> makes decisions unilaterally, without much input from team members. The leader has complete control over all aspects of the project, from planning to execution. This style is often used in situations where speed and efficiency are paramount, or in high-stakes environments.</p><h3>When to use it:</h3><ul><li><strong>Crisis situations</strong>: When quick decisions are required, such as handling an urgent bug or system failure.</li><li><strong>Military-like environments</strong>: Where strict rules and immediate action are necessary.</li><li><strong>Low-skilled teams</strong>: When the team is new or inexperienced, and the leader needs to provide direction and clarity.</li></ul><p><strong>Challenges</strong>: Autocratic leadership can lead to dissatisfaction and lack of engagement if used long-term. It can stifle creativity and initiative in the team.</p><h3>2. Democratic Leadership (Participative)</h3><h3>What it is:</h3><p>In a <strong>democratic leadership</strong> style, leaders encourage input from team members and make decisions through group discussions and consensus. Team members are involved in decision-making, and their opinions are valued.</p><h3>When to use it:</h3><ul><li><strong>Creative or brainstorming sessions</strong>: When new ideas are needed, such as during the development of new features or innovations.</li><li><strong>High-skill teams</strong>: When team members are experienced and can contribute valuable insights.</li><li><strong>Building team cohesion</strong>: When the goal is to create a strong, collaborative team environment.</li></ul><p><strong>Challenges</strong>: Decision-making can become slow due to the need for group consensus, and some team members may feel overlooked if their ideas are not fully considered.</p><h3>3. Transformational Leadership (Inspirational)</h3><h3>What it is:</h3><p>A <strong>transformational leader</strong> focuses on inspiring and motivating the team to exceed their expectations and achieve extraordinary results. This style is centered around personal growth, enthusiasm, and a shared vision of success. The leader acts as a role model and encourages innovation and creativity.</p><h3>When to use it:</h3><ul><li><strong>Long-term vision</strong>: When focusing on long-term goals and strategic direction.</li><li><strong>Innovation-driven environments</strong>: When your team needs to think outside the box and push boundaries.</li><li><strong>Developing future leaders</strong>: When you want to cultivate leadership skills within your team.</li></ul><p><strong>Challenges</strong>: It can be challenging to balance inspiration with the practical demands of delivery. Additionally, not all team members may resonate with this leadership style if they are more focused on day-to-day tasks.</p><h3>4. Transactional Leadership (Rewards and Punishments)</h3><h3>What it is:</h3><p><strong>Transactional leadership</strong> focuses on structure, rewards, and penalties. Leaders set clear goals, expectations, and rewards for achieving those goals. It’s more about maintaining order and ensuring tasks are completed efficiently.</p><h3>When to use it:</h3><ul><li><strong>Routine tasks and projects</strong>: When the work is standardized or involves repetitive processes.</li><li><strong>Performance-driven environments</strong>: When outcomes and productivity need to be measured, such as sales or customer support metrics.</li><li><strong>Large teams or distributed teams</strong>: When the team requires a structured and predictable environment to ensure everyone is aligned.</li></ul><p><strong>Challenges</strong>: This style can lead to a lack of creativity and reduced team morale if used exclusively. It often focuses more on short-term results rather than long-term development.</p><h3>5. Servant Leadership (Empowering and Supporting)</h3><h3>What it is:</h3><p>A <strong>servant leader</strong> puts the needs of the team first, empowering them to perform to the best of their abilities. This style emphasizes empathy, listening, and support rather than exercising authority.</p><h3>When to use it:</h3><ul><li><strong>Building strong team culture</strong>: When the focus is on teamwork, trust, and collaboration.</li><li><strong>Employee development</strong>: When you aim to foster growth and provide support to individual team members.</li><li><strong>High-empowerment teams</strong>: When the team is self-motivated and can thrive with autonomy.</li></ul><p><strong>Challenges</strong>: This style can be misunderstood as being too lenient or lacking in authority. It can also take more time as it focuses heavily on individual growth.</p><h3>6. Laissez-Faire Leadership (Hands-off)</h3><h3>What it is:</h3><p><strong>Laissez-faire leadership</strong> is the most hands-off approach. Leaders offer minimal direction, allowing the team to make decisions on their own. This style works well with highly skilled and self-motivated individuals who need little supervision.</p><h3>When to use it:</h3><ul><li><strong>Highly skilled, experienced teams</strong>: When you have a team of experts who require little to no direction.</li><li><strong>Innovation-driven environments</strong>: When creativity and autonomy are important, such as in research or development teams.</li><li><strong>Encouraging leadership among team members</strong>: When you want to empower team members to take leadership roles.</li></ul><p><strong>Challenges</strong>: Without enough oversight, this leadership style can lead to disorganization, lack of coordination, and missed deadlines if team members are not self-motivated or need more direction.</p><h3>Choosing the Right Leadership Style</h3><p>The best leaders are those who can adapt their style to the situation and the needs of their team. <strong>Leadership is situational</strong> — different challenges and different team dynamics require different approaches. Here’s how to effectively mix and match leadership styles:</p><ul><li><strong>Assess team maturity</strong>: New or less experienced teams may require more direction (autocratic or transactional), while highly skilled, self-sufficient teams may thrive with a hands-off approach (laissez-faire).</li><li><strong>Evaluate the situation</strong>: Urgent, crisis moments require a more authoritative style (autocratic), while long-term projects benefit from collaborative leadership (democratic, transformational).</li><li><strong>Develop your emotional intelligence</strong>: Recognizing the needs of your team and being able to adjust your style will help foster the best outcomes.</li></ul><p>By blending these styles strategically, you can become a more versatile and effective leader, capable of guiding your team through a range of circumstances.</p><h3>Common Scenarios in Software Team Leadership</h3><h3>1. Senior Developers Block Junior Ones</h3><p>Senior devs may unintentionally dominate or be unapproachable.</p><ul><li>Encourage code reviews and pair programming</li><li>Assign mentorship roles</li></ul><h3>2. Poor Communication Across Teams</h3><ul><li>Use daily standups and retrospectives</li><li>Share project goals in every sprint kickoff</li></ul><h3>3. Engineers Struggle with Product Thinking</h3><ul><li>Involve them in early product discussions</li><li>Share business impact of each feature</li></ul><h3>4. Conflicts Between Backend and Frontend Teams</h3><ul><li>Promote shared design documents</li><li>Encourage empathy by job-swapping or pairing</li></ul><h3>5. Lack of Documentation</h3><ul><li>Add documentation as a definition of done</li><li>Rotate the documentation responsibility</li></ul><h3>6. Team Becomes Too Comfortable (Low Innovation)</h3><ul><li>Bring in hackathons or innovation sprints</li><li>Encourage exploration time for new tools</li></ul><h3>7. Engineers Resisting Change (New Tech, Process)</h3><ul><li>Involve them in evaluation</li><li>Run pilots before full rollout</li></ul><h3>How to Get the Best Output from Your Team</h3><p>Getting the best output from your team involves a combination of effective leadership, clear communication, motivation, and creating a conducive work environment. Here are key strategies you can apply to achieve optimal results:</p><h3>1. Set Clear Expectations and Goals</h3><ul><li>Define <strong>SMART goals</strong> (Specific, Measurable, Achievable, Relevant, Time-bound).</li><li>Break down big objectives into smaller, manageable tasks.</li><li>Align individual goals with the team’s overall objectives.</li></ul><h3>2. Provide the Right Tools and Resources</h3><ul><li>Invest in the latest software, technology, or training that supports the team’s needs.</li><li>Ensure that the work environment (hardware, software, workspace) is conducive to productivity.</li></ul><h3>3. Empower and Trust Your Team</h3><ul><li>Delegate responsibilities based on individual strengths.</li><li>Provide autonomy while ensuring accountability.</li><li>Avoid micromanaging. Allow your team to make decisions, solve problems, and come up with creative solutions.</li></ul><h3>4. Offer Continuous Feedback and Recognition</h3><ul><li>Provide both <strong>positive feedback</strong> and <strong>constructive criticism</strong>.</li><li>Make feedback timely, actionable, and specific to the individual’s efforts.</li><li>Recognize achievements both privately and publicly to reinforce positive behaviors.</li></ul><h3>5. Foster Collaboration and Teamwork</h3><ul><li>Encourage collaboration through <strong>pair programming</strong>, <strong>code reviews</strong>, or team brainstorming sessions.</li><li>Promote cross-functional teamwork between developers, designers, product managers, and other departments.</li><li>Build a culture of open communication where every member’s voice is heard.</li></ul><h3>6. Create a Healthy Work-Life Balance</h3><ul><li>Respect personal boundaries — avoid excessive overtime and encourage regular breaks.</li><li>Lead by example: make time for personal well-being to set a healthy tone for the team.</li><li>Offer flexible working arrangements, if possible.</li></ul><h3>7. Encourage Ownership and Accountability</h3><ul><li>Assign clear ownership for tasks or projects.</li><li>Encourage responsibility for deliverables and timelines.</li><li>Hold team members accountable without being overly punitive — focus on constructive outcomes.</li></ul><h3>8. Invest in Professional Development</h3><ul><li>Provide opportunities for training, certifications, or attending conferences.</li><li>Encourage mentorship, coaching, and peer learning within the team.</li><li>Support career development and set growth paths for each team member.</li></ul><h3>9. Foster a Culture of Innovation and Risk-Taking</h3><ul><li>Encourage experimentation and creativity — allow the team to try new approaches without fearing failure.</li><li>Reward innovative thinking, even if the outcome isn’t always perfect.</li><li>Give team members the freedom to explore ideas outside of their immediate responsibilities.</li></ul><h3>10. Be a Source of Motivation and Inspiration</h3><ul><li>Lead by example and set a positive tone for the team.</li><li>Regularly communicate the <strong>vision</strong> and <strong>purpose</strong> behind the work to help team members feel aligned with the larger mission</li></ul><h3>Final Thoughts</h3><p>Being a great leader isn’t about being liked or being the smartest — it’s about:</p><ul><li>Delivering results without burning bridges</li><li>Growing others without shrinking yourself</li><li>Balancing empathy with accountability</li><li>Making hard decisions with a human touch</li></ul><p>Your job is not just to build software — it’s to build <strong>a culture of trust, ownership, and excellence</strong>.</p><blockquote><em>“A leader is one who knows the way, goes the way, and shows the way.” — John C. Maxwell</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25814ca10892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Deep Dive into Flyway for Java SpringProjects: Concepts, Pitfalls, and Power Features]]></title>
            <link>https://medium.com/@sajib.cuetcse10/deep-dive-into-flyway-for-java-springprojects-concepts-pitfalls-and-power-features-532f55c8ba05?source=rss-1543aac61b6a------2</link>
            <guid isPermaLink="false">https://medium.com/p/532f55c8ba05</guid>
            <dc:creator><![CDATA[Mohammad Sajib Miah]]></dc:creator>
            <pubDate>Sat, 03 May 2025 07:56:11 GMT</pubDate>
            <atom:updated>2025-05-03T07:56:11.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Deep Dive into Flyway for Java Springboot Projects: Concepts, Pitfalls, and Power Features</h3><p>Flyway is one of the most powerful database migration tools in the Java ecosystem. It simplifies versioning, schema evolution, and DevOps database automation with minimal setup. However, once you’re beyond basic usage, understanding how Flyway handles scripts, checksums, repeatable migrations, and advanced flags like group, clean, and callbacks becomes essential.</p><p>In this blog post, we’ll cover:</p><ol><li>What Flyway does in a Java project</li><li>How Flyway handles checksums</li><li>Detailed look at <strong>repeatable migrations</strong></li><li>What happens when you modify repeatable or versioned migrations</li><li>Corner cases and real-world pitfalls</li><li>Deep dive into group, clean, and callback options</li></ol><p>Let’s begin!</p><h3>📌 What is Flyway?</h3><p>Flyway is an open-source database migration tool that tracks, executes, and verifies changes to your database schema. It’s heavily used in Spring Boot, but also works standalone or in any Java application.</p><h3>✅ How Flyway Works:</h3><ul><li>Flyway stores a migration history in a table called flyway_schema_history.</li><li>When you add a new migration script (named like V1__create_table.sql), it:</li></ul><ol><li>Runs the script.</li><li>Records its version and checksum.</li><li>Won’t rerun it unless the checksum or logic changes (with some exceptions).</li></ol><h3>🧮 How Flyway Checksum Works</h3><p>Flyway calculates a <strong>checksum</strong> of each migration script file (both versioned and repeatable). It stores this in the history table to detect changes.</p><h3>🔍 What Triggers a Checksum Change?</h3><ul><li>Changing even <strong>a comment</strong> or <strong>whitespace</strong> will cause the checksum to change.</li><li>For versioned migrations, if Flyway sees a checksum mismatch with one already applied, it will <strong>fail validation</strong>.</li><li>For repeatable migrations, if the checksum changes, Flyway <strong>re-runs the migration</strong>.</li></ul><h3>🔁 Repeatable Migrations in Flyway</h3><p>Repeatable migrations use a naming convention like:</p><pre>R__create_views.sql<br>R__refresh_summary_data.sql</pre><p>They don’t have version numbers. Instead, Flyway re-applies them whenever:</p><ul><li>The file content (and thus checksum) changes.</li><li>A versioned migration has run since the last time the repeatable was executed.</li></ul><h3>✅ Use Cases:</h3><ul><li>Views</li><li>Stored Procedures</li><li>Functions</li><li>Reference data</li></ul><h3>❗ Important Rule:</h3><p><strong>Repeatable migrations must always be idempotent</strong> — i.e., safe to run multiple times.</p><h3>⚠️ What If I Modify a Repeatable Script?</h3><p>If you modify a repeatable migration that already contains something like:</p><pre>CREATE TABLE users (...);</pre><p>And you change the file later to add a column or modify its logic, Flyway will:</p><ol><li>Detect the checksum change.</li><li>Attempt to re-run it.</li><li>❌ Fail if the object already exists — unless the script is safe to reapply.</li></ol><h3>✅ Best Practices:</h3><ul><li>Use CREATE OR REPLACE for views or functions.</li><li>Use DROP IF EXISTS or check object existence before creation.</li><li>Make repeatables <strong>idempotent</strong>, e.g.:</li></ul><pre>DO $$<br>BEGIN<br>    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = &#39;users&#39;) THEN<br>        CREATE TABLE users (...);<br>    END IF;<br>END $$;</pre><h3>🧠 Real-World Flyway Corner Cases &amp; Pitfalls</h3><h3>🧨 1. Checksum Mismatch in Versioned Migrations</h3><p><strong>Scenario:</strong> A developer edits a previously applied versioned migration file (e.g., V1__create_user.sql).</p><p><strong>What Happens:</strong></p><ul><li>Flyway compares the new checksum with the stored one.</li><li>If they don’t match, migration fails with:</li></ul><pre>ERROR: Validate failed: Migration checksum mismatch</pre><p><strong>How to Handle:</strong></p><ul><li><strong>Never</strong> edit versioned files after execution.</li><li>If it must be done (only in local/dev), use:</li></ul><pre>flyway repair</pre><h3>🔁 2. Repeatable Migration with Destructive Changes</h3><p><strong>Scenario:</strong> A repeatable migration does something destructive like DROP TABLE or DROP COLUMN.</p><p><strong>Risk:</strong></p><ul><li>A small script edit (e.g., a comment) triggers re-execution.</li><li>Data loss or schema breakage can occur.</li></ul><p><strong>Solution:</strong></p><ul><li>Avoid irreversible operations in repeatables.</li><li>Always write <strong>idempotent</strong>, <strong>safe-to-reapply</strong> logic.</li></ul><h3>🧩 3. Repeatable Migrations Executing Out of Order</h3><p><strong>Scenario:</strong> You have multiple repeatables:</p><pre>R__1_create_views.sql<br>R__2_create_procedures.sql</pre><p>But someone renames them:</p><pre>R__a_views.sql<br>R__b_procedures.sql</pre><p><strong>Issue:</strong></p><ul><li>Execution order changes (alphabetical sorting matters).</li><li>Can break dependencies (e.g., procedure uses view).</li></ul><p><strong>Fix:</strong></p><ul><li>Use consistent, meaningful, alphabetically sorted names.</li><li>Avoid renaming existing repeatables unless you understand the consequence.</li></ul><h3>🐛 4. Multiple Developers Working on Same Version</h3><p><strong>Scenario:</strong> Two devs both create V3__*.sql locally.</p><p><strong>Problem:</strong></p><ul><li>When merged, only one version will run; the other will conflict.</li><li>Causes checksum mismatch or missed migration.</li></ul><p><strong>Solution:</strong></p><ul><li>Use coordination:</li><li>Reserve versions before pushing.</li><li>Or adopt timestamp-based naming (e.g., V20250503_1200__...).</li></ul><h3>🚧 5. Migrations That Depend on Runtime Data</h3><p><strong>Example:</strong></p><pre>INSERT INTO config (value) VALUES (CURRENT_TIMESTAMP);</pre><p><strong>Problem:</strong></p><ul><li>Migrations should be deterministic and replayable.</li><li>Inserting dynamic data makes rollback and debugging hard.</li></ul><p><strong>Fix:</strong></p><ul><li>Keep dynamic content out of migrations.</li><li>Use application-level logic for runtime data insertions.</li></ul><h3>⚖️ 6. Different Flyway Configs in Dev vs Prod</h3><p><strong>Problem:</strong></p><ul><li>Dev allows clean, but prod disables it: properties</li></ul><pre>spring.flyway.clean-disabled=true</pre><ul><li>Someone accidentally runs flyway clean in prod (if not properly disabled).</li></ul><p><strong>Solution:</strong></p><ul><li>Enforce consistent config across environments.</li><li>Use environment variables or profiles carefully.</li></ul><h3>🧼 7. Flyway Clean Deletes Everything</h3><p><strong>Danger:</strong></p><ul><li>flyway clean drops <em>all</em> tables, including non-migration-related ones (e.g., audit logs, backups).</li></ul><p><strong>Fix:</strong></p><ul><li>Disable in prod (clean-disabled=true).</li><li>If needed, use callbacks to handle schema-specific cleanup.</li></ul><h3>🗃️ 8. Non-Transactional Migrations</h3><p>Some databases or commands <strong>don’t support transactions</strong>, e.g., DDL in MySQL or certain partition operations in PostgreSQL.</p><p><strong>What Happens:</strong></p><ul><li>If a statement fails mid-migration, partial changes remain.</li><li>Can leave your DB in an inconsistent state.</li></ul><p><strong>How to Handle:</strong></p><ul><li>Be aware of which statements are non-transactional.</li><li>Use Flyway’s group or mixed options appropriately.</li></ul><h3>⏳ 9. Long-Running Migrations and Timeouts</h3><p><strong>Example:</strong></p><ul><li>You have a data migration that updates millions of rows.</li></ul><p><strong>Problem:</strong></p><ul><li>Script may time out.</li><li>Flyway might mark it as failed even if partially applied.</li></ul><p><strong>Solution:</strong></p><ul><li>Break large migrations into smaller batches.</li><li>Or increase DB timeout settings temporarily.</li></ul><h3>🧪 10. Flyway Repair Misuse</h3><p><strong>Misconception:</strong></p><ul><li>Some devs use flyway repair as a fix-all.</li></ul><p><strong>Risk:</strong></p><ul><li>It updates checksums, masking real issues.</li><li>Can lead to mismatched DB states across environments.</li></ul><p><strong>Tip:</strong></p><ul><li>Only use repair <strong>if you are 100% sure</strong> the DB matches the updated script.</li></ul><h3>👥 11. Multiple Schemas or Tenants</h3><p><strong>Scenario:</strong></p><ul><li>You have multi-tenant or multi-schema setups.</li></ul><p><strong>Issue:</strong></p><ul><li>Flyway tracks migrations per schema by default.</li><li>Managing migrations across schemas needs careful config:</li></ul><p>properties</p><pre>flyway.schemas=tenant1,tenant2</pre><p><strong>Tip:</strong></p><ul><li>Consider running Flyway per tenant with isolated schema history.</li></ul><h3>📦 12. Custom Callbacks Behaving Unexpectedly</h3><p>Flyway supports lifecycle callbacks (beforeMigrate, afterEachMigrate, etc.).</p><p><strong>Gotcha:</strong></p><ul><li>Callbacks execute globally across all migrations and may have unintended side effects if not scoped.</li></ul><p><strong>Fix:</strong></p><ul><li>Keep callbacks modular.</li><li>Test thoroughly across multiple environments.</li></ul><h3>🧱 Flyway group – Run All Migrations in One Transaction</h3><p>By default, Flyway runs <strong>each migration in its own transaction</strong>.</p><h3>Setting:</h3><p>properties</p><pre>spring.flyway.group=true</pre><h3>Behavior:</h3><p>ModeOutcomeDefaultEach V*.sql runs in its own transactiongroup=trueAll versioned migrations run in one transaction</p><h3>✅ Benefit:</h3><ul><li>Atomic — if one migration fails, <strong>none are committed</strong>.</li></ul><h3>⚠️ Caution:</h3><ul><li>Only works if your DB supports transactional DDL (e.g., PostgreSQL does, MySQL often does not).</li></ul><h3>🧼 Flyway clean – Wipe the Schema</h3><h3>What It Does:</h3><ul><li>Drops all tables, views, procedures, etc. in the schema.</li><li>Deletes flyway_schema_history.</li></ul><h3>Usage:</h3><pre>flyway clean</pre><h3>⚠️ DANGER:</h3><ul><li><strong>Do not use in production</strong>.</li></ul><p>Instead:</p><p>properties</p><pre>spring.flyway.clean-disabled=true</pre><h3>✅ Use For:</h3><ul><li>Development resets</li><li>Test automation</li><li>CI pipelines</li></ul><h3>🪝 Flyway callback – Hook into Lifecycle Events</h3><p>Flyway provides <strong>hooks (callbacks)</strong> to execute logic before/after key events:</p><h3>Events include:</h3><ul><li>beforeMigrate, afterMigrate</li><li>beforeEachMigrate, afterEachMigrate</li><li>beforeClean, afterClean</li></ul><h3>✅ Use Cases:</h3><ul><li>Audit logging</li><li>Pre-migration setup (e.g., creating a backup)</li><li>Sending notifications</li><li>Populating reference data</li></ul><h3>✍️ SQL Callback File:</h3><p><strong>File:</strong> beforeMigrate.sql</p><pre>INSERT INTO migration_log (event, run_at) VALUES (&#39;start&#39;, NOW());</pre><h3>👨‍💻 Java Callback Example:</h3><pre>public class CustomCallback extends BaseCallback {<br>    public void handle(Event event, Context context) {<br>        if (event == Event.BEFORE_MIGRATE) {<br>            System.out.println(&quot;About to migrate!&quot;);<br>        }<br>    }<br>}</pre><p>Register:</p><pre>Flyway.configure()<br>    .callbacks(new CustomCallback())<br>    .load()<br>    .migrate();</pre><h3>✅ Final Best Practices for Flyway</h3><p>Writing migrations: Keep versioned migrations immutable</p><p>Repeatables: Ensure they’re idempotent</p><p>Collaboration: Reserve version numbers ahead of time</p><p>Production safety: Disable clean; test group thoroughly</p><p>Callbacks: Use to automate or monitor migrations safely</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=532f55c8ba05" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>