<?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 Samrat Alam on Medium]]></title>
        <description><![CDATA[Stories by Samrat Alam on Medium]]></description>
        <link>https://medium.com/@samrat.alam?source=rss-1f02e6b48bf6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-GmIqvANbw-a4EgBvzZzPA.jpeg</url>
            <title>Stories by Samrat Alam on Medium</title>
            <link>https://medium.com/@samrat.alam?source=rss-1f02e6b48bf6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 10:34:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samrat.alam/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[Hexagonal Architecture Explained Simply: Why It Exists (and Why Layered Architecture Isn’t Wrong)]]></title>
            <link>https://medium.com/@samrat.alam/hexagonal-architecture-explained-simply-why-it-exists-and-why-layered-architecture-isnt-wrong-51b07aadc63a?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b07aadc63a</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 11:40:45 GMT</pubDate>
            <atom:updated>2026-06-27T11:40:45.232Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve searched for Hexagonal Architecture, you’ve probably seen diagrams like this:</p><pre>         UI<br>         │<br>         ▼<br>    ┌───────────┐<br>    │  Domain   │<br>    └───────────┘<br>         ▲<br>         │<br> Database  Kafka  Email  REST API</pre><p>Then someone says:</p><blockquote><em>“Hexagonal Architecture makes your application independent from frameworks.”</em></blockquote><p>Sounds great. But after reading several articles, one question still remains:</p><blockquote><strong><em>“Can’t I do exactly the same thing with a normal layered architecture?”</em></strong></blockquote><p>The answer is:</p><blockquote><strong><em>Yes… if your layered architecture is designed well.</em></strong></blockquote><p>So why does Hexagonal Architecture exist? Let’s understand it with real examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5C1IeY1cDMsS3Z4G.png" /></figure><h3>What Is Layered Architecture?</h3><p>Most Spring Boot applications look like this.</p><pre>Client<br>   │<br>Controller<br>   │<br>Service<br>   │<br>Repository<br>   │<br>Database</pre><p>Each layer has a responsibility.</p><ul><li>Controller → HTTP</li><li>Service → Business Logic</li><li>Repository → Database</li></ul><p>Example:</p><pre>Controller<br>    ↓<br>OrderService<br>    ↓<br>OrderRepository</pre><p>Nothing wrong here. In fact, <strong>most successful Spring applications use this architecture.</strong></p><h3>The Good Part About Layered Architecture</h3><p>It is</p><ul><li>Simple</li><li>Easy to understand</li><li>Fast to develop</li><li>Perfect for CRUD applications</li><li>Great for small and medium projects</li></ul><p>This is why Spring itself encourages this style. So… <strong>Layered Architecture is NOT bad.</strong></p><h3>Where Layered Architecture Starts to Hurt</h3><p>Let’s build an e-commerce application.</p><p>Business requirement:</p><pre>Validate Order<br>    ↓<br>Charge Customer<br>    ↓<br>Save Order<br>    ↓<br>Notify Customer</pre><p>Implementation:</p><pre>@Service<br>class OrderService {<br>private PaymentService paymentService;<br>    private EmailService emailService;<br>    private OrderRepository repository;<br>    public void placeOrder() {<br>        paymentService.pay();<br>        repository.save();<br>        emailService.send();<br>    }<br>}</pre><p>Looks good.</p><h3>Six Months Later…</h3><p>Business grows. Now requirements become:</p><ul><li>Stripe</li><li>bKash</li><li>PayPal</li></ul><p>Typical implementation becomes:</p><pre>if(payment == STRIPE){<br>    .....<br>}<br>else if(payment == BKASH){<br>    .....<br>}<br>else{<br>    .....<br>}</pre><p>Business logic now knows</p><ul><li>Stripe</li><li>bKash</li><li>PayPal</li></ul><p>But are these business concepts? No. These are implementation details.</p><h3>Another Requirement</h3><p>Current:</p><pre>Save Order</pre><p>using</p><pre>PostgreSQL</pre><p>Later:</p><pre>MongoDB</pre><p>Or</p><pre>DynamoDB</pre><p>Business code slowly changes because technology changes.</p><h3>Even Worse…</h3><p>Notification changes. Yesterday</p><pre>Email</pre><p>Tomorrow</p><pre>Kafka Event</pre><p>Next month</p><pre>Push Notification</pre><p>Again… Business logic changes.</p><h3>The Real Problem</h3><p>The business requirement never said</p><pre>Use Stripe<br><br>Use PostgreSQL<br><br>Use Kafka<br><br>Use Email</pre><p>It simply said</p><pre>Charge Customer<br><br>Save Order<br><br>Notify Customer</pre><p>Business thinks in capabilities. Developers often think in technologies.</p><p>Hexagonal Architecture separates those two worlds.</p><h3>Enter Hexagonal Architecture</h3><p>Instead of depending on implementations,</p><p>business depends on <strong>Ports</strong>.</p><pre>interface PaymentPort {<br>  void pay(Order order);<br>}<br><br>interface NotificationPort {<br>    void notify(Order order);<br>}<br><br>interface OrderRepositoryPort {<br>    void save(Order order);<br>}</pre><p>Now the use case becomes</p><pre>class PlaceOrderUseCase {<br>    paymentPort.pay();<br><br>    repository.save();<br><br>    notification.notify();<br>}</pre><p>Notice something interesting.</p><p>There is no</p><ul><li>Stripe</li><li>PostgreSQL</li><li>Kafka</li><li>Spring</li><li>Hibernate</li></ul><p>The code reads exactly like the business requirement.</p><h3>What Is a Port?</h3><p>A Port is simply a contract. It describes <strong>what the business needs</strong>, not <strong>how it is implemented</strong>.</p><p>Think of it like this:</p><pre>    Business<br>       ↓<br>&quot;I need someone to process payment.&quot;</pre><p>Not</p><pre>&quot;I need Stripe.&quot;</pre><h3>The USB-C Analogy</h3><p>This is my favorite way to explain Hexagonal Architecture.</p><p>Your laptop has a <strong>USB-C port</strong>.</p><p>You can plug in</p><ul><li>Charger</li><li>Monitor</li><li>SSD</li><li>Ethernet Adapter</li><li>Docking Station</li></ul><p>The laptop doesn’t know what brand you’re using.</p><p>It only knows</p><pre>USB-C</pre><p>If tomorrow you replace one charger with another, does the laptop change?</p><p>No.</p><p>Only the accessory changes. Exactly the same thing happens in Hexagonal Architecture.</p><pre>            PaymentPort<br>                ▲<br>                │<br>      ┌─────────┴─────────┐<br>      │                   │<br> StripeAdapter     BkashAdapter</pre><p>Business never changes. Only adapters change.</p><h3>Stripe vs bKash Example</h3><p>Business requirement:</p><pre>Charge Customer</pre><p>Today</p><pre>PaymentPort<br>    ↓<br>StripeAdapter</pre><p>Tomorrow</p><pre>PaymentPort<br>    ↓<br>BkashAdapter</pre><p>Business code stays exactly the same. Only infrastructure changes.</p><h3>Database Example</h3><p>Business says</p><pre>Save Order</pre><p>Today</p><pre>OrderRepositoryPort<br>    ↓<br>JpaAdapter<br>    ↓<br>PostgreSQL</pre><p>Tomorrow</p><pre>OrderRepositoryPort<br>    ↓<br>MongoAdapter<br>    ↓<br>MongoDB</pre><p>Business doesn’t care.</p><h3>Notification Example</h3><p>Business says</p><pre>Notify Customer</pre><p>Today</p><pre>EmailAdapter</pre><p>Tomorrow</p><pre>KafkaAdapter</pre><p>Next year</p><pre>PushNotificationAdapter</pre><p>Still… Business doesn’t change.</p><h3>“But I Can Do This in Layered Architecture Too!”</h3><p>Yes. And this is where many articles become misleading.</p><p>You absolutely can. For example,</p><pre>interface PaymentGateway {<br>    void pay();<br>}</pre><p>Then</p><pre>StripePaymentGateway</pre><p>implements it. Your service depends on the interface.</p><p>Congratulations.</p><p>You’re already applying <strong>Dependency Inversion</strong>, one of the key ideas behind Hexagonal Architecture.</p><h3>Then What’s the Difference?</h3><p>Hexagonal Architecture makes this a rule. Dependency direction always looks like this.</p><pre>Business<br>    ↓<br>Port (Interface)<br>    ↓<br>Adapter<br>    ↓<br>Framework</pre><p>Never</p><pre>Business<br>    ↓<br>Framework</pre><p>The business owns the contract. Infrastructure adapts to it. Not the other way around.</p><h3>Dependency Direction</h3><p>Layered Architecture usually looks like</p><pre>Controller<br>    ↓<br>Service<br>    ↓<br>Repository<br>    ↓<br>Database</pre><p>Hexagonal Architecture looks like</p><pre>Controller<br>    ↓<br>Use Case<br>    ↓<br>  Port<br>    ↓<br> Adapter<br>    ↓<br>Framework</pre><p>Notice something subtle. In Layered, business often ends up depending on infrastructure.</p><p>In Hexagonal, infrastructure always depends on business. That single difference changes everything.</p><h3>When Should You Use Hexagonal?</h3><p>Use a simple layered architecture when:</p><ul><li>CRUD application</li><li>Admin panel</li><li>Internal tools</li><li>Small project</li><li>Few integrations</li></ul><p>Hexagonal shines when:</p><ul><li>Complex business rules</li><li>Payment gateways</li><li>External APIs</li><li>Kafka</li><li>RabbitMQ</li><li>Multiple databases</li><li>Cloud services</li><li>Large teams</li><li>Long-term maintenance</li><li>Frequently changing integrations</li></ul><h3>Key Takeaways</h3><p>✅ Layered Architecture is not wrong.</p><p>✅ Hexagonal Architecture is not about adding interfaces.</p><p>✅ Ports describe <strong>what</strong> the business needs.</p><p>✅ Adapters decide <strong>how</strong> those needs are fulfilled.</p><p>✅ Business rules should never know about Stripe, Kafka, PostgreSQL, or Spring.</p><p>✅ Think of a <strong>USB-C port</strong>:</p><ul><li>The laptop (business) depends on the USB-C interface.</li><li>Chargers, monitors, SSDs, and docks (adapters) plug into it.</li><li>You can replace any accessory without changing the laptop.</li></ul><p>That’s exactly what Hexagonal Architecture aims to achieve.</p><p>I think this structure would make a <strong>much stronger Medium article</strong> because it teaches <strong>the reasoning behind Hexagonal Architecture</strong>, not just its definitions. Readers first understand the limitations of a typical layered application, then naturally discover ports, adapters, dependency inversion, and finally the USB-C analogy — which usually creates the “aha!” moment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b07aadc63a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polling, SSE, WebSockets, Redis, and Multi-Pod Scaling: Building Real-Time Applications with Spring…]]></title>
            <link>https://medium.com/@samrat.alam/polling-sse-websockets-redis-and-multi-pod-scaling-building-real-time-applications-with-spring-4af8d2ebc055?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af8d2ebc055</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[long-polling]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 15:24:18 GMT</pubDate>
            <atom:updated>2026-06-20T15:24:18.677Z</atom:updated>
            <content:encoded><![CDATA[<h3>Polling, SSE, WebSockets, Redis, and Multi-Pod Scaling: Building Real-Time Applications with Spring Boot</h3><h3>Introduction</h3><p>Many developers learn WebSocket by building a simple chat application on a single machine.</p><p>Everything works:</p><pre>User A &lt;---&gt; Spring Boot App &lt;---&gt; User B</pre><p>Then the application is deployed to Kubernetes:</p><pre>                    Load Balancer<br>                        |<br>          -----------------------------<br>          |             |             |<br>        Pod-1         Pod-2         Pod-3</pre><p>Suddenly:</p><ul><li>Messages are missing</li><li>Online status becomes inaccurate</li><li>WebSocket sessions disappear after pod restarts</li><li>Notifications reach some users but not others</li></ul><p>To understand why, we first need to understand the different real-time communication approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nn3m38QxGEjIivAH.jpeg" /></figure><h3>1. Short Polling</h3><p>With short polling, the client repeatedly asks the server for updates.</p><h3>Flow</h3><pre>Client               Server<br>   | ---- GET -----&gt; |<br>   | &lt;--- Data ----- |<br>(wait 5 seconds)<br>   | ---- GET -----&gt; |<br>   | &lt;--- Data ----- |</pre><h3>Example</h3><p>Checking payment status:</p><pre>Is payment completed?</pre><p>Every 5 seconds:</p><pre>GET /payments/123/status</pre><p>Response:</p><pre>{<br>  &quot;status&quot;: &quot;PROCESSING&quot;<br>}</pre><p>After several requests:</p><pre>{<br>  &quot;status&quot;: &quot;SUCCESS&quot;<br>}</pre><h3>Problems</h3><p>Suppose payment processing takes 2 minutes.</p><p>The browser sends:</p><pre>24 requests</pre><p>But only one request contains new information.<strong> Most requests are wasted.</strong></p><h3>2. Long Polling</h3><p>Long polling reduces unnecessary requests. Instead of responding immediately, the server waits until new data becomes available.</p><h3>Flow</h3><pre>Client                 Server<br>   | ---- GET -------&gt; |<br>   |                   |<br>   |      WAITING      |<br>   |                   |<br>New Event Arrives<br>   | &lt;--- Response --- |</pre><p>The client immediately creates another long-poll request.</p><h3>Spring Boot Concept</h3><pre>DeferredResult&lt;String&gt;</pre><p>The request remains open until:</p><ul><li>Data arrives</li><li>Timeout occurs</li></ul><h3>3. Server-Sent Events (SSE)</h3><p>SSE keeps one HTTP connection open. The server continuously pushes updates to the browser.</p><h3>Flow</h3><pre>Client                   Server<br>   | ---- Connect -----&gt; |<br>   | &lt;--- Event -------- |<br>   | &lt;--- Event -------- |<br>   | &lt;--- Event -------- |</pre><h3>Perfect For</h3><ul><li>Notifications</li><li>Live dashboards</li><li>Monitoring systems</li><li>Stock prices</li></ul><h3>Example</h3><pre>Payment Processing...<br>Payment Successful<br>Receipt Generated<br>Reward Points Added</pre><p>The client subscribes once and continuously receives updates.</p><h3>4. WebSocket</h3><p>WebSocket enables full-duplex communication. Both client and server can send messages anytime.</p><h3>Flow</h3><pre>Client &lt;=================&gt; Server</pre><h3>Perfect For</h3><ul><li>Chat applications</li><li>Multiplayer games</li><li>Collaborative editing</li><li>Live support systems</li></ul><h3>Example</h3><pre>User A: Hello<br>User B: Hi<br>User A: How are you?</pre><p>Messages travel instantly in both directions.</p><h3>Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqB_F1h1it0x1ZMUlhrVKQ.png" /></figure><h3>The Multi-Pod Problem</h3><p>Everything works on a single instance.</p><pre>          Spring Boot<br>               |<br>      -----------------<br>      |               |<br>   User A         User B</pre><p>Now let’s scale.</p><pre>                  Load Balancer<br>                        |<br>          -----------------------------<br>          |             |             |<br>        Pod-1         Pod-2         Pod-3</pre><p>User A connects to Pod-1.</p><p>User B connects to Pod-3.</p><pre>User A ---&gt; Pod-1<br>User B ---&gt; Pod-3</pre><p>User A sends:</p><pre>Hello</pre><p>Question:</p><p>How does Pod-1 send that message to User B connected to Pod-3?</p><p>It cannot. Each pod only knows its own connections.</p><h3>Why Sticky Sessions Are Not Enough</h3><p>A common solution is session affinity.</p><pre>User A -&gt; Pod-1<br>User A -&gt; Pod-1<br>User A -&gt; Pod-1</pre><p>The loadbalancer always routes the user to the same pod.</p><p>While this helps maintain connections, it does not solve cross-pod communication.</p><p>Problems:</p><ul><li>Pod failures</li><li>Uneven load distribution</li><li>Limited scalability</li></ul><h3>🔥 Handling Dynamic Routing (Chat Rooms, Orders, SSE Streams) Without Creating Dynamic Topics</h3><p>In real systems, we often need:</p><h3>Examples:</h3><ul><li>Chat rooms created dynamically (room-123, room-xyz)</li><li>Order tracking (order-1001, order-1002)</li><li>User-specific notifications</li><li>SSE streams per request</li></ul><p>A naive approach is:</p><blockquote><em>“Let’s create a topic per user / order / room”</em></blockquote><p>But this breaks at scale.</p><h3>❌ Wrong Approach: Dynamic Topics (DO NOT DO THIS)</h3><h3>Kafka / Redis Topics:</h3><pre>order-1001-topic<br>order-1002-topic<br>user-100-topic<br>room-abc-topic</pre><h3>Why this fails:</h3><ul><li>Millions of topics = broker overload</li><li>Hard to manage partitions</li><li>Memory + metadata explosion</li><li>Operational nightmare</li></ul><h3>🧠 Correct Approach: Static Topics + Message Routing</h3><p>Instead of creating topics dynamically:</p><pre>chat-events<br>order-events<br>notification-events</pre><p>We embed routing info inside the message.</p><h3>📦 Example 1: Chat Room (Dynamic Groups)</h3><h3>📤 Message sent</h3><p>User sends message to a room:</p><pre>{<br>  &quot;type&quot;: &quot;CHAT_MESSAGE&quot;,<br>  &quot;roomId&quot;: &quot;group-a&quot;,<br>  &quot;senderId&quot;: &quot;user-100&quot;,<br>  &quot;message&quot;: &quot;Hello team!&quot;<br>}</pre><h3>📡 Kafka / Redis topic</h3><pre>chat-events</pre><h3>📊 Flow Diagram</h3><pre>          User A<br>             |<br>             v<br>          Pod-1 (WebSocket Handler)<br>             |<br>             v<br>          Kafka / Redis Topic: chat-events<br>             |<br>             v<br>          All Pods receive event<br>             |<br>   +----------------------+<br>   |                      |<br>Pod-1                 Pod-3<br>(room-a users)       (room-b users)<br>   |                      |<br>User A                User B</pre><h3>🎯 Routing logic inside Pod</h3><p>Each pod keeps in-memory mapping:</p><pre>Map&lt;String, Set&lt;WebSocketSession&gt;&gt; roomSessions;</pre><p>Example:</p><pre>room-a → [session1, session2]<br>room-b → [session3]</pre><p>Then:</p><pre>Set&lt;WebSocketSession&gt; sessions = roomSessions.get(message.getRoomId());<br><br>if (sessions != null) {<br>    sendToAll(sessions, message);<br>}</pre><h3>📦 Example 2: Order Status Streaming (SSE)</h3><h3>📤 Client subscribes</h3><pre>GET /orders/1001/stream</pre><h3>🧠 Pod stores emitter locally</h3><pre>Map&lt;String, SseEmitter&gt; emitters;<br><br>order-1001 → emitter</pre><h3>📡 Order event published</h3><pre>{<br>  &quot;orderId&quot;: &quot;1001&quot;,<br>  &quot;status&quot;: &quot;SHIPPED&quot;<br>}</pre><p>Sent to:</p><pre>order-events</pre><h3>📊 Flow Diagram</h3><pre>          Order Service<br>               |<br>               v<br>          Kafka / Redis Topic: order-events<br>               |<br>               v<br>          All Pods receive event<br>               |<br>     +----------------------+<br>     |                      |<br>Pod-1                 Pod-2<br>(no emitter)        (has emitter)<br>                         |<br>                         v<br>                SSE → Browser updates</pre><h3>🎯 Pod-side filtering</h3><pre>if (emitters.containsKey(event.getOrderId())) {<br>    emitters.get(orderId).send(event.getStatus());<br>}</pre><h3>📦 Key Insight (VERY IMPORTANT)</h3><p>👉 <strong>All pods receive all events</strong><br> 👉 Only the correct pod responds</p><p>This avoids:</p><ul><li>Dynamic topics</li><li>Complex routing in Kafka</li><li>Broker overload</li></ul><h3>🧠 Kafka Version (Same Concept)</h3><p>Instead of dynamic topics:</p><pre>order-events</pre><p>Use partition key:</p><pre>kafkaTemplate.send(&quot;order-events&quot;, orderId, event);</pre><h3>Guarantees:</h3><pre>Same orderId → same partition → ordered processing</pre><h3>🚀 Mental Model (Easy to Remember)</h3><pre>Topics = highways<br>Messages = trucks<br>orderId / roomId = GPS address<br>Pods = delivery centers<br>Redis/Kafka = traffic controller</pre><p>✔ Do NOT create topics per user/order/room<br> ✔ Use fixed topics<br> ✔ Put routing data inside message<br> ✔ Let pods decide what to process<br> ✔ Combine with Redis for session lookup</p><h3>Introducing Redis Pub/Sub</h3><p>Redis becomes the communication bridge between pods.</p><h3>Architecture</h3><pre>             Redis Pub/Sub<br>            /      |     \<br>         Pod-1   Pod-2   Pod-3</pre><h3>Message Flow</h3><p>User A sends a message.</p><pre>User A<br>   |<br> Pod-1</pre><p>Instead of trying to find User B directly:</p><pre>redis.publish(&quot;chat-room-1&quot;, message);</pre><p>Redis distributes the message:</p><pre>                Redis<br>               /  |  \<br>              /   |   \<br>           Pod1 Pod2 Pod3</pre><p>Every pod receives the event. Pod-3 finds User B and pushes the message through WebSocket.</p><h3>Tracking Online Users</h3><p>A common beginner mistake:</p><pre>Map&lt;String, Session&gt; sessions</pre><p>This works only inside a single pod. In distributed systems we use Redis.</p><h3>Presence Tracking</h3><p>When user connects:</p><pre>SET online:user:100 pod-2</pre><p>When user disconnects:</p><pre>DEL online:user:100</pre><p>Checking online status:</p><pre>exists(&quot;online:user:100&quot;)</pre><h3>The Pod Crash Problem</h3><p>Suppose:</p><pre>User Connected</pre><p>Then:</p><pre>Pod Crashed</pre><p>Disconnect event never executes.</p><p>Redis still shows:</p><pre>online:user:100</pre><p>Incorrect.</p><h3>Using TTL and Heartbeats</h3><p>A better approach:</p><pre>SET online:user:100 pod-2 EX 60</pre><p>The key automatically expires after 60 seconds.</p><p>Every 30 seconds:</p><pre>{<br>  &quot;type&quot;: &quot;PING&quot;<br>}</pre><p>Server refreshes TTL:</p><pre>EXPIRE online:user:100 60</pre><h3>Presence Flow</h3><pre>Connect<br>   |<br>   v<br>Save Redis Presence<br>(TTL = 60s)<br>   |<br>Heartbeat Every 30s<br>   |<br>Refresh TTL<br>   |<br>Disconnect<br>   |<br>Delete Presence</pre><p>If a pod crashes:</p><pre>Heartbeat Stops<br>       |<br>TTL Expires<br>       |<br>User Automatically Offline</pre><h3>Last Seen Feature</h3><p>Applications often show:</p><pre>Last Seen 5 Minutes Ago</pre><p>Store:</p><pre>last_seen:user:100</pre><p>Whenever:</p><ul><li>User disconnects</li><li>Heartbeat expires</li><li>Session closes</li></ul><h3>Multi-Device Support</h3><p>Users may connect from:</p><pre>Web<br>Mobile<br>Tablet</pre><p>Do not store:</p><pre>online:user:100 = true</pre><p>Store active sessions:</p><pre>user:100:sessions</pre><p>Example:</p><pre>session-web<br>session-mobile<br>session-tablet</pre><p>User is online if:</p><pre>session count &gt; 0</pre><h3>Production Architecture</h3><p>A scalable chat system typically looks like this:</p><pre>                  Load Balancer<br>                          |<br>          ----------------------------------<br>          |                |              |<br>        WS-1             WS-2           WS-3<br>          |                |              |<br>          ----------------------------------<br>                          |<br>                   Redis Pub/Sub<br>                          |<br>                    Chat Service<br>                          |<br>                       Database</pre><h3>Message Flow</h3><p>User A sends:</p><pre>Hello</pre><p>Flow:</p><pre>User A<br>   |<br>WebSocket Pod-1<br>   |<br>Redis Pub/Sub<br>   |<br>WebSocket Pod-3<br>   |<br>User B</pre><h3>Presence Flow</h3><pre>User Connects<br>      |<br>      v<br>Redis Presence Store<br>      |<br>Heartbeat<br>      |<br>TTL Refresh<br>      |<br>Online Indicator</pre><h3>When Redis Is Not Enough</h3><p>Redis Pub/Sub is excellent for:</p><ul><li>Notifications</li><li>Chat</li><li>Presence</li></ul><p>However, messages are not durable.</p><p>If a subscriber is down:</p><pre>Message Lost</pre><p>For critical systems:</p><ul><li>Financial transactions</li><li>Audit logs</li><li>Event sourcing</li><li>Large-scale messaging</li></ul><p>Use:</p><pre>Kafka</pre><p>instead.</p><h3>Conclusion</h3><p>The journey usually looks like this:</p><pre>Short Polling<br>      ↓<br>Long Polling<br>      ↓<br>     SSE<br>      ↓<br>WebSocket<br>      ↓<br>Multi-Pod Scaling<br>      ↓<br>Redis Presence<br>      ↓<br>Redis Pub/Sub<br>      ↓<br>Kafka (Large Scale)</pre><p>Understanding WebSocket alone is not enough for modern systems. The real challenge begins when your application runs across multiple pods and thousands of concurrent connections.</p><p>Redis presence tracking, heartbeat mechanisms, and distributed messaging are the building blocks that transform a simple chat application into a production-ready real-time platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af8d2ebc055" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Java Functional Interfaces (Predicate, Function, BiFunction)]]></title>
            <link>https://medium.com/@samrat.alam/java-functional-interfaces-predicate-function-bifunction-4f9004e80fb7?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f9004e80fb7</guid>
            <category><![CDATA[java-functional-interface]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 03:01:34 GMT</pubDate>
            <atom:updated>2026-04-01T03:01:34.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern Java isn’t just about OOP anymore. Since Java 8, functional programming has become a <strong>core part of writing clean, scalable, and production-grade code</strong>.</p><p>If you’re working with <strong>Spring Boot, fintech systems, or rule engines</strong>, understanding functional interfaces is not optional — it’s essential.</p><p>Let’s break it down with <strong>simple explanations + real-world examples</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrPK3YENWMdAaIPrzSxg_g.png" /></figure><h3>🔹 What is a Functional Interface?</h3><p>A <strong>functional interface</strong> is an interface that has:</p><ul><li>Exactly <strong>one abstract method</strong></li><li>Can have multiple <strong>default/static methods</strong></li></ul><p>Example:</p><pre>@FunctionalInterface<br>interface DiscountStrategy {<br>    double apply(double price);<br>}</pre><p>With lambda:</p><pre>DiscountStrategy tenPercent = price -&gt; price * 0.9;</pre><h3>🔹 Why Functional Interfaces Matter</h3><p>They allow you to:</p><p>✔ Write less boilerplate code<br>✔ Pass behavior as data<br>✔ Build flexible and reusable systems<br>✔ Replace complex if-else logic</p><h3>🔹 Core Functional Interfaces (java.util.function)</h3><p>Let’s explore the most useful ones.</p><h3>✅ 1. Predicate → Condition Checker</h3><p>👉 Takes input → returns boolean</p><pre>Predicate&lt;Double&gt; isExpensive = price -&gt; price &gt; 1000;<br><br>System.out.println(isExpensive.test(1500)); // true</pre><h3>💡 Real Use Case: Discount Eligibility</h3><pre>Predicate&lt;Double&gt; eligibleForDiscount = price -&gt; price &gt;= 500;<br><br>if (eligibleForDiscount.test(600)) {<br>    System.out.println(&quot;Discount applicable&quot;);<br>}</pre><h3>✅ 2. Function&lt;T, R&gt; → Transformation</h3><p>👉 Takes input → returns output</p><pre>Function&lt;Double, Double&gt; applyDiscount = price -&gt; price * 0.9;<br><br>System.out.println(applyDiscount.apply(1000)); // 900</pre><h3>❗ Common Mistake (Important)</h3><p>Many developers try this:</p><pre>Function&lt;Double, Double&gt; tax = (p, t) -&gt; p * t; // ❌ WRONG</pre><p>👉 Problem: Function accepts only <strong>one input</strong></p><h3>✅ Correct Way: Use BiFunction</h3><pre>BiFunction&lt;Double, Double, Double&gt; tax = (price, rate) -&gt; price * rate;</pre><h3>Example:</h3><pre>double taxAmount = tax.apply(1000.0, 0.15); // 150.0</pre><h3>✅ 3. Consumer → Side Effects</h3><p>👉 Takes input → <strong>returns nothing</strong></p><pre>Consumer&lt;Double&gt; logger = price -&gt; System.out.println(&quot;Final price: &quot; + price);<br><br>logger.accept(500);</pre><h3>✅ 4. Supplier → Value Provider</h3><p>👉 No input → returns value</p><pre>Supplier&lt;Double&gt; randomDiscount = () -&gt; Math.random() * 0.2;<br><br>System.out.println(randomDiscount.get());</pre><h3>🔥 Real-World Example: Discount + Tax Engine</h3><p>Let’s build something closer to production.</p><h3>🎯 Goal:</h3><ul><li>Check eligibility</li><li>Apply discount</li><li>Apply tax</li><li>Log result</li></ul><h3>🧠 Implementation</h3><pre>import java.util.function.*;<br><br><br>public class PricingEngine {<br><br>    public static double calculateFinalPrice(<br>            double price,<br>            Predicate&lt;Double&gt; eligibility,<br>            Function&lt;Double, Double&gt; discount,<br>            BiFunction&lt;Double, Double, Double&gt; taxCalculator,<br>            double taxRate,<br>            Consumer&lt;Double&gt; logger<br>    ) {<br>        double updatedPrice = price;<br><br>        if (eligibility.test(price)) {<br>            updatedPrice = discount.apply(price);<br>        }<br>        double tax = taxCalculator.apply(updatedPrice, taxRate);<br>        double finalPrice = updatedPrice + tax;<br>        logger.accept(finalPrice);<br><br>        return finalPrice;<br>    }<br>}<br></pre><h3>🚀 Usage</h3><pre>public class Main {<br>    public static void main(String[] args) {<br>        Predicate&lt;Double&gt; eligible = p -&gt; p &gt;= 500;<br>        Function&lt;Double, Double&gt; discount = p -&gt; p * 0.9;<br>        BiFunction&lt;Double, Double, Double&gt; tax =<br>                (amount, rate) -&gt; amount * rate;<br><br>        Consumer&lt;Double&gt; logger =<br>                p -&gt; System.out.println(&quot;Final price: &quot; + p);<br><br>        double result = PricingEngine.calculateFinalPrice(<br>                1000,<br>                eligible,<br>                discount,<br>                tax,<br>                0.15,<br>                logger<br>        );<br>        System.out.println(&quot;Returned: &quot; + result);<br>    }<br>}</pre><h3>🧠 Advanced Concepts (Level Up)</h3><h3>🔹 Function Composition</h3><pre>Function&lt;Double, Double&gt; discount = p -&gt; p * 0.9;<br>Function&lt;Double, Double&gt; tax = p -&gt; p * 1.1;<br><br>Function&lt;Double, Double&gt; finalPrice = discount.andThen(tax);</pre><h3>🔹 Predicate Chaining</h3><pre>Predicate&lt;Double&gt; highPrice = p -&gt; p &gt; 500;<br>Predicate&lt;Double&gt; lessThan2000 = p -&gt; p &lt; 2000;<br><br>Predicate&lt;Double&gt; validRange = highPrice.and(lessThan2000);</pre><h3>🔥 Architecture Insight (Senior-Level)</h3><p>Instead of writing:</p><pre>if (userType.equals(&quot;VIP&quot;)) {<br>    // logic<br>}</pre><p>Use:</p><pre>Map&lt;String, Function&lt;Double, Double&gt;&gt; discountStrategies;</pre><p>👉 This enables:</p><ul><li>Strategy pattern without classes</li><li>Easy extension</li><li>Clean, testable code</li></ul><h3>❌ Traditional Approach (Not Scalable)</h3><pre>public double applyDiscount(String userType, double price) {<br>    if (userType.equals(&quot;VIP&quot;)) {<br>        return price * 0.8;<br>    } else if (userType.equals(&quot;REGULAR&quot;)) {<br>        return price * 0.9;<br>    } else if (userType.equals(&quot;NEW&quot;)) {<br>        return price * 0.95;<br>    }<br>    return price;<br>}</pre><h3>🚫 Problems:</h3><ul><li>Hard to extend</li><li><strong>Violates Open/Closed Principle</strong></li><li>Becomes messy with more rules</li></ul><h3>✅ Modern Approach (Strategy via Map)</h3><h3>🧠 Step 1: Define Strategies</h3><pre>import java.util.HashMap;<br>import java.util.Map;<br>import java.util.function.Function;<br><br>public class DiscountService {<br>    private static final Map&lt;String, Function&lt;Double, Double&gt;&gt; discountStrategies = new HashMap&lt;&gt;();<br>    static {<br>        discountStrategies.put(&quot;VIP&quot;, price -&gt; price * 0.8);<br>        discountStrategies.put(&quot;REGULAR&quot;, price -&gt; price * 0.9);<br>        discountStrategies.put(&quot;NEW&quot;, price -&gt; price * 0.95);<br>    }</pre><h3>🧠 Step 2: Apply Strategy Dynamically</h3><pre>public static double applyDiscount(String userType, double price) {<br>      Function&lt;Double, Double&gt; strategy =<br>                discountStrategies.getOrDefault(userType, p -&gt; p);<br>        return strategy.apply(price);<br>    }<br>}</pre><h3>🚀 Step 3: Usage</h3><pre>public class Main {<br>    public static void main(String[] args) {<br><br>        double vipPrice = DiscountService.applyDiscount(&quot;VIP&quot;, 1000);<br>        double regularPrice = DiscountService.applyDiscount(&quot;REGULAR&quot;, 1000);<br>        double newUserPrice = DiscountService.applyDiscount(&quot;NEW&quot;, 1000);<br>        double unknownPrice = DiscountService.applyDiscount(&quot;UNKNOWN&quot;, 1000);<br><br>        System.out.println(&quot;VIP: &quot; + vipPrice);         // 800<br>        System.out.println(&quot;Regular: &quot; + regularPrice); // 900<br>        System.out.println(&quot;New: &quot; + newUserPrice);     // 950<br>        System.out.println(&quot;Default: &quot; + unknownPrice); // 1000<br>    }<br>}</pre><h3>🔥 Why This is Powerful (Senior Insight)</h3><h3>✔ Open for extension, closed for modification</h3><p>Add new strategy without touching logic:</p><pre>discountStrategies.put(&quot;STUDENT&quot;, price -&gt; price * 0.85);</pre><h3>✔ Plug from DB / Config (Real Fintech Use Case)</h3><p>You can load dynamically:</p><pre>discountStrategies.put(userTypeFromDB, dynamicLambda);</pre><h3>✔ Works perfectly with Spring Boot</h3><p>Example idea:</p><pre>@Component<br>Map&lt;String, Function&lt;Double, Double&gt;&gt; discountStrategies;</pre><p>Or inject different beans by qualifier.</p><h3>🔥 Even Better (Enum-Based Strategy — Safer)</h3><p>Avoid string bugs:</p><pre>enum UserType {<br>    VIP, REGULAR, NEW<br>}<br><br>Map&lt;UserType, Function&lt;Double, Double&gt;&gt; strategies = Map.of(<br>    UserType.VIP, p -&gt; p * 0.8,<br>    UserType.REGULAR, p -&gt; p * 0.9,<br>    UserType.NEW, p -&gt; p * 0.95<br>);</pre><h3>🧠 Next-Level Upgrade (Production Thinking)</h3><p>In fintech pricing systems, you often combine:</p><pre>Function&lt;Double, Double&gt; discount;<br>BiFunction&lt;Double, Double, Double&gt; tax;<br>Function&lt;Double, Double&gt; fee;</pre><p>👉 Then chain them into a <strong>pipeline</strong></p><h3>🔚 Final Thoughts</h3><p>Functional interfaces are not just a Java feature — they are a <strong>design mindset</strong>. They help you:</p><p>✔ Build flexible systems<br>✔ Reduce complexity<br>✔ Write production-grade clean code</p><p>If you’re building <strong>fintech systems, pricing engines, or microservices</strong>, mastering these concepts will significantly improve your design quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f9004e80fb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ HTTP/1.1 vs HTTP/2 vs HTTP/3 — Evolution of the Web]]></title>
            <link>https://medium.com/@samrat.alam/http-1-1-vs-http-2-vs-http-3-evolution-of-the-web-d5811be3114f?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5811be3114f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[http1-vs-http2-vs-http3]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 05:28:29 GMT</pubDate>
            <atom:updated>2026-03-28T05:28:29.738Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Why your API feels slow… even when your code is fast.</em></blockquote><h3>🚀 Introduction</h3><p>As backend engineers, we spend hours optimizing:</p><ul><li>database queries</li><li>caching layers</li><li>thread pools</li></ul><p>…but often ignore one critical layer:</p><p>👉 <strong>the protocol that actually moves your data</strong></p><p>HTTP isn’t just a “request-response thing” anymore.<br>It has evolved across three major generations:</p><ul><li><strong>HTTP/1.1</strong> → Works</li><li><strong>HTTP/2</strong> → Optimizes</li><li><strong>HTTP/3</strong> → Reinvents</li></ul><p>This is not just an upgrade — it’s an <strong>architectural shift</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EdoaN9bDab0ewAgfhCnDSw.png" /></figure><h3>🧱 Part 1 — HTTP/1.1: The Sequential Bottleneck</h3><h3>🧠 How it Works</h3><ul><li>Text-based protocol</li><li>Runs on TCP</li><li>One request → one response</li></ul><h3>🔄 Flow Diagram</h3><pre>Client<br>  │<br>  ├─── Request 1 ───────────────▶ Server<br>  │                              │<br>  │◀──────── Response 1 ─────────┤<br>  │<br>  ├─── Request 2 ───────────────▶ Server<br>  │                              │<br>  │◀──────── Response 2 ─────────┤<br>  │<br>  ├─── Request 3 ───────────────▶ Server<br>  │                              │<br>  │◀──────── Response 3 ─────────┤</pre><h3>⚠️ The Real Problem: Head-of-Line Blocking</h3><pre>Client<br>  │<br>  ├─── Request 1[Large img] (SLOW) ────────▶ Server<br>  │                              │<br>  │        ❗ waiting...          │<br>  │<br>  ├─── Request 2 ───────────────▶ (blocked)<br>  ├─── Request 3 ───────────────▶ (blocked)</pre><h3>📦 Real Example</h3><p>Loading a dashboard:</p><pre>GET /index.html<br>GET /styles.css<br>GET /app.js<br>GET /orders<br>GET /charts</pre><p>👉 Requests are:</p><ul><li>sequential</li><li>spread across multiple TCP connections</li></ul><h3>🧠 Mental Model</h3><p>🚗 <strong>Single-lane road</strong><br>If one car stops → everything stops</p><h3>💥 Why It Hurts Modern Systems</h3><ul><li>High latency</li><li>Too many connections</li><li>Redundant headers (cookies, auth)</li><li>Poor scalability for microservices</li></ul><h3>⚡ Part 2 — HTTP/2: Multiplexing &amp; Efficiency</h3><h3>🧠 What Changed?</h3><ul><li>Binary protocol</li><li>Multiplexing</li><li>Header compression (HPACK)</li></ul><h3>🔥 Multiplexing (Game Changer)</h3><pre>Single TCP Connection<br><br>Client<br>  │<br>  ├─── Stream 1 (HTML) ─────────▶<br>  ├─── Stream 2 (CSS) ──────────▶<br>  ├─── Stream 3 (JS) ───────────▶<br>  ├─── Stream 4 (API) ──────────▶<br>  │<br>  │◀══ Interleaved Responses ══▶ Server</pre><h3>🔬 Internal Packet Behavior</h3><pre>[Stream1-Part1][Stream2-Part1][Stream3-Part1]<br>[Stream1-Part2][Stream2-Part2][Stream3-Part2]</pre><p>👉 Everything shares <strong>one TCP connection</strong></p><h3>📉 Header Compression (HPACK)</h3><p>Before:</p><pre>Authorization: Bearer abc123<br>Cookie: session=xyz</pre><p>Sent repeatedly ❌</p><p>After:</p><ul><li>Sent once</li><li>Reused efficiently ✅</li></ul><h3>🚨 Hidden Limitation: TCP HOL Blocking</h3><pre>Packet Flow: [1][2][3][4][5][6]<br><br>❌ Packet 3 lost<br><br>Result:<br>[1][2][❗ waiting for 3][4][5][6]</pre><h3>🧠 Insight</h3><ul><li>Parallel at <strong>HTTP level</strong></li><li>Still blocked at <strong>transport (TCP) level</strong></li></ul><h3>🧠 Mental Model</h3><p>🚦 <strong>Multi-lane highway with traffic lights</strong><br>Fast… until something breaks</p><h3>🚀 Part 3 — HTTP/3: Transport-Level Reinvention</h3><h3>🧠 What Changed?</h3><ul><li>Uses <strong>QUIC (UDP-based)</strong></li><li>Built-in TLS 1.3</li><li>Independent streams</li></ul><p>👉 This is a <strong>protocol redesign</strong>, not just an upgrade.</p><h3>🔄 Flow Diagram</h3><pre>Client<br>  │<br>  ├─── Stream 1 ───────────────▶ Server<br>  ├─── Stream 2 ───────────────▶ Server<br>  ├─── Stream 3 ───────────────▶ Server<br>  │<br>  │◀──────── Independent Responses ───────▶</pre><h3>🔥 No Head-of-Line Blocking</h3><pre>Stream 1: [1][2][❌ lost][4]<br>Stream 2: [A][B][C][D]<br><br>👉 Stream 2 continues unaffected</pre><h3>⚡ Faster Connection Setup</h3><h3>HTTP/1.1 &amp; HTTP/2 (TCP)</h3><pre>TCP handshake → TLS handshake → Request</pre><h3>HTTP/3 (QUIC)</h3><pre>Handshake + TLS + Request (combined) → Immediate data transfer</pre><h3>📶 Built for Real-World Networks</h3><ul><li>Works better on unstable networks</li><li>Connection migration (WiFi → Mobile)</li><li>Lower latency in high-loss regions</li></ul><h3>🧠 Mental Model</h3><p>🚁 <strong>Independent flying drones</strong><br>No waiting. No traffic jams.</p><h3>📊 Side-by-Side Comparison</h3><p>FeatureHTTP/1.1HTTP/2HTTP/3ProtocolTextBinaryBinaryTransportTCPTCPQUIC (UDP)Multiplexing❌✅✅HOL Blocking❌⚠️ (TCP-level)❌Compression❌✅ (HPACK)✅ (QPACK)EncryptionOptionalOptionalMandatoryConnection SetupSlowFasterFastest</p><h3>🏗️ Real Engineering Insights</h3><h3>🧠 1. Backend Systems Reality</h3><ul><li><strong>HTTP/1.1</strong> → still used (simplicity, legacy)</li><li><strong>HTTP/2</strong> → dominant for microservices</li><li><strong>HTTP/3</strong> → growing for edge &amp; mobile</li></ul><h3>🧠 2. Why Industry Is Moving to HTTP/3</h3><p>Companies like Cloudflare and Google are adopting HTTP/3 because:</p><ul><li>Better performance in <strong>high latency regions</strong></li><li>Handles <strong>packet loss gracefully</strong></li><li>Improves <strong>real-world user experience</strong></li></ul><h3>🔄 Real-World Scenario: Payment Dashboard</h3><h3>HTTP/1.1</h3><pre>Login → Wait<br>Fetch Balance → Wait<br>Fetch Transactions → Wait<br>Fetch Charts → Wait</pre><p>👉 Slow UX</p><h3>HTTP/2</h3><pre>Login + Balance + Transactions + Charts<br>→ Parallel streams<br>→ Faster but may pause on packet loss</pre><h3>HTTP/3</h3><pre>All requests → Independent streams<br><br>Packet loss?<br>👉 Only one request affected<br>👉 Others continue smoothly</pre><h3>🧩 Final Takeaway</h3><p>👉 HTTP/1.1 → Works<br>👉 HTTP/2 → Optimizes request handling<br>👉 HTTP/3 → Fixes the transport layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXPa20CZp6pQt4RQe0h9pg.png" /></figure><h3>🧠 One-Line Summary</h3><blockquote><em>HTTP/3 is faster not because of HTTP — but because it replaces TCP with QUIC.</em></blockquote><h3>🚀 Closing Thought</h3><p>If you’re building:</p><ul><li>scalable APIs</li><li>microservices</li><li>global products</li></ul><p>👉 Understanding HTTP evolution is not optional — it’s a <strong>performance advantage</strong>gRPC vs REST benchmarks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5811be3114f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Copy-Paste Prompts to AI-Driven Architecture: How to Use Claude for Real Backend Systems]]></title>
            <link>https://medium.com/@samrat.alam/from-copy-paste-prompts-to-ai-driven-architecture-how-to-use-claude-for-real-backend-systems-83238fbcfc64?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/83238fbcfc64</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 05:12:58 GMT</pubDate>
            <atom:updated>2026-03-27T05:12:58.211Z</atom:updated>
            <content:encoded><![CDATA[<p>🚀 From Copy-Paste Prompts to AI-Driven Architecture: How to Use Claude for Real Backend Systems</p><p>Most developers use AI like Google.</p><p>👉 Ask a question<br>👉 Get an answer<br>👉 Copy-paste code</p><p>That works… until you try to build something real.</p><p>When I started working on Spring Boot, Kafka, and fintech systems, I realized something:</p><p><strong>AI is not a tool — it’s a team.</strong></p><p>And if you don’t structure it properly, it becomes a junior developer at best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*kdpDaq2K17VtfuwE.jpg" /></figure><h3>🧠 The Shift: From Prompts → Systems</h3><p>Using Claude AI effectively is not about “better wording”.</p><p>It’s about:</p><ul><li>Defining roles</li><li>Controlling outputs</li><li>Designing workflows</li></ul><p>Think of it like this:</p><p>❌ Bad approach</p><blockquote><em>“Generate payment service code”</em></blockquote><p>✅ Good approach</p><blockquote><em>“Act as a fintech architect and design an idempotent payment system with retry safety”</em></blockquote><h3>⚙️ Production Prompt Framework</h3><p>Use a structured format for every serious task:</p><pre>[ROLE]<br>Senior backend architect (fintech, distributed systems)<br><br>[CONTEXT]<br>Spring Boot + Kafka + PostgreSQL payment system<br><br>[TASK]<br>Design idempotent transaction processing<br><br>[CONSTRAINTS]<br>  - Handle duplicate requests<br>  - Ensure exactly-once semantics<br>  - Horizontally scalable<br><br>[OUTPUT]<br>  - Architecture<br>  - DB schema<br>  - API design<br>  - Failure scenarios<br>  - Code</pre><p>👉 This turns AI into a <strong>senior engineer, not a code generator</strong></p><h3>🔥 Ready-to-Use Prompt Library (Examples)</h3><h3>1. 🏦 Payment System (Idempotency + Retry)</h3><pre>You are a senior fintech backend engineer.<br><br>Design a payment processing system with:<br>  - Idempotency<br>  - Retry handling<br>  - Exactly-once processing<br><br>Tech:<br>  - Spring Boot<br>  - Kafka<br>  - PostgreSQL<br><br>Output:<br>  1. Architecture<br>  2. Sequence flow<br>  3. DB schema<br>  4. API contracts<br>  5. Failure handling<br>  6. Sample code</pre><h3>2. 📡 Kafka Event-Driven Architecture</h3><pre>Act as a distributed systems architect.<br><br>Design an event-driven system using Kafka for order processing.<br><br>Focus on:<br>  - Event schema design<br>  - Consumer idempotency<br>  - Retry + DLQ strategy<br>  - Partitioning strategy<br><br>Output:<br>  - Architecture diagram (text)<br>  - Topic design<br>  - Failure scenarios</pre><h3>3. 🔒 Concurrency &amp; Locking (Fintech Critical)</h3><pre>You are a database and concurrency expert.<br><br>Explain and implement:<br>  - Pessimistic locking<br>  - Optimistic locking<br>  - Deadlock handling<br><br>Context:<br>High-concurrency payment system<br><br>Output:<br>  - Concept explanation<br>  - When to use which<br>  - Spring Boot examples</pre><h3>4. 🧪 Code Review (Senior Level)</h3><pre>Act as a strict senior reviewer.<br><br>Review this Spring Boot code for:<br>  - Scalability issues<br>  - Concurrency bugs<br>  - Transaction problems<br><br>Provide:<br>  - Issues<br>  - Severity<br>  - Fix suggestions<br>  - Improved version</pre><h3>🧠 BMAD: Turning AI into a Team</h3><p>Instead of one prompt, Use a <strong>multi-step workflow (BMAD style)</strong>:</p><h3>Step 1 — Planner</h3><pre>Break down the system into components</pre><h3>Step 2 — Architect</h3><pre>Design high-level architecture</pre><h3>Step 3 — Builder</h3><pre>Generate production-ready code</pre><h3>Step 4 — Reviewer</h3><pre>Find flaws and improve design</pre><p>👉 This mimics a real engineering team.</p><h3>💻 Setup</h3><p>Here’s how to structure it:</p><h3>📁 Project AI Workflow</h3><pre>/ai-prompts<br>  ├── planner.md<br>  ├── architect.md<br>  ├── builder.md<br>  ├── reviewer.md</pre><h3>🧩 How I Use It</h3><ul><li>Load prompt templates</li><li>Run step-by-step prompts</li><li>Iterate like a real dev cycle</li></ul><h3>🔁 The Real Power: Iteration Loop</h3><p>After generating:</p><pre>1. Generate solution<br>2. Ask AI to critique it<br>3. Improve it</pre><p>Example:</p><pre>Review your previous design like a senior architect.<br>Find weaknesses and improve it.</pre><p>👉 This alone can 10x your output quality.</p><h3>🚫 Mistakes Most Developers Make</h3><ul><li>Vague prompts</li><li>No constraints</li><li>Asking everything in one shot</li><li>No output structure</li><li>No iteration</li></ul><h3>🏆 Final Thought</h3><p>If you’re working with Spring Boot, Kafka, or fintech systems:</p><p>👉 Start treating AI like:</p><ul><li>Architect</li><li>Developer</li><li>Reviewer</li></ul><p>Not just a chatbot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83238fbcfc64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Complexity Drills: Rules & Traps Every Programmer Must Know]]></title>
            <link>https://medium.com/@samrat.alam/time-complexity-drills-rules-traps-every-programmer-must-know-ddf20fc39d30?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf20fc39d30</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 05:29:45 GMT</pubDate>
            <atom:updated>2025-12-18T05:29:45.400Z</atom:updated>
            <content:encoded><![CDATA[<p>Time complexity is one of the trickiest topics for interviews — even experienced programmers sometimes overthink it. The problem? People mix <strong>mathematical reasoning</strong> with <strong>actual code execution</strong>, creating “phantom” complexities. Let’s break it down clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7HYZlqcJrfq-z6Hu.png" /></figure><h3>Part 1–10 Lightning Time Complexity Drills</h3><p>For each, <strong>guess TC first</strong>, then check the explanation.</p><h3>1️⃣ Single pointer forward</h3><pre>i = 0;<br>while (i &lt; n) i++;</pre><p><strong>TC:</strong> O(n)</p><ul><li>Linear, moves forward, no reset.</li></ul><h3>2️⃣ Two-pointer same speed</h3><pre>i = 0; j = 0;<br>while (i &lt; n) {<br>    i++; j++;<br>}</pre><p><strong>TC:</strong> O(n)</p><ul><li>Two pointers, one phase. Don’t multiply.</li></ul><h3>3️⃣ Two-pointer different speeds</h3><pre>i = 0; j = 0;<br>while (i &lt; n) {<br>    i++;<br>    j += 2;<br>}</pre><p><strong>TC:</strong> O(n)</p><ul><li>j += 2 is constant work; linear.</li></ul><h3>4️⃣ Sliding window</h3><pre>left = 0;<br>for (right = 0; right &lt; n; right++) {<br>    while (sum &gt; k) left++;<br>}</pre><p><strong>TC:</strong> O(n)</p><ul><li>The inner while loop seems nested, but the total left moves are ≤ n.</li></ul><h3>5️⃣ Reset trap</h3><pre>for (i = 0; i &lt; n; i++) {<br>    j = 0;<br>    while (j &lt; n) j++;<br>}</pre><p><strong>TC:</strong> O(n²)</p><ul><li>j resets every i → multiply.</li></ul><h3>6️⃣ Cycle traversal</h3><pre>slow = head; fast = head;<br>while (fast &amp;&amp; fast-&gt;next) {<br>    slow = slow-&gt;next;<br>    fast = fast-&gt;next-&gt;next;<br>}</pre><p><strong>TC:</strong> O(n)</p><ul><li>Fast may loop multiple times, but the total number of moves is ≤ 2n.</li></ul><h3>7️⃣ Nested linear (true O(n²))</h3><pre>for (i = 0; i &lt; n; i++)<br>    for (j = 0; j &lt; n; j++)<br>        doSomething();</pre><p><strong>TC:</strong> O(n²)</p><ul><li>Standard nested loops.</li></ul><h3>8️⃣ Amortized doubling</h3><pre>size = 1;<br>while (size &lt; n) size *= 2;</pre><p><strong>TC:</strong> O(log n)</p><ul><li>Exponential growth → logarithmic steps.</li></ul><h3>9️⃣ Pointer restart illusion</h3><pre>i = 0;<br>while (i &lt; n) {<br>    if (arr[i] % 2 == 0) i = 0;<br>    else i++;<br>}</pre><p><strong>TC:</strong> Could be O(n²)</p><ul><li>i may reset → multiply.</li></ul><h3>🔟 Hash visit once</h3><pre>visited = {};<br>cur = head;<br>while (!visited[cur]) {<br>    visited[cur] = true;<br>    cur = cur.next;<br>}</pre><p><strong>TC:</strong> O(n)</p><ul><li>Nodes visited ≤ n, even if in a cycle.</li></ul><h3>Part 2 — Traps</h3><h3>Trap 1 — Off-by-one</h3><pre>l = 0; r = n;<br>while (l &lt;= r) {<br>    mid = (l+r)/2;<br>}</pre><ul><li>Wrong r = n → may access out of bounds</li><li>Proper: r = n-1</li><li>TC: O(log n)</li></ul><h3>Trap 2 — Two pointers overlap</h3><pre>left = 0; right = n-1;<br>while (left &lt; right) {<br>    if (arr[left] + arr[right] &gt; target) right--;<br>    else left++;<br>}</pre><ul><li>TC: O(n), each pointer moves forward at most n steps</li><li><strong>Trap:</strong> Don’t assume nested loops → linear, not n²</li></ul><h3>Trap 3 — Binary search inside two pointers</h3><pre>for (i = 0; i &lt; n; i++) {<br>    j = binarySearch(i+1, n-1, arr[i]);<br>}</pre><ul><li>TC: O(n log n)</li><li>Inner binary search doesn’t multiply n² (log factor only)</li></ul><h3>Trap 4 — Multiple pointer phases</h3><ul><li>Multiple passes over the array:</li></ul><pre>i = 0; while (i &lt; n) i++;<br>j = 0; while (j &lt; n) j++;</pre><ul><li>TC: O(n + n) → O(2n) ~ O(n), <strong>not O(n²)</strong></li></ul><h3>Trap 5 — Fast pointer skip</h3><pre>i = 0; j = 0;<br>while (i &lt; n &amp;&amp; j &lt; n) {<br>    i += 2;<br>    j++;<br>}</pre><ul><li>Each pointer moves forward ≤ n → O(n)</li><li><strong>Trap:</strong> multiplying speeds mentally → wrong O(n²)</li></ul><p>✅ <strong>General lessons from these traps</strong></p><ol><li><strong>Pointer movement matters</strong>, not loop count.</li><li><strong>Reset inside loops</strong> = multiplication.</li><li><strong>Binary search inside loop</strong> = n log n, not n².</li><li><strong>Two-pointer “nested” loops</strong> are often linear.</li><li><strong>Amortized analysis</strong> handles “re-visits” like in cycles or sliding windows.</li></ol><h3>🔥 Time Complexity Cheat Sheet</h3><h3>1️⃣ Core Rules</h3><ol><li><strong>Total operations matter, not loops</strong></li></ol><ul><li>Count how many times the code executes, not how many loops exist.</li></ul><p><strong>2. Forward-only pointer → linear</strong></p><ul><li>Pointer moves forward, never resets → O(n)</li></ul><p><strong>3. Reset inside a loop = danger</strong></p><ul><li>Only triggers multiplication if it causes reprocessing.</li></ul><p><strong>4. Phases add, don’t multiply</strong></p><ul><li>Sequential loops → O(n + m), not O(n*m)</li></ul><p><strong>5. Constants don’t matter</strong></p><ul><li>2n, 3n → O(n)</li></ul><p><strong>6. Nested loops only multiply if ranges overlap</strong></p><ul><li>Inner loop must restart or process the full range per outer iteration.</li></ul><h3>Cheat Mental Checklist</h3><p>Before saying TC in interviews:</p><ol><li>Are loops nested in <strong>code</strong> or just in math?</li><li>Do any variables reset inside loops?</li><li>Can a node/element/pointer be processed <strong>unboundedly</strong>?</li><li>Are operations inside loops constant time?</li></ol><p>✅ If answers: No, No, No, Yes → O(n)</p><h3>Quick Examples to Remember</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*AppTEueBgPY5r1JV8h992Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf20fc39d30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Multi-Tenant (Database-per-Tenant) Architecture in Spring Boot, Hibernate, and Liquibase]]></title>
            <link>https://medium.com/@samrat.alam/dynamic-multi-tenant-database-per-tenant-architecture-in-spring-boot-hibernate-and-liquibase-82725474657c?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/82725474657c</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[tenants]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multitenancy]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 07:10:46 GMT</pubDate>
            <atom:updated>2025-12-06T07:30:56.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a SaaS application often requires multi-tenancy, where each tenant can have <strong>isolated data</strong>. In this guide, we’ll implement a <strong>database-per-tenant architecture</strong> using <strong>Spring Boot 4</strong>, <strong>Hibernate 7</strong>, and <strong>PostgreSQL</strong>, along with a <strong>master database for tenant metadata</strong>.</p><p>We’ll cover:</p><ul><li>Master database storing tenant metadata</li><li>Dynamic tenant connection provisioning</li><li>Hibernate 7 multi-tenancy</li><li>Liquibase migrations running automatically for:<br>- Master DB<br>- Every tenant on startup<br>- Newly created tenants</li></ul><p><strong>Check out the full demo project on GitHub:</strong> <a href="https://github.com/samratalamshanto/db-per-tenant-spring-boot-demo-application?utm_source=chatgpt.com"><strong>DB-per-Tenant Spring Boot Demo</strong></a></p><h3>Key Features 🚀</h3><ul><li><strong>Master &amp; Tenant Liquibase Support:</strong> Each DB has its own changelog applied automatically.</li><li><strong>Runtime Tenant Creation:</strong> Add new tenant databases on the fly with automatic migrations.</li><li><strong>Dynamic DataSource Routing:</strong> Queries are routed to the correct tenant DB using tenant identifiers.</li><li><strong>Strong Data Isolation:</strong> Each tenant has a dedicated database to prevent data leakage.</li><li><strong>Scalable &amp; Maintainable:</strong> Easy to add tenants and sync schema updates across all DBs.</li></ul><h3>Why Multi-Tenancy (Database-per-Tenant)?</h3><p>Multi-tenancy allows a <strong>single application instance to serve multiple tenants</strong>. The main approaches are:</p><ul><li><strong>Database-per-tenant</strong>: Each tenant has a separate Postgres database.</li><li><strong>Schema-per-tenant</strong>: Single DB, each tenant in a different schema.</li><li><strong>Table-per-tenant</strong>: Single DB, single schema, tenant_id column in all tables.</li></ul><p>We’ll focus on <strong>database-per-tenant</strong>, which provides the best isolation and scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*-Cd93tDAaYn3h3gh.png" /></figure><h3>Architecture Overview</h3><pre>           +-------------------+<br>           |   Master Database |<br>           |  (Tenant Metadata)|<br>           +--------+----------+<br>                    |<br>                    v<br>           +-------------------+<br>           |  Application      |<br>           |  (Spring Boot)    |<br>           +--------+----------+<br>                    |<br>        +-----------+-----------+<br>        |                       |<br>+-------------------+   +-------------------+<br>| Tenant DB #1      |   | Tenant DB #2      |<br>| (Liquibase schema)|   | (Liquibase schema)|<br>+-------------------+   +-------------------+</pre><h3>Components</h3><ol><li><strong>Master DB</strong></li></ol><ul><li>Stores tenant metadata (Tenant entity) like database name, schema, username, and password.</li></ul><p><strong>2. Tenant DBs</strong></p><ul><li>Each tenant gets its own Postgres database with isolated data.</li></ul><p><strong>3. Spring Boot + Hibernate</strong></p><ul><li>Master EMF(EntityManagerFactory) → manages Tenant entity, master configuration data</li></ul><pre>Client → Request → TenantFilter → MasterDB</pre><ul><li>Tenant EMF → manages per-tenant entities dynamically</li></ul><pre>Client → Request → TenantFilter → TenantResolver → TenantEntityManagerFactory → TenantDB</pre><h3>Spring Boot Project Setup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VIWtcBli7eSy1hujs2-YcA.png" /></figure><h3>Implementation Steps</h3><h3>Step 1: Master Database Configuration</h3><pre>@Configuration<br>@EnableJpaRepositories(<br>        basePackages = &quot;com.example.multi_tenant.master&quot;,<br>        entityManagerFactoryRef = &quot;masterEntityManagerFactory&quot;,<br>        transactionManagerRef = &quot;masterTransactionManager&quot;<br>)<br>@RequiredArgsConstructor<br>public class MasterDbConfig {<br>    private final MasterDbProperties masterDbProps;<br><br>    @Bean<br>    @Primary<br>    public DataSource masterDataSource() {<br>        return DataSourceBuilder.create()<br>                .url(https://medium.com/masterDbProps.getUrl())<br>                .username(masterDbProps.getUsername())<br>                .password(masterDbProps.getPassword())<br>                .build();<br>    }<br><br>    @Bean<br>    @Primary<br>    public LocalContainerEntityManagerFactoryBean masterEntityManagerFactory() {<br><br>        Map&lt;String, Object&gt; jpaProperties = new HashMap&lt;&gt;();<br><br>        jpaProperties.put(&quot;hibernate.show_sql&quot;, true);<br>        jpaProperties.put(&quot;hibernate.format_sql&quot;, true);<br><br>        // camelCase to Db snakeCase issue<br>        jpaProperties.put(&quot;hibernate.physical_naming_strategy&quot;, new CamelCaseToSnakeCaseStrategy());<br>        jpaProperties.put(&quot;hibernate.implicit_naming_strategy&quot;, new ImplicitNamingStrategyJpaCompliantImpl());<br><br>        var emf = new LocalContainerEntityManagerFactoryBean();<br>        emf.setDataSource(masterDataSource());<br>        emf.setPackagesToScan(&quot;com.example.multi_tenant.master&quot;);<br>        emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());<br>        emf.setJpaPropertyMap(jpaProperties);<br>        return emf;<br>    }<br><br>    @Bean<br>    @Primary<br>    public PlatformTransactionManager masterTransactionManager(<br>            @Qualifier(&quot;masterEntityManagerFactory&quot;) EntityManagerFactory emf<br>    ) {<br>        return new JpaTransactionManager(emf);<br>    }<br>}</pre><ul><li>Let’s represent MasterDbConfig beans and how they connect:</li></ul><pre>MasterDbProperties<br>        │<br>        ▼<br>  masterDataSource()  ────────────► JDBC Connection to Master DB<br>        │<br>        ▼<br>masterEntityManagerFactory() ─────► Scans entities in com.example.multi_tenant.master<br>        │<br>        ▼<br>  HibernateJpaVendorAdapter + JPA Properties<br>        │<br>        ▼<br>Repositories in com.example.multi_tenant.master<br>        │<br>        ▼<br>masterTransactionManager() ──────► Manages transactions for these repositories</pre><p><strong>Explanation flow:</strong></p><ol><li>MasterDbProperties provides Master DB credentials.</li><li>masterDataSource() builds a JDBC connection using these credentials.</li><li>masterEntityManagerFactory() uses the DataSource, scans entities, and configures Hibernate (with naming strategies, SQL logging).</li><li>JPA repositories depend on this EntityManagerFactory to perform DB operations.</li><li>masterTransactionManager() ensures all repository operations are transactional using the EntityManagerFactory.</li></ol><p>Summary:</p><ul><li><strong>Master DB setup</strong>:</li><li>DataSource – JDBC connection.</li><li>EntityManagerFactory – JPA/Hibernate bridge with naming strategies.</li><li>TransactionManager – Manages transactions for repository operations.</li><li>All beans are marked @Primary to distinguish them from potential tenant DB configurations in a multi-tenant architecture.</li><li>Naming strategies ensure Java field conventions don’t conflict with DB column conventions.dbName → db_name automatically for PostgreSQL.</li></ul><h3>Step 2: Tenant Database Configuration</h3><pre><br>@Configuration<br>@EnableJpaRepositories(<br>        basePackages = &quot;com.example.multi_tenant.tenant&quot;,<br>        entityManagerFactoryRef = &quot;tenantEntityManagerFactory&quot;,<br>        transactionManagerRef = &quot;tenantTransactionManager&quot;<br>)<br>public class TenantDbConfig {<br><br>    @Bean<br>    public LocalContainerEntityManagerFactoryBean tenantEntityManagerFactory(<br>            MultiTenantConnectionProvider connectionProvider,<br>            CurrentTenantIdentifierResolver tenantResolver<br>    ) {<br><br>        Map&lt;String, Object&gt; jpaProperties = new HashMap&lt;&gt;();<br>        jpaProperties.put(&quot;hibernate.show_sql&quot;, true);<br>        jpaProperties.put(&quot;hibernate.format_sql&quot;, true);<br>        jpaProperties.put(&quot;hibernate.multiTenancy&quot;, &quot;DATABASE&quot;);<br>        jpaProperties.put(&quot;hibernate.multi_tenant_connection_provider&quot;, connectionProvider);<br>        jpaProperties.put(&quot;hibernate.tenant_identifier_resolver&quot;, tenantResolver);<br><br>        // camelCase to Db snakeCase issue<br>        jpaProperties.put(&quot;hibernate.physical_naming_strategy&quot;, new CamelCaseToSnakeCaseStrategy());<br>        jpaProperties.put(&quot;hibernate.implicit_naming_strategy&quot;, new ImplicitNamingStrategyJpaCompliantImpl());<br><br><br>        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();<br>        emf.setPackagesToScan(&quot;com.example.multi_tenant.tenant&quot;);<br>        emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());<br>        emf.setJpaPropertyMap(jpaProperties);<br>        return emf;<br>    }<br><br>    @Bean<br>    public PlatformTransactionManager tenantTransactionManager(<br>            @Qualifier(&quot;tenantEntityManagerFactory&quot;) EntityManagerFactory emf<br>    ) {<br>        return new JpaTransactionManager(emf);<br>    }<br>}</pre><ol><li>@Configuration – Spring will manage this class as a configuration class.</li><li>@EnableJpaRepositories – Configures Spring Data JPA repositories:</li></ol><ul><li>basePackages → Only scan tenant DB repositories (tenant package) to avoid mixing with master DB repositories.</li><li>entityManagerFactoryRef → Links these repositories to tenantEntityManagerFactory.</li><li>transactionManagerRef → Links these repositories to tenantTransactionManager.</li></ul><h3>Why separate from DbConfig?</h3><blockquote><strong><em>Reason for separation:</em></strong><em><br> Master DB and tenant DBs are </em><strong><em>different databases</em></strong><em> in a multi-tenant architecture. Master stores metadata (tenant info), while tenant DBs store actual business data. We need separate </em><em>EntityManagerFactory and </em><em>TransactionManager so that Spring can manage them independently.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLWfliq2slV0c6TiFHbiyQ.png" /></figure><ul><li>If we combined them:</li><li>Spring would get confused about which DB to use for which repository.</li><li>Transactions could break across tenants.</li><li>Multi-tenancy would be impossible to manage cleanly.</li></ul><blockquote><em>In short: </em><strong><em>Master DB is static and global, tenant DBs are dynamic per user/organization.</em></strong><em> They need independent configuration for JPA to handle them correctly.</em></blockquote><h3>Step 3: Tenant Entity &amp; Repository</h3><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Entity<br>@Table(name = &quot;tenant_details&quot;)<br>@Builder<br>public class Tenant {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String tenantKey;<br>    private String dbName;<br>    private String schemaName;<br>    private String dbUserName;<br>    private String dbHashedPassword;<br><br>    @CreationTimestamp<br>    @Column(updatable = false)<br>    private LocalDateTime createdAt;<br>    @UpdateTimestamp<br>    private LocalDateTime updatedAt;<br><br>}</pre><h3>Step 4: Create Tenant at Runtime (Example)</h3><pre>curl -X POST \<br>  http://localhost:8090/api/v1/admin/tenants \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>        &quot;dbName&quot;: &quot;test_db_21&quot;,<br>        &quot;schemaName&quot;: &quot;test_schema&quot;,<br>        &quot;dbUserName&quot;: &quot;test_user_21&quot;,<br>        &quot;dbPassword&quot;: &quot;th3bsa!f2^3&quot;<br>      }&#39;</pre><p><strong>Sample Response</strong></p><pre>{<br>  &quot;id&quot;: 8,<br>  &quot;tenantKey&quot;: &quot;a625205b-6104-4ef4-9a0e-76f1f5978c39&quot;,<br>  &quot;dbName&quot;: &quot;test_db_21&quot;,<br>  &quot;schemaName&quot;: &quot;test_schema&quot;,<br>  &quot;dbUserName&quot;: &quot;test_user_21&quot;<br>}</pre><p><strong>Behind the scenes:</strong></p><ol><li>Tenant database is created dynamically.</li><li>Tenant-specific Liquibase changelog is applied.</li><li>Master DB stores tenant metadata.</li><li>Queries are routed to the correct tenant database automatically.</li></ol><h3>Step 5: Dynamic Multi-Tenant Connection Provider</h3><pre>@Slf4j<br>@Component<br>@RequiredArgsConstructor<br>public class DynamicDataSourceConnectionProvider implements MultiTenantConnectionProvider {<br>    private final DataSource defaultDataSource;<br>    private final TenantProviderService tenantProviderService;<br><br>    private final Map&lt;String, DataSource&gt; dataSourceCache = new ConcurrentHashMap&lt;&gt;();<br><br>    @Override<br>    public Connection getAnyConnection() throws SQLException {<br>        return defaultDataSource.getConnection();<br>    }<br><br>    @Override<br>    public void releaseAnyConnection(Connection connection) throws SQLException {<br>        connection.close();<br>    }<br><br>    @Override<br>    public Connection getConnection(Object tenantIdentifier) throws SQLException {<br>        DataSource dataSource = dataSourceCache.computeIfAbsent(<br>                tenantIdentifier.toString(),<br>                tenantProviderService::getOrCreate<br>        );<br>        return dataSource.getConnection();<br>    }<br><br>    @Override<br>    public void releaseConnection(Object tenantIdentifier, Connection connection) throws SQLException {<br>        connection.close(); // return to pool<br>    }<br><br>    @Override<br>    public boolean supportsAggressiveRelease() {<br>        return false;<br>    }<br><br>    @Override<br>    public boolean isUnwrappableAs(Class&lt;?&gt; unwrapType) {<br>        return false;<br>    }<br><br>    @Override<br>    public &lt;T&gt; T unwrap(Class&lt;T&gt; unwrapType) {<br>        return null;<br>    }<br><br>    public void clearCache(String tenantKey) {<br>        dataSourceCache.remove(tenantKey);<br>    }<br>}</pre><h3>Step 6: Tenant Filter (HTTP Interceptor)</h3><ul><li>Extracts X-Tenant-ID from requests</li><li>Sets ThreadLocal tenant identifier</li><li>Skips tenant filter for onboarding endpoints</li></ul><pre>@Component<br>public class TenantFilter extends OncePerRequestFilter {<br>    private static final String TENANT_HEADER = &quot;X-Tenant-ID&quot;;<br>    private static final String DEFAULT_TENANT = &quot;defaultTenant&quot;;<br><br>    private final AntPathMatcher pathMatcher = new AntPathMatcher();<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request,<br>                                    HttpServletResponse response,<br>                                    FilterChain filterChain<br>    ) throws ServletException, IOException {<br>        try {<br><br>            String tenant = request.getHeader(TENANT_HEADER);  //will parse from JWT token<br>            if (tenant == null || tenant.isEmpty()) {<br>                tenant = DEFAULT_TENANT;<br>            }<br><br>            MDC.put(&quot;tenantId&quot;, tenant);<br><br>            TenantIdentifierResolverImpl.setCurrentTenant(tenant);<br>            filterChain.doFilter(request, response);<br>        } finally {<br>            TenantIdentifierResolverImpl.clearCurrentTenant();<br>        }<br>    }<br><br>    @Override<br>    protected boolean shouldNotFilter(HttpServletRequest request) {<br>        // 1. Skip filter for tenant onboarding endpoints<br>        String path = request.getRequestURI();<br>        String[] skipPatterns = {&quot;/api/v1/admin/tenants/**&quot;};<br><br>        for (String pattern : skipPatterns) {<br>            if (pathMatcher.match(pattern, path)) {<br>                return true; // skip the filter<br>            }<br>        }<br><br>        // 2. If no tenant header exists → do not run filter<br>        String tenant = request.getHeader(TENANT_HEADER);<br>        return (tenant == null || tenant.isBlank());<br>    }<br>}</pre><h3>Step 7: Liquibase Migrations</h3><p><strong>Master DB:</strong> db.changelog-master.yaml → Creates tenant_details table.</p><p><strong>Tenant DB:</strong> db.changelog-tenant.yaml → Creates tenant-specific tables like product.</p><ul><li>New tenants run migrations automatically when created.</li><li>Existing tenants run migrations on app startup.</li></ul><h3>Step 8: Key Advantages</h3><ul><li><strong>Automated Master DB &amp; Tenant DB migrations</strong></li><li><strong>Consistent schemas across all tenants</strong></li><li><strong>Full isolation per tenant</strong></li><li><strong>Scalable &amp; maintainable for SaaS apps</strong></li></ul><h3>Challenges Faced</h3><p>Implementing a database-per-tenant architecture comes with its own set of hurdles. Here are the main challenges I encountered:</p><h4>1️⃣ All Queries Went to the Master Database</h4><ul><li>Initially, all JPA repository queries were hitting the <strong>master database</strong>, even for tenant-specific entities.</li><li>The root cause: Spring Boot, by default, picks the first EntityManagerFactory for all repositories. Since the master DB was marked @Primary, tenant entities were also routed there.</li><li><strong>Solution:</strong> I configured separate JPA repositories for master and tenant packages using @EnableJpaRepositories with distinct entityManagerFactoryRef and transactionManagerRef.</li><li>Master DB → com.example.multi_tenant.master</li><li>Tenant DB → com.example.multi_tenant.tenant</li><li>After this separation, tenant entity queries started going to the correct tenant databases.</li></ul><h4>2️⃣ Dynamic Database Switching</h4><ul><li>Routing requests dynamically to the correct tenant database was challenging.</li><li>Misconfigurations in CurrentTenantIdentifierResolver or MultiTenantConnectionProvider initially caused requests to hit the wrong DB.</li><li><strong>Solution:</strong> Implemented a robust dynamic switching mechanism ensuring each request resolves to the proper tenant database at runtime.</li></ul><h4>3️⃣ CamelCase to Snake_Case Mapping</h4><ul><li>Hibernate’s default naming strategy didn’t match the database column naming conventions.</li><li>Fields like createdAt were not automatically mapped to created_at in PostgreSQL.</li><li><strong>Solution:</strong> Introduced a custom CamelCaseToSnakeCaseStrategy for the physical naming strategy while keeping ImplicitNamingStrategyJpaCompliantImpl for implicit names.</li></ul><h4>4️⃣ Liquibase Synchronization</h4><ul><li>Ensuring both master and tenant DBs ran their respective changelogs correctly on startup required careful configuration.</li><li>Tenant DB changelogs had to apply dynamically for new tenants created at runtime.</li><li><strong>Solution:</strong> Configured separate Liquibase changelogs for master and tenant DBs and triggered migrations dynamically when creating new tenant databases.</li></ul><h3>Key Takeaways</h3><ul><li>Separate EMFs for master and tenant DBs</li><li>MultiTenantConnectionProvider + CurrentTenantIdentifierResolver for runtime switching</li><li>ThreadLocal ensures request-level tenant isolation</li><li>Use HikariCP per tenant for connection pooling</li><li>Naming strategies prevent DB column conflicts</li></ul><h3>Conclusion</h3><p>With this setup:</p><ul><li>Adding a new tenant requires only inserting metadata into the master DB.</li><li>Hibernate dynamically routes queries to the correct tenant database.</li><li>Fully compatible with Spring Boot 4, Hibernate 7, and PostgreSQL.</li></ul><p>This architecture provides <strong>scalability, isolation, and maintainability</strong>, perfect for SaaS applications with multiple clients.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82725474657c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Default Library Sorting in Java: List, Set, and Map]]></title>
            <link>https://medium.com/@samrat.alam/default-library-sorting-in-java-list-set-and-map-42e9f172d86b?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/42e9f172d86b</guid>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[comparison]]></category>
            <category><![CDATA[compare]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 09:57:25 GMT</pubDate>
            <atom:updated>2025-11-28T09:57:25.354Z</atom:updated>
            <content:encoded><![CDATA[<p>Sorting is one of the most common operations in programming. In Java, the standard library provides powerful, <strong>easy-to-use methods</strong> to sort collections.<br>This guide covers <strong>List, Set, and Map</strong>, with examples that are simple to understand and remember.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*GLMEfrSSOdgY4uCo.png" /></figure><h3>✅ 1️⃣ Sorting Lists</h3><p>Java provides built-in methods for sorting lists:</p><ul><li>Collections.sort(list) → ascending, natural order</li><li>list.sort(Comparator) → custom order</li><li>Collections.reverse(list) → reverses a list</li></ul><h3>Example: Sorting Integers</h3><pre>List&lt;Integer&gt; numbers = Arrays.asList(5, 1, 4, 2);<br><br>Collections.sort(numbers);  // Ascending<br>System.out.println(numbers); // [1, 2, 4, 5]<br><br>Collections.sort(numbers, Collections.reverseOrder());  // Descending<br>System.out.println(numbers); // [5, 4, 2, 1]</pre><h3>Example: Sorting Strings</h3><pre>List&lt;String&gt; fruits = Arrays.asList(&quot;Banana&quot;, &quot;Apple&quot;, &quot;Orange&quot;);<br><br>Collections.sort(fruits);<br>System.out.println(fruits); // [Apple, Banana, Orange]<br><br>fruits.sort(Comparator.comparingInt(String::length)); // Sort by length<br>System.out.println(fruits); // [Apple, Orange, Banana]</pre><h3>🔹 Tips for Custom Objects</h3><p>If your list contains objects, you can sort by:</p><ol><li><strong>Comparable (natural order)</strong></li></ol><pre>class User implements Comparable&lt;User&gt; {<br>    String name;<br>    int age;<br><br>    @Override<br>    public int compareTo(User other) {<br>        return Integer.compare(this.age, other.age); // Sort by age<br>    }<br>}</pre><pre>List&lt;User&gt; users = Arrays.asList(new User(&quot;Sam&quot;, 25), new User(&quot;Alex&quot;, 30));<br>Collections.sort(users);</pre><ol><li><strong>Comparator (custom order)</strong></li></ol><pre>users.sort(Comparator.comparing(User::getName));</pre><h3>✅ 2️⃣ Sorting Sets</h3><ul><li><strong>HashSet</strong> → unordered → cannot sort directly</li><li><strong>LinkedHashSet</strong> → preserves insertion order → convert to list to sort</li><li><strong>TreeSet</strong> → automatically sorted</li></ul><h3>Example: TreeSet (Natural Order)</h3><pre>Set&lt;Integer&gt; set = new TreeSet&lt;&gt;();<br>set.add(5);<br>set.add(2);<br>set.add(9);<br><br>System.out.println(set); // [2, 5, 9]</pre><h3>Example: HashSet → List → Sort</h3><pre>Set&lt;Integer&gt; set = new HashSet&lt;&gt;(Arrays.asList(5, 2, 9));<br><br>List&lt;Integer&gt; list = new ArrayList&lt;&gt;(set);<br><br>Collections.sort(list); // Ascending<br>Collections.sort(list, Collections.reverseOrder()); // Descending<br><br>System.out.println(list); // [2, 5, 9] or [9, 5, 2]</pre><h3>✅ 3️⃣ Sorting Maps</h3><p>Maps store <strong>key → value</strong> pairs. Sorting can be done <strong>by keys</strong> or <strong>by values</strong>.</p><h3>A) TreeMap → Keys Sorted Automatically</h3><pre>Map&lt;String, Integer&gt; map = new TreeMap&lt;&gt;();<br>map.put(&quot;Apple&quot;, 50);<br>map.put(&quot;Banana&quot;, 30);<br>map.put(&quot;Orange&quot;, 40);<br><br>System.out.println(map);<br>// {Apple=50, Banana=30, Orange=40} → keys sorted</pre><h3>B) HashMap → Sort by Keys</h3><pre>Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();<br>map.put(&quot;Apple&quot;, 50);<br>map.put(&quot;Banana&quot;, 30);<br>map.put(&quot;Orange&quot;, 40);<br><br><br>List&lt;String&gt; keys = new ArrayList&lt;&gt;(map.keySet());<br>Collections.sort(keys);<br><br>for (String key : keys) {<br>    System.out.println(key + &quot; = &quot; + map.get(key));<br>}</pre><h3>C) HashMap → Sort by Values</h3><pre>List&lt;Map.Entry&lt;String, Integer&gt;&gt; entries = new ArrayList&lt;&gt;(map.entrySet());<br><br>entries.sort(Map.Entry.comparingByValue()); //ascending<br><br>entries.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); //descending<br><br>for (Map.Entry&lt;String,Integer&gt; entry : entries) {<br>    System.out.println(entry.getKey() + &quot; = &quot; + entry.getValue());<br>}</pre><h3>🔹 Quick Visual Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1G3FMY1Nky4iNYoHxP-FTA.png" /></figure><h3>🧩 Sorting Custom Objects: Comparable vs Comparator</h3><p>When sorting <strong>custom objects</strong> (like User, Product, or Student), Java needs a way to <strong>know how to compare two objects</strong>. This is where <strong>Comparable</strong> and <strong>Comparator</strong> come in.</p><h3>1️⃣ Comparable → Natural Order</h3><ul><li>Implemented <strong>inside the class</strong></li><li>Defines the object’s <strong>default sorting order</strong></li><li>Method to implement:</li></ul><pre>public class User implements Comparable&lt;User&gt; {<br>    String name;<br>    int age;<br><br><br>    @Override<br>    public int compareTo(User other) {<br>        return Integer.compare(this.age, other.age); // Sort by age<br>    }<br>}</pre><h3>✅ Usage:</h3><pre>List&lt;User&gt; users = Arrays.asList(new User(&quot;Sam&quot;, 25), new User(&quot;Alex&quot;, 30));<br>Collections.sort(users);  // Uses compareTo</pre><h3>⚡ Notes:</h3><ul><li>Only <strong>one natural order per class</strong></li><li>Works with Collections.sort() and Arrays.sort()</li></ul><h3>2️⃣ Comparator → Custom Order</h3><ul><li><strong>Separate class</strong> or <strong>lambda</strong></li><li>Useful for multiple ways to sort the same object</li><li>Does <strong>not modify the class</strong> itself</li></ul><h3>Example: Sort by name</h3><pre>List&lt;User&gt; users = Arrays.asList(new User(&quot;Sam&quot;, 25), new User(&quot;Alex&quot;, 30));<br><br>users.sort(Comparator.comparing(User::getName));<br>System.out.println(users); // Alex, Sam</pre><h3>Example: Sort by age descending</h3><pre>users.sort(Comparator.comparing(User::getAge).reversed());</pre><h3>⚡ Notes:</h3><ul><li>Multiple comparators possible</li><li>Works even if the class doesn’t implement Comparable</li><li>Lambda expressions make it concise</li></ul><h3>🧠 Summary Tips</h3><ol><li><strong>List</strong> → use Collections.sort() or list.sort()</li><li><strong>Set</strong> → TreeSet or convert to List</li><li><strong>Map</strong> → TreeMap for key sorting, or entrySet/List for value sorting</li><li><strong>Custom objects</strong> → implement Comparable or use Comparator</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42e9f172d86b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering Java Collections: A Beginner-Friendly Guide to Time Complexities]]></title>
            <link>https://medium.com/@samrat.alam/mastering-java-collections-a-beginner-friendly-guide-to-time-complexities-e09b137554e2?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e09b137554e2</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 03:33:34 GMT</pubDate>
            <atom:updated>2025-11-28T03:33:34.119Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the performance of Java collections becomes extremely easy once you visualize <strong>how the data structure is built internally</strong>. In this guide, we break down all commonly used Java data structures using:</p><p>✅ Simple metaphors<br>✅ Real-world analogies<br>✅ Clear O(1) / O(n) / O(log n) explanations<br>✅ Small visual examples</p><p>Let’s begin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vswb-R_ndgZ2bSAb.png" /></figure><h3>✅ 1️⃣ ArrayList → “A long row of seats.”</h3><p>Internally, ArrayList uses a <strong>dynamic array</strong>.</p><p>Imagine a long fixed row of seats:</p><pre>[ seat0 ][ seat1 ][ seat2 ][ seat3 ] ...</pre><h3>✔ get(index) → O(1)</h3><p>Direct access. No walking.</p><pre>address = base + index * elementSize</pre><h3>✔ add(element) → O(1) (amortized), O(n) worst case</h3><p>If seats are available → new element sits immediately.</p><p>If the row is full → Java builds a <strong>bigger row</strong> and copies everyone:</p><pre>Old: [A B C]<br>New: [A B C _ _ _]</pre><p><strong>Copying takes O(n).</strong></p><h3>❌ remove(index) → O(n)</h3><p>Everyone to the right must shift left.</p><pre>[ A B C D E ]<br>      ↓ shift D, E left</pre><h3>❌ contains(x) → O(n)</h3><p>Must check seat-by-seat.</p><h3>Summary</h3><p>ArrayList is amazing for:</p><ul><li>Random access</li><li>Adding at the end</li></ul><p>Not good for:</p><ul><li>Removing in the middle</li><li>Searching large lists</li></ul><h3>✅ 2️⃣ LinkedList → “People holding hands in a line”</h3><p>Internally, LinkedList uses <strong>nodes connected by pointers</strong>.</p><pre>[A] → [B] → [C] → [D]</pre><h3>✔ addFirst() / addLast() → O(1)</h3><p>Change head/tail pointers — nobody needs to shift.</p><h3>✔ removeFirst() / removeLast() → O(1)</h3><p>Again, pointer manipulation.</p><h3>❌ get(index) → O(n)</h3><p>To reach the 50th person, you must walk 49 nodes.</p><h3>❌ contains(x) → O(n)</h3><p>Check each person one by one.</p><h3>Summary</h3><p>LinkedList is amazing for:</p><ul><li>Frequent add/remove at the beginning or end</li></ul><p>Not good for:</p><ul><li>Random access</li><li>Searching</li></ul><h3>✅ 3️⃣ HashSet → “Buckets based on hash code”</h3><p>HashSet organizes values into <strong>buckets</strong>, like:</p><pre>0:  [ ]<br>1:  [X]<br>2:  [ ]<br>3:  [Y]</pre><h3>✔ add(x) → O(1)</h3><p>Hash the value, then drop it into the bucket.</p><h3>✔ contains(x) → O(1)</h3><p>Go straight to its bucket — instant check.</p><h3>✔ remove(x) → O(1)</h3><p>Find bucket → remove element.</p><h3>❗ No ordering</h3><p>HashSet does not sort or preserve insertion order.</p><h3>Summary</h3><p>Great for:</p><ul><li>Fast membership checks</li><li>Unique values</li></ul><p>Not good for:</p><ul><li>Ordering</li></ul><h3>✅ 4️⃣ LinkedHashSet → “HashSet that remembers insertion order”</h3><p>Same buckets as HashSet, but also keeps a <strong>linked list of the insertion order</strong>.</p><pre>Insertion order: A → B → C</pre><p>Time complexities are still:</p><ul><li>add → O(1)</li><li>contains → O(1)</li><li>remove → O(1)</li></ul><p>But order is preserved.</p><h3>Summary</h3><p>Best when you need:</p><ul><li>Fast operations</li><li>But want the elements in the same order you inserted them</li></ul><h3>✅ 5️⃣ TreeSet → “A self-balancing sorted tree”</h3><p>TreeSet uses a <strong>Red-Black Tree</strong>, meaning it always stores elements sorted.</p><p>Example tree:</p><pre>        20<br>      /    \<br>     10    30<br>             \<br>             40</pre><h3>✔ add(x) → O(log n)</h3><p>Insert while comparing:</p><ul><li>If x &lt; root → go left</li><li>If x &gt; root → go right</li></ul><p>Tree may rebalance.</p><h3>✔ contains(x) → O(log n)</h3><p><strong>Binary search</strong> on the tree.</p><h3>✔ remove(x) → O(log n)</h3><p>Find node → <strong>adjust tree → rebalance</strong>.</p><h3>✔ Always sorted</h3><p>Sorting is automatic.</p><h3>Summary</h3><p>Best for:</p><ul><li>Sorted data without manual sorting</li><li>Range queries (e.g., elements between 10–20)</li></ul><h3>✅ 6️⃣ HashMap → “HashSet but key → value”</h3><p>Buckets again, but inside each bucket:</p><pre>Key → Value<br><br>HashMap: key → value pairs<br>Buckets:<br>0: []<br>1: [&quot;A&quot; → 100]<br>2: []<br>3: [&quot;C&quot; → 300]</pre><h3>✔ put(key, value) → O(1)</h3><h3>✔ get(key) → O(1)</h3><h3>✔ remove(key) → O(1)</h3><p>All instances are due to hashing.</p><h3>❗ Worst case O(n)**</h3><p><strong>If many keys are located in the same bucket. But rare. </strong>Then the HashMap looks like this:</p><pre>Bucket 0:  [ K1 → K2 → K3 → K4 → K5 → K6 → ... → Kn ]<br>Bucket 1:  [  ]<br>Bucket 2:  [  ]<br>Bucket 3:  [  ]<br>Bucket 4:  [  ]<br>Bucket 5:  [  ]</pre><p>Instead of being spread across 16 buckets, <strong>everything is inside ONE long chain</strong>. This chain used to be a <strong>LinkedList</strong> before Java 8.</p><p>In Java 8+, if the chain becomes too long → it becomes a <strong>Red-Black Tree </strong>→<strong>O(log n)</strong>. But the worst-case is still theoretical <strong>O(n)</strong>.</p><h3>Summary</h3><p>Best for:</p><ul><li>Fast lookups</li><li>Key-value mapping</li></ul><h3>✅ 7️⃣ LinkedHashMap → “HashMap + remember insertion order”</h3><p>Same speed as HashMap: O(1)</p><p>But keeps order:</p><pre>First Inserted → Second → Third</pre><p>Great for caches.</p><h3>✅ 8️⃣ TreeMap → “Sorted map using Red-Black Tree”</h3><p>Similar to TreeSet but for key/value pairs.</p><ul><li>put → O(log n)</li><li>get → O(log n)</li><li>remove → O(log n)</li></ul><p>And sorted by key.</p><h3>✅ 9️⃣ Stack → “Plates in a cafeteria (LIFO)”</h3><p>Operations:</p><ul><li>push → O(1)</li><li>pop → O(1)</li><li>peek → O(1)</li><li>search → O(n)</li></ul><p>Best for undo operations, recursion simulation, and expression parsing.</p><h3>✅ 🔟 Queue → “People waiting in a line (FIFO)”</h3><p>Using ArrayDeque (recommended):</p><ul><li>add → O(1)</li><li>remove → O(1)</li><li>peek → O(1)</li></ul><p>Great for BFS, background processing.</p><h3>✅ 1️⃣1️⃣ PriorityQueue → “Always keep smallest (or largest) on top”</h3><p>Uses a <strong>binary heap</strong>:</p><ul><li>add → O(log n)</li><li>remove → O(log n)</li><li>peek → O(1)</li></ul><p>Sorted by priority, but not fully sorted.</p><h3>🧠 The Final Memory Trick</h3><p>Ask only one question:</p><h3>“What is the internal structure?”</h3><ul><li><strong>Array?</strong><br> → Fast get, slow modifications</li><li><strong>Linked List?</strong><br> → Fast add/remove ends, slow searching</li><li><strong>Hash (Set/Map)?</strong><br> → Very fast everything (O(1))</li><li><strong>Tree (Set/Map)?</strong><br> → Sorted + O(log n)</li><li><strong>Heap?</strong><br> → Fast top element access</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e09b137554e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Redis in Spring Boot: Beyond Simple Key-Value Storage]]></title>
            <link>https://medium.com/@samrat.alam/mastering-redis-in-spring-boot-beyond-simple-key-value-storage-388c519154d6?source=rss-1f02e6b48bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/388c519154d6</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[key-value-pair]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samrat Alam]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 09:43:20 GMT</pubDate>
            <atom:updated>2025-11-27T09:43:20.435Z</atom:updated>
            <content:encoded><![CDATA[<p>Redis is more than just a key-value store — it’s a versatile, high-performance database supporting lists, sets, hashes, sorted sets, and Pub/Sub messaging. In this guide, we’ll explore how to leverage these features in a Spring Boot application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vUDQO5ymeKGdv4zH.png" /></figure><h3>✅ 1. Setting Up a Maven Project</h3><p>Create a Maven Spring Boot project with the following <strong>pom.xml</strong>:</p><pre>        &lt;!-- Spring Data Redis --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;!-- Lettuce Redis Client --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.lettuce.core&lt;/groupId&gt;<br>            &lt;artifactId&gt;lettuce-core&lt;/artifactId&gt;<br>            &lt;version&gt;6.2.0.RELEASE&lt;/version&gt;<br>        &lt;/dependency&gt;</pre><p><strong>application.yml</strong></p><pre>spring:<br>  redis:<br>    host: localhost<br>    port: 6379</pre><p>Configure RedisTemplate:</p><pre>@Bean<br>public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory factory) {<br>    RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();<br>    template.setConnectionFactory(factory);<br>    return template;<br>}</pre><h3>2️⃣ Key-Value Operations with TTL</h3><pre>redisTemplate.opsForValue().set(&quot;session:1234&quot;, &quot;active&quot;, 60, TimeUnit.SECONDS);<br>String sessionStatus = (String) redisTemplate.opsForValue().get(&quot;session:1234&quot;);</pre><h3>3️⃣ List Operations (taskList)</h3><p><strong>Add tasks:</strong></p><pre>redisTemplate.opsForList().rightPush(&quot;taskList&quot;, &quot;Design Module&quot;);<br>redisTemplate.opsForList().rightPush(&quot;taskList&quot;, &quot;Write Tests&quot;);</pre><p><strong>Read all tasks:</strong></p><pre>List&lt;Object&gt; allTasks = redisTemplate.opsForList().range(&quot;taskList&quot;, 0, -1);</pre><p><strong>Check if a task exists:</strong></p><pre>boolean exists = redisTemplate.opsForList().range(&quot;taskList&quot;, 0, -1).contains(&quot;Design Module&quot;);</pre><p><strong>Remove/Pop a specific task (any position):</strong></p><pre>// Remove first occurrence<br>redisTemplate.opsForList().remove(&quot;taskList&quot;, 1, &quot;Write Tests&quot;);<br><br>// Remove all occurrences<br>redisTemplate.opsForList().remove(&quot;taskList&quot;, 0, &quot;Design Module&quot;);<br><br><br>//Pop an element from the start:<br>String task = (String) redisTemplate.opsForList().leftPop(&quot;taskList&quot;);</pre><pre>/**<br> * Removes the first count occurrences of value from the list stored at key.<br> *<br> * @param key must not be null.<br> * @param count<br> * @param value<br> */<br>Long remove(K key, long count, Object value);<br><br><br>//Removes and returns first element in list stored at key.<br>V leftPop(K key);<br>//Removes and returns first elements in list stored at key.<br>List&lt;V&gt; leftPop(K key, long count);<br><br>//Removes and returns last element in list stored at key.<br>V rightPop(K key);<br>//Removes and returns last elements in list stored at key.<br>List&lt;V&gt; rightPop(K key, long count);</pre><p><strong>Explanation of the </strong><strong>count parameter:</strong></p><ul><li>count &gt; 0 → remove first count occurrences from <strong>head to tail</strong>.</li><li>count &lt; 0 → remove first abs(count) occurrences from <strong>tail to head</strong>.</li><li>count = 0 → remove <strong>all occurrences</strong>.</li></ul><p>This is perfect if you don’t want to pop from left or right.</p><h3>4️⃣ Set Operations (taskSet)</h3><p><strong>Add users/tasks to the set:</strong></p><pre>redisTemplate.opsForSet().add(&quot;taskSet&quot;, &quot;Design Module&quot;, &quot;Write Tests&quot;, &quot;Deploy App&quot;);</pre><p><strong>Get all members:</strong></p><pre>Set&lt;Object&gt; tasks = redisTemplate.opsForSet().members(&quot;taskSet&quot;);</pre><p><strong>Check if an element exists:</strong></p><pre>boolean exists = redisTemplate.opsForSet().isMember(&quot;taskSet&quot;, &quot;Write Tests&quot;);</pre><p><strong>Remove a specific element:</strong></p><pre>redisTemplate.opsForSet().remove(&quot;taskSet&quot;, &quot;Deploy App&quot;);</pre><h3>5️⃣ Hash Operations</h3><pre>redisTemplate.opsForHash().put(&quot;user:1001&quot;, &quot;name&quot;, &quot;Samrat&quot;);<br>redisTemplate.opsForHash().put(&quot;user:1001&quot;, &quot;age&quot;, &quot;20&quot;);<br><br><br>Object name = redisTemplate.opsForHash().get(&quot;user:1001&quot;, &quot;name&quot;);<br>Map&lt;Object, Object&gt; allFields = redisTemplate.opsForHash().entries(&quot;user:1001&quot;);</pre><h3>6️⃣ Sorted Sets (ZSet)</h3><p>A <strong>Sorted Set (ZSet)</strong> in Redis stores unique elements along with a <strong>score</strong>, and always keeps them sorted. Perfect for:</p><ul><li>Leaderboards</li><li>Priority queues</li><li>Task rankings</li><li>Expiring scores</li></ul><h3>Add Elements with Score</h3><p><strong>Use case: leaderboard sorting by points</strong></p><pre>redisTemplate.opsForZSet().add(&quot;leaderboard&quot;, &quot;Alice&quot;, 120.0);<br>redisTemplate.opsForZSet().add(&quot;leaderboard&quot;, &quot;Bob&quot;, 150.0);<br>redisTemplate.opsForZSet().add(&quot;leaderboard&quot;, &quot;Charlie&quot;, 90.0);</pre><h3>Update Score (Increment/Decrement)</h3><p><strong>Alice gained 10 more points</strong></p><pre>redisTemplate.opsForZSet().incrementScore(&quot;leaderboard&quot;, &quot;Alice&quot;, 10);</pre><p><strong>Decrease score (penalty):</strong></p><pre>redisTemplate.opsForZSet().incrementScore(&quot;leaderboard&quot;, &quot;Alice&quot;, -5);</pre><h3>Retrieve Sorted Data (Low → High)</h3><pre>Set&lt;Object&gt; ascending = redisTemplate.opsForZSet().range(&quot;leaderboard&quot;, 0, -1);</pre><h3>Retrieve Sorted Data (High → Low)</h3><p>This is the typical ranking use case.</p><pre>Set&lt;Object&gt; descending = redisTemplate.opsForZSet().reverseRange(&quot;leaderboard&quot;, 0, -1);</pre><h3>Get Top N Players (High → Low)</h3><p><strong>Top 3 players:</strong></p><pre>Set&lt;Object&gt; top3 = redisTemplate.opsForZSet().reverseRange(&quot;leaderboard&quot;, 0, 2);</pre><h3>Get Score of an Element</h3><pre>Double score = redisTemplate.opsForZSet().score(&quot;leaderboard&quot;, &quot;Bob&quot;);</pre><h3>Get Rank of an Element</h3><h4>Ascending rank (0 = lowest score)</h4><pre>Long rank = redisTemplate.opsForZSet().rank(&quot;leaderboard&quot;, &quot;Charlie&quot;);</pre><h4>Descending rank (0 = highest score)</h4><pre>Long reverseRank = redisTemplate.opsForZSet().reverseRank(&quot;leaderboard&quot;, &quot;Bob&quot;);</pre><h3>7️⃣ Pub/Sub Messaging</h3><p><strong>Publisher:</strong></p><pre>redisTemplate.convertAndSend(&quot;chat&quot;, &quot;Hello Redis!&quot;);</pre><p><strong>Subscriber:</strong></p><pre>@Component<br>public class RedisSubscriber implements MessageListener {<br>    @Override<br>    public void onMessage(Message message, byte[] pattern) {<br>        System.out.println(&quot;Received: &quot; + message.toString());<br>    }<br>}</pre><p><strong>Configuration:</strong></p><pre>@Bean<br>RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisSubscriber subscriber) {<br>    RedisMessageListenerContainer container = new RedisMessageListenerContainer();<br>    container.setConnectionFactory(factory);<br>    container.addMessageListener(subscriber, new ChannelTopic(&quot;chat&quot;));<br>    return container;<br>}</pre><p>Redis supports subscribing to <strong>multiple channels (topics)</strong>. You can do this in Spring Boot with RedisMessageListenerContainer. For example:</p><pre>@Bean<br>RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisSubscriber subscriber) {<br>    RedisMessageListenerContainer container = new RedisMessageListenerContainer();<br>    container.setConnectionFactory(factory);<br><br>    // Subscribe to multiple topics<br>    container.addMessageListener(subscriber, new ChannelTopic(&quot;chat&quot;));<br>    container.addMessageListener(subscriber, new ChannelTopic(&quot;notifications&quot;));<br>    container.addMessageListener(subscriber, new ChannelTopic(&quot;tasks&quot;));<br>    return container;<br>}</pre><p>The RedisSubscriber will receive messages from all these topics. You can differentiate inside onMessage:</p><pre>@Component<br>public class RedisSubscriber implements MessageListener {<br>    @Override<br>    public void onMessage(Message message, byte[] pattern) {<br>        String topic = new String(pattern); // the channel/topic<br>        String payload = message.toString();<br><br>        switch (topic) {<br>            case &quot;chat&quot;:<br>                handleChat(payload);<br>                break;<br>            case &quot;notifications&quot;:<br>                handleNotifications(payload);<br>                break;<br>            case &quot;tasks&quot;:<br>                handleTasks(payload);<br>                break;<br>        }<br>    }<br>}</pre><h3>8️⃣ Other Useful Operations</h3><ul><li><strong>Atomic counters:</strong></li></ul><pre>redisTemplate.opsForValue().increment(&quot;counter&quot;);<br>redisTemplate.opsForValue().decrement(&quot;counter&quot;);</pre><ul><li><strong>Check key existence:</strong></li></ul><pre>redisTemplate.hasKey(&quot;session:1234&quot;);</pre><ul><li><strong>Expire a key manually:</strong></li></ul><pre>redisTemplate.expire(&quot;session:1234&quot;, 120, TimeUnit.SECONDS);</pre><h3>Conclusion</h3><p>By using <strong>meaningful Redis keys</strong> like taskList and taskSet, and knowing how to <strong>check for existence</strong> and <strong>remove specific elements</strong>, you can build robust caching, task management, and real-time systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=388c519154d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>