<?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 Vikas Sengar on Medium]]></title>
        <description><![CDATA[Stories by Vikas Sengar on Medium]]></description>
        <link>https://medium.com/@vsengar?source=rss-397f5d56d41f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1YMLKEp8qaJNDh_7</url>
            <title>Stories by Vikas Sengar on Medium</title>
            <link>https://medium.com/@vsengar?source=rss-397f5d56d41f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:47:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vsengar/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[From Threads to Async: Choosing the Right Concurrency Model]]></title>
            <link>https://medium.com/@vsengar/from-threads-to-async-choosing-the-right-concurrency-model-868f4bfed555?source=rss-397f5d56d41f------2</link>
            <guid isPermaLink="false">https://medium.com/p/868f4bfed555</guid>
            <dc:creator><![CDATA[Vikas Sengar]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 12:14:59 GMT</pubDate>
            <atom:updated>2025-09-20T10:48:19.175Z</atom:updated>
            <content:encoded><![CDATA[<h2>Comparative Study of Threads and Async in Modern Concurrency</h2><p>This blog explores the evolution of concurrency models — from classic threading to modern async programming — helping developers decide which model best suits their applications.</p><h2>Threads to Async: A Deep Dive into Concurrency Models</h2><p>Concurrency is essential in modern software development. Whether you’re building a web server, a mobile app, or a data processing pipeline, your application needs to do many things at once — efficiently and correctly.</p><p>This post will walk you through:</p><ul><li>What concurrency is and why it matters</li><li>Traditional <strong>threads</strong>: pros, cons, and when to use them</li><li>The <strong>async/await</strong> paradigm: pros, cons, and use cases</li><li>How to choose the right model</li><li>A side-by-side comparison</li></ul><h2>What Is Concurrency?</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*uq0TTgdsSoTNn9TWEcSVFw.png" /></figure><p>Concurrency is the ability of a program to manage multiple tasks <strong>at the same time</strong>. It doesn’t necessarily mean they’re running simultaneously (parallelism), but rather that they’re making <strong>progress independently</strong></p><blockquote>Think of it as a chef preparing multiple dishes: chopping vegetables while a pot boils.</blockquote><h2>The Classic Approach: Threads</h2><h3>What Are Threads?</h3><p>A thread is the smallest unit of execution within a process. Most programming languages support <strong>multi-threading</strong>, allowing you to run code in parallel.</p><pre>new Thread(() -&gt; {<br>    System.out.println(&quot;Running in a thread&quot;);<br>}).start();</pre><h3>Pros</h3><ul><li>True parallelism on multi-core systems</li><li>Mature debugging and tooling support</li><li>Simple model (especially for CPU-bound tasks)</li></ul><h3>Cons</h3><ul><li>Heavy on memory (~1MB per thread)</li><li>Thread switching is costly</li><li>Risk of <strong>deadlocks</strong>, <strong>race conditions</strong>, and <strong>synchronization issues</strong></li></ul><h2>The Async/Await Revolution</h2><h3>What Is Async?</h3><p>Async programming enables <strong>non-blocking</strong> code execution. Instead of waiting (blocking) for a task to finish (e.g., I/O), the program continues executing and comes back when the task completes.</p><pre>async function fetchData() {<br>  const response = await fetch(&quot;https://api.example.com/data&quot;);<br>  const data = await response.json();<br>  console.log(data);<br>}</pre><h3>Pros</h3><ul><li>Efficient resource usage (ideal for I/O-heavy tasks)</li><li>Scales well under load (e.g., thousands of concurrent requests)</li><li>Lightweight compared to threads</li></ul><h3>Cons</h3><ul><li>Harder to debug (stack traces may be misleading)</li><li>Not ideal for CPU-bound tasks</li><li>Code can become “callback hell” if not structured well</li></ul><h2>Threads vs. Async: A Comparison</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*s02TcooRgzblCKs_cXJSaQ.png" /></figure><h3>Diagram: Concurrency Models at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5e2dBB-F387daOXumgFKvw.png" /></figure><h2>Under the Hood</h2><h3>Thread-Based Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJyi75wuQupfSgCcr4cc_g.png" /></figure><p>Each request is handled by a separate thread. Great for CPU tasks but can be memory-heavy.</p><h3>Async Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Mbzg3QFveXF4lgUCGCPi8w.png" /></figure><p>Single-threaded event loop handles many tasks using callbacks/promises/futures.</p><h2>Choosing the Right Model</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*zhh-yj4hTlyViYEv6_2KCA.png" /></figure><h2>Hybrid Approaches</h2><p>You don’t always have to pick one. Many modern frameworks (e.g., Python’s asyncio + ThreadPoolExecutor, or Java virtual threads) allow <strong>mixing models</strong>:</p><ul><li>Use <strong>threads</strong> for compute-heavy tasks</li><li>Use <strong>async</strong> for I/O operations</li></ul><pre># Python example: mixing threads and asyncio<br>loop = asyncio.get_event_loop()<br>result = await loop.run_in_executor(None, heavy_cpu_function)</pre><h2>Language Support Overview</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*c74aUrD9gJ3ldufzLXvokg.png" /></figure><h2>Final Thoughts</h2><p>Choosing the right concurrency model depends on:</p><ul><li>Your application’s workload (CPU vs. I/O)</li><li>Resource constraints</li><li>Developer expertise</li><li>Tooling/debugging needs</li></ul><blockquote>In modern apps, <strong>asynchronous I/O</strong> is a clear winner for scalability, while <strong>threads</strong> remain relevant for intensive computation.</blockquote><h2>Try It Yourself</h2><p>Explore concurrency using:</p><ul><li><a href="https://docs.python.org/3/library/asyncio.html">asyncio</a> in Python</li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html">CompletableFuture</a> or Virtual Threads in Java</li><li><a href="https://nodejs.dev/en/learn/the-nodejs-event-loop/">Node.js Async</a> in JavaScript</li></ul><h2>Further Reading</h2><ul><li><a href="https://docs.oracle.com/en/java/javase/21/">Thread vs Async in Java</a></li><li><a href="https://nodejs.dev/en/learn/the-nodejs-event-loop/">Node.js Event Loop</a></li><li><a href="https://realpython.com/async-io-python/">Python Concurrency Guide</a></li><li><a href="https://openjdk.org/projects/loom/">Project Loom — Java Virtual Threads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=868f4bfed555" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Sense of API Patterns: API Gateway, BFF, or GraphQL]]></title>
            <link>https://medium.com/@vsengar/api-gateway-vs-bff-vs-graphql-when-to-use-what-024ca5bbfa66?source=rss-397f5d56d41f------2</link>
            <guid isPermaLink="false">https://medium.com/p/024ca5bbfa66</guid>
            <dc:creator><![CDATA[Vikas Sengar]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 11:53:58 GMT</pubDate>
            <atom:updated>2025-09-20T10:51:58.515Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern application architectures, backend communication patterns are evolving rapidly. With diverse frontends (web, mobile, IoT, third-party clients) and distributed services, choosing the right integration layer is crucial.</p><p>Three common patterns are:</p><ul><li><strong>API Gateway</strong></li><li><strong>Backend for Frontend (BFF)</strong></li><li><strong>GraphQL</strong></li></ul><p>Each has unique advantages and trade-offs. Let’s explore them, compare their strengths, and see when to use which.</p><h2>1. API Gateway</h2><p>An <strong>API Gateway</strong> is a single entry point that sits between clients and microservices. It routes, aggregates, and transforms requests before forwarding them to backend services.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Routing client requests to the right microservice</li><li>Authentication &amp; authorization</li><li>Rate limiting &amp; throttling</li><li>Request/response transformation</li><li>Monitoring and logging</li></ul><p><strong>Diagram: API Gateway Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*RguYsZc-chxn9Wdk8BgXLA.png" /></figure><p><strong>When to Use:</strong></p><ul><li>Multiple microservices that need a single unified entry point</li><li>Need for centralized cross-cutting concerns (auth, logging, rate limiting)</li><li>Suitable for traditional REST-based systems</li></ul><h2>2. Backend for Frontend (BFF)</h2><p>A <strong>BFF</strong> is a pattern where each frontend application has its own dedicated backend service. Instead of having a generic gateway, each frontend (web, mobile, IoT) communicates with a tailored backend optimized for its needs.</p><p><strong>Key Responsibilities:</strong></p><ul><li>Simplify client logic by tailoring responses</li><li>Aggregate data from multiple services</li><li>Apply frontend-specific business logic</li></ul><p><strong>Diagram: BFF Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*MKIT8uFYO-nvKnFV6JEQ1A.png" /></figure><p><strong>When to Use:</strong></p><ul><li>Different clients (e.g., mobile vs web) require different payloads</li><li>Want to avoid over-fetching or under-fetching of data</li><li>Teams want to independently evolve frontend-specific backends</li></ul><h2>3. GraphQL</h2><p><strong>GraphQL</strong> is a query language and runtime for APIs. Instead of fixed endpoints, clients request exactly the data they need. The backend provides a schema, and the client queries against it.</p><p><strong>Key Benefits:</strong></p><ul><li>Flexible querying (clients decide the shape of data)</li><li>Reduces over-fetching and under-fetching</li><li>Strongly typed schema for better tooling and validation</li><li>Great for frontend-driven development</li></ul><p><strong>Diagram: GraphQL Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*zREAJUnGvOHJ3WOktgET4g.png" /></figure><p><strong>When to Use:</strong></p><ul><li>Multiple clients with varying data needs</li><li>Frontend teams want faster iteration</li><li>Complex data fetching across multiple microservices</li></ul><h2>4. Hybrid Approach</h2><p>In real-world systems, you often don’t choose <strong>only one</strong>. A <strong>hybrid approach</strong> combines these patterns:</p><ul><li><strong>API Gateway</strong> for centralized cross-cutting concerns</li><li><strong>BFFs</strong> for frontend-specific backends</li><li><strong>GraphQL</strong> as a query layer for flexible data fetching</li></ul><p><strong>Diagram: Hybrid Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*sLYIdRvJBiSoKZAhGqnkjQ.png" /></figure><h2>5. Comparison Table</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*O4n8t2JrwvdRXoCM19T9AA.png" /></figure><h2>6. Choosing the Right Approach</h2><ul><li>Use <strong>API Gateway</strong> when you need a <strong>single entry point</strong> for multiple services with centralized concerns.</li><li>Use <strong>BFF</strong> when <strong>different clients need different APIs</strong>, and you want to reduce frontend complexity.</li><li>Use <strong>GraphQL</strong> when <strong>flexibility and frontend-driven queries</strong> are a priority.</li><li>Use a <strong>Hybrid Approach</strong> for large-scale systems that need <strong>all three</strong>.</li></ul><h2>Conclusion</h2><p>There’s no one-size-fits-all solution. Your choice depends on:</p><ul><li>The complexity of your system</li><li>The diversity of your clients</li><li>The agility you want for frontend teams</li></ul><p>Most modern systems adopt a <strong>hybrid model</strong> — API Gateway for global concerns, BFFs for client-specific needs, and GraphQL for flexible queries.</p><p>By carefully selecting and combining these patterns, you can create scalable, flexible, and efficient architectures that support diverse frontend clients and evolving backend systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=024ca5bbfa66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Threads to Virtual Threads: Supercharging Java Servers]]></title>
            <link>https://medium.com/@vsengar/how-java-virtual-threads-are-revolutionizing-server-side-concurrency-800659e76a58?source=rss-397f5d56d41f------2</link>
            <guid isPermaLink="false">https://medium.com/p/800659e76a58</guid>
            <dc:creator><![CDATA[Vikas Sengar]]></dc:creator>
            <pubDate>Mon, 15 Sep 2025 11:39:23 GMT</pubDate>
            <atom:updated>2025-09-20T10:56:07.915Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, the software industry has seen an explosive demand for scalability, responsiveness, and efficiency in server-side applications. Traditional concurrency models in Java have long relied on platform (OS) threads, which are resource-intensive and difficult to manage at scale. But with <strong>Project Loom</strong> and the introduction of <strong>Virtual Threads</strong> in Java 21, things are about to change — <em>drastically</em>.</p><p>In this blog, we’ll explore <strong>how Java Virtual Threads work</strong>, why they’re such a <strong>game-changer for server-side concurrency</strong>, and how you can leverage them to build <strong>highly scalable and efficient applications</strong>.</p><h2>What Are Virtual Threads?</h2><p>Virtual Threads are lightweight threads managed by the Java Virtual Machine (JVM), not the underlying operating system. They’re part of the <strong>Project Loom</strong> initiative aimed at simplifying concurrency in Java.</p><p>They look and behave just like traditional threads but are far cheaper to create and manage. A single OS thread can run <strong>millions of virtual threads</strong> because they are <strong>scheduled and paused cooperatively</strong> by the JVM.</p><ul><li>Use the same java.lang.Thread API</li><li>Created using Thread.ofVirtual().start(...)</li><li>Designed for high-throughput concurrent applications</li><li>Non-blocking I/O becomes simpler and more intuitive</li></ul><h2>Traditional Threads vs Virtual Threads</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDRRSRH4I2sZrANTq1k5sw.png" /></figure><h2>Why Are Virtual Threads a Big Deal for Server-Side Apps?</h2><p>Server-side applications (like web servers, microservices, REST APIs) need to handle thousands — even millions — of concurrent requests. Traditional threading models are inefficient in these scenarios because:</p><ul><li>Each request is typically handled by a thread</li><li>Threads block on I/O (database calls, REST calls)</li><li>Context switching is expensive</li><li>Memory usage increases linearly with threads</li></ul><p><strong>Virtual Threads solve all of this</strong> by enabling <strong>cheap and abundant concurrency</strong>.</p><h3>Real-World Analogy</h3><p>Think of OS threads as physical workers. Hiring more means more desks, electricity, lunch, etc. Virtual threads are like gig workers in the cloud — summoned instantly, cost pennies, and disappear when done.</p><h2>Simplifying Concurrency: Goodbye Reactive, Hello Straightforward Code</h2><p>Before virtual threads, many developers turned to <strong>reactive programming (RxJava, Reactor, etc.)</strong> to overcome thread limitations. While reactive models are powerful, they’re also:</p><ul><li>Hard to learn</li><li>Difficult to debug</li><li>Prone to callback hell or broken stack traces</li></ul><p>Virtual Threads bring <strong>sequential programming back into style</strong> — you can write blocking-style code that scales like async!</p><pre>public void handleRequest() {<br>    var data = database.get(&quot;user123&quot;); <br>    var result = service.call(data);<br>    respond(result);<br>}</pre><p>With virtual threads, this blocking call is <strong>cheap and non-disruptive</strong>, as the JVM handles the suspension and resumption efficiently.</p><h2>Integration with Existing Frameworks</h2><ul><li><strong>Spring Boot (6.1+):</strong> Built-in support to run request handlers on virtual threads</li><li><strong>Tomcat, Jetty, Undertow:</strong> Support virtual threads with minor configuration changes</li><li><strong>JPA, Hibernate:</strong> Work seamlessly, since blocking DB calls no longer hurt performance</li></ul><h2>Structured Concurrency: Better Resource Management</h2><p>Another Project Loom feature is <strong>structured concurrency</strong>, which helps manage groups of threads as units. It improves:</p><ul><li><strong>Lifecycle management</strong></li><li><strong>Error propagation</strong></li><li><strong>Cancellation policies</strong></li></ul><pre>try (var scope = StructuredTaskScope.shutdownOnFailure()) {<br>    Future&lt;String&gt; user = scope.fork(() -&gt; fetchUser(id));<br>    Future&lt;List&lt;Order&gt;&gt; orders = scope.fork(() -&gt; fetchOrders(id));<br>    scope.join();<br>    scope.throwIfFailed();<br>    return merge(user.get(), orders.get());<br>}</pre><h2>Benchmark: Threads at Scale</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TyGoI2v0eWkQnBYBYmBkw.png" /></figure><h2>When Not to Use Virtual Threads</h2><ul><li><strong>CPU-bound tasks:</strong> Use thread pools with limited concurrency.</li><li><strong>Poorly written native code:</strong> If native libraries block OS threads, virtual threads don’t help.</li><li><strong>Custom ThreadLocal dependencies:</strong> Virtual threads reuse carriers, so ThreadLocal behavior may differ.</li></ul><h2>Final Thoughts</h2><p>Java Virtual Threads are <strong>revolutionizing server-side concurrency</strong> by combining the <strong>simplicity of synchronous code</strong> with the <strong>scalability of asynchronous models</strong>. They eliminate the need for complex frameworks or reactive programming in most cases.</p><p>This isn’t just an optimization — it’s a <strong>paradigm shift</strong>. If you’re building scalable Java applications, <strong>now is the time to experiment with virtual threads</strong>. With the maturity of Java 21 and ongoing enhancements from Project Loom, the future of high-concurrency server-side Java is <strong>brighter and simpler than ever</strong>.</p><h3>🚀 Try It Yourself</h3><pre>Runnable task = () -&gt; System.out.println(&quot;Running in virtual thread: &quot; + Thread.currentThread());<br>Thread.startVirtualThread(task);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800659e76a58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Guide to OWASP 2021: Top 10 Security Flaws for Developers]]></title>
            <link>https://medium.com/@vsengar/understanding-the-owasp-2021-top-10-security-vulnerabilities-every-developer-must-know-83e1d426d17e?source=rss-397f5d56d41f------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e1d426d17e</guid>
            <dc:creator><![CDATA[Vikas Sengar]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 06:02:16 GMT</pubDate>
            <atom:updated>2025-09-20T11:00:47.682Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>OWASP (Open Worldwide Application Security Project)</strong> is a nonprofit foundation focused on improving software security. Its flagship publication, the <strong>OWASP Top 10</strong>, outlines the ten most critical security risks to web applications. The 2021 edition reflects changes in technology, threat patterns, and real-world incidents.</p><h3>What are web applications?</h3><ul><li>Web applications (or web apps) are software programs that run on web servers and are accessed through web browsers.</li><li>Unlike traditional desktop applications, web apps do not need to be installed on users’ devices. Users interact with them over the internet.</li></ul><p><strong>Types:</strong></p><ol><li><strong>Static Web Apps:</strong></li></ol><ul><li>Fixed content (e.g., company websites).</li><li>No dynamic interactions.</li></ul><p><strong>2. Dynamic Web Apps:</strong></p><ul><li>Interactive and data-driven (e.g., social media platforms, e-commerce sites).</li><li>Use APIs, databases, and user authentication.</li></ul><p><strong>3. Single-Page Applications (SPAs):</strong></p><ul><li>Load once and dynamically update content (e.g., Gmail, Twitter).</li><li>Heavy use of JavaScript frameworks (e.g., React, Angular, Vue).</li></ul><h3>Importance of security in web applications</h3><ol><li><strong>Data Protection:</strong></li></ol><ul><li>Web applications handle sensitive user data (personal information, financial details, etc.).</li><li>Proper security measures prevent unauthorized access, data breaches, and identity theft.</li></ul><p><strong>2. User Trust and Reputation:</strong></p><ul><li>Secure apps build trust with users.</li><li>A breach can damage an organization’s reputation and lead to legal consequences.</li></ul><p><strong>3. Business Continuity:</strong></p><ul><li>Attacks (e.g., DDoS) can disrupt services, causing financial losses.</li><li>Security ensures uninterrupted operations.</li></ul><p><strong>4. Compliance and Regulations:</strong></p><ul><li>Many industries (finance, healthcare) have strict security requirements.</li><li>Compliance ensures legal adherence.</li></ul><p><strong>5. Preventing Exploits:</strong></p><ul><li>Vulnerabilities (e.g., SQL injection, XSS) can be exploited.</li><li>Security practices minimize risks.</li></ul><h3>Top 10 Security Vulnerabilities (2021):</h3><h3>1. Broken Access Control</h3><p><strong>Description:</strong> Inadequate restrictions allow attackers to act as users or admins, or access unauthorized resources.</p><p><strong>Example:</strong> User modifies a URL to access another user’s data: /accounts/456 → /accounts/457</p><p><strong>Prevention:</strong> Enforce access rules server-side. Use deny-by-default and proper access control mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*TQ59l1cyhFsP4M0ht0Jx2w.png" /></figure><h3>2. Cryptographic Failures</h3><p><strong>Description:</strong> Sensitive data isn’t properly encrypted or protected during storage or transit.</p><p><strong>Example:</strong> Passwords stored in plaintext or no TLS used for login forms.</p><p><strong>Prevention:</strong> Use HTTPS, encrypt sensitive data with strong algorithms, and manage keys securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*aotuJOVFhdtFplBKddW_ZA.png" /></figure><h3>3. Injection</h3><p><strong>Description:</strong> Untrusted input is interpreted as code by the application (e.g., SQL, LDAP, OS commands).</p><p><strong>Example:</strong> SQL Injection: &#39; OR &#39;1&#39;=&#39;1 bypasses authentication.</p><p><strong>Prevention:</strong> Use parameterized queries (e.g., PreparedStatement), input validation, and ORM libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YalLZw_flBX-Js27mertAA.png" /></figure><h3>4. Insecure Design</h3><p><strong>Description:</strong> Security is not considered at the design phase. Controls may be missing entirely, exposing fundamental flaws.</p><p><strong>Example:</strong> A banking app has no rate limiting on fund transfers, allowing brute-force attacks.</p><p><strong>Prevention:</strong></p><ul><li><strong>Rate Limiting:</strong> Implement rate limiting to restrict the number of requests an IP address can make in a certain time frame</li><li><strong>Threat Modeling:</strong> Identify and mitigate risks early.</li><li><strong>Security by Design:</strong> Incorporate best practices from the start.</li><li><strong>Server-Side Validation:</strong> Validate all critical actions.</li><li><strong>Business Risk Profiling:</strong> Assess security needs based on risks.</li><li><strong>Regular Reviews:</strong> Conduct frequent security audits.</li></ul><h3>5. Security Misconfiguration</h3><p><strong>Description:</strong> Default credentials, overly verbose error messages, or misconfigured cloud storage expose systems.</p><p><strong>Example:</strong> Publicly exposed admin panel or AWS S3 bucket.</p><p><strong>Prevention:</strong> Harden deployments, remove unnecessary features, and use secure configuration templates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*9Du9psri1Iqtxf-LtI0p_g.png" /></figure><h3>6. Vulnerable and Outdated Components</h3><p><strong>Description:</strong> Using outdated libraries or packages with known vulnerabilities opens your app to attacks.</p><p><strong>Example:</strong> A vulnerable version of Log4j is exploited for remote code execution.</p><p><strong>Prevention:</strong> Track dependencies, use software composition analysis tools, and patch regularly.</p><h3>7. Identification and Authentication Failures</h3><p><strong>Description:</strong> Weak authentication or session management lets attackers assume other users’ identities.</p><p><strong>Example:</strong> Poor password policy allows simple passwords like 123456, or session IDs are reused.</p><p><strong>Prevention:</strong> Implement MFA, use secure session handling, and enforce strong password policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*K0LnDfBjey0RsHxSQj3hvg.png" /></figure><h3>8. Software and Data Integrity Failures</h3><p><strong>Description:</strong> Failing to verify software integrity (e.g., unsigned updates or insecure CI/CD pipelines).</p><p><strong>Example:</strong> Application updates fetched from an unverified source are compromised.</p><p><strong>Prevention:</strong> Use signed packages, secure CI/CD practices, and integrity checks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BGhPkFdB3W88CINv8n1oQ.png" /></figure><h3>9. Security Logging and Monitoring Failures</h3><p><strong>Description:</strong> Lack of proper logging and alerting allows attackers to operate undetected.</p><p><strong>Example:</strong> No logs for failed login attempts or privilege escalation activities.</p><p><strong>Prevention:</strong> Log all critical events, protect logs from tampering, and monitor continuously.</p><h3>10. Server-Side Request Forgery (SSRF)</h3><p><strong>Description:</strong> Server is tricked into making unauthorized requests to internal systems or resources.</p><p><strong>Example:</strong> Attacker submits a request to http://169.254.169.254 (AWS metadata service).</p><p><strong>Prevention:</strong> Validate external URLs, block internal IPs, and enforce allow-lists for outbound requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wqJd2qbj-q92shVqJN6ww.png" /></figure><h3>OWASP Top 10 (2021) Summary Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*LvsK-wtGmU0D3yMgdfMO8g.png" /></figure><h3>Final Recommendations</h3><ul><li>Integrate security into each phase of the SDLC.</li><li>Conduct threat modeling early and regularly.</li><li>Automate security testing (SAST, DAST, dependency scanning).</li><li>Stay updated with latest OWASP guidance and security advisories.</li></ul><p><strong>Secure coding is not optional — it’s essential. Make it a habit, not an afterthought.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e1d426d17e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture Explained: A Guide for Developers]]></title>
            <link>https://medium.com/@vsengar/understanding-hexagonal-architecture-a-developers-guide-4716fcfcfbec?source=rss-397f5d56d41f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4716fcfcfbec</guid>
            <dc:creator><![CDATA[Vikas Sengar]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 05:34:39 GMT</pubDate>
            <atom:updated>2025-09-20T11:03:53.178Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving world of software development, architecture plays a crucial role in determining the effectiveness, scalability, and maintainability of applications. Among various architectural styles, <strong>Hexagonal Architecture</strong> — also known as <strong>Ports and Adapters</strong> — has garnered significant attention for its clean separation of concerns and adaptability.</p><p>Originally introduced by <strong>Alistair Cockburn</strong>, this architecture style helps build applications that are independent of frameworks, user interfaces, and external technologies like databases or APIs. This blog will explore the core components, benefits, and best practices of Hexagonal Architecture, with practical examples to help you apply it in your projects.</p><h3>What is Hexagonal Architecture?</h3><p>Hexagonal Architecture promotes an inside-out design where the <strong>business logic</strong> (or application core) is central, and all external interactions are plugged in via well-defined interfaces — <strong>ports</strong> — and their implementations — <strong>adapters</strong>.</p><p>Its key components:</p><ol><li><strong>Core Domain Logic</strong>: The heart of the application, containing all the business rules.</li><li><strong>Ports</strong>: Interfaces that define how the core communicates with the outside world.</li><li><strong>Adapters</strong>: Implementations of those ports, connecting the core to databases, UIs, REST APIs, message queues, etc.</li></ol><p>This design decouples the system, making it flexible, testable, and easier to evolve.</p><h3><strong>The Structure of Hexagonal Architecture</strong></h3><p>Imagine your application as a <strong>hexagon</strong>:</p><ul><li>At the center lies the <strong>core domain logic</strong>.</li><li>Surrounding it are <strong>ports</strong>, representing entry and exit points for communication.</li><li><strong>Inbound Ports</strong>: Define how external users or systems (like a REST API or CLI) invoke core logic.</li><li><strong>Outbound Ports</strong>: Define how the core interacts with infrastructure (like databases or external services).</li><li><strong>Adapters</strong> implement those ports, translating between external concerns and the core.</li></ul><p>This visual and structural metaphor emphasizes that there is <strong>no single fixed entry point</strong> — your application can expose multiple interfaces or evolve them independently.</p><p>The following illustration shows an exemplary application which</p><ol><li>is controlled by a user via a user interface,</li><li>is controlled by a user via a REST API,</li><li>is controlled by an external application via the same REST API,</li><li>controls a database and</li><li>controls an external application.</li></ol><p>(The numbering does not represent an order but references the arrows in the illustration).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hMn3bTYAlORcC4q2AJLMw.png" /></figure><p>The connection to the external components is provided by “adapters.”</p><p>For example, the user interface could provide a registration form. When the user has filled in all the data and clicks “Register,” the UI adapter generates a “Register User” command and sends it to the business logic. Alternatively, the same command could be generated by the REST adapter for a corresponding HTTP POST request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*RVd9SuGlEi_xzu2r.png" /></figure><p>On the “other side” of the application, the database adapter could translate the “Store User” command into an “INSERT INTO User VALUES (…)” SQL query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*TQADKyTaWu1ZdcRa.png" /></figure><p>How exactly the adapter does this — whether it uses an O/R mapper and which one and in which version — is irrelevant from the application core’s point of view.</p><p>Several adapters can be connected to one port. For example, as in the example above, a user interface adapter and a REST adapter can both be connected to the port to control the application. And a port for sending notifications could have an email adapter, an SMS adapter, and a WhatsApp adapter connected to it.</p><p>Incidentally, the term “port” refers to electrical connections to which any device that complies with the connection’s mechanical and electrical protocols can be connected.</p><h3>Practical Example: Bank Account Service</h3><p>Let’s consider a service that allows users to deposit and withdraw money.</p><h3>Domain Interface (Port)</h3><pre>public interface AccountUseCase {<br>    void deposit(String accountId, BigDecimal amount);<br>    void withdraw(String accountId, BigDecimal amount);<br>}</pre><h3>Domain Logic (Core)</h3><pre>public class AccountService implements AccountUseCase {<br>    private final AccountRepository repository;<br>public AccountService(AccountRepository repository) {<br>    this.repository = repository;<br>}</pre><pre>public void deposit(String accountId, BigDecimal amount) {<br>    Account acc = repository.find(accountId);<br>    acc.deposit(amount);<br>    repository.save(acc);<br>}</pre><pre>public void withdraw(String accountId, BigDecimal amount) {<br>    Account acc = repository.find(accountId);<br>    acc.withdraw(amount);<br>    repository.save(acc);<br>}</pre><pre>}</pre><h3>REST Adapter (Inbound)</h3><pre>@RestController<br>public class AccountController {<br>    private final AccountUseCase useCase;<br>public AccountController(AccountUseCase useCase) {<br>    this.useCase = useCase;<br>}</pre><pre>@PostMapping(&quot;/deposit&quot;)<br>public void deposit(@RequestBody DepositRequest req) {<br>    useCase.deposit(req.getAccountId(), req.getAmount());<br>}</pre><pre>}</pre><h3>JPA Adapter (Outbound)</h3><pre>@Repository<br>public class JpaAccountRepository implements AccountRepository {<br>    // DB operations<br>}</pre><p>Notice how the <strong>core doesn’t depend</strong> on Spring, HTTP, or JPA — it only knows the interface AccountRepository. That’s the power of Hexagonal Architecture.</p><h3>Benefits of Hexagonal Architecture</h3><ol><li><strong>Improved Testability</strong><br>You can test the business logic without needing a running database, web server, or framework.</li><li><strong>Enhanced Maintainability</strong><br>Changes in external systems (e.g., switching from REST to gRPC, or JPA to MongoDB) affect only the adapters.</li><li><strong>Clear Separation of Concerns</strong><br>The core domain logic is isolated and easier to reason about.</li><li><strong>Flexibility and Portability</strong><br>Easily add new interfaces (like GraphQL, CLI, or batch jobs) without touching the core.</li></ol><h3>Best Practices for Implementation</h3><ul><li><strong>Define Clear Ports</strong>: Think in terms of use cases and infrastructure responsibilities.</li><li><strong>Keep Core Logic Free of Dependencies</strong>: No framework, no annotations — just plain objects and logic.</li><li><strong>Use Dependency Injection</strong>: Let frameworks wire up the adapters at runtime.</li><li><strong>Favor TDD</strong>: Write tests around your ports to ensure logic correctness from day one.</li><li><strong>Document Roles Clearly</strong>: Make it easy for new developers to understand your architecture layout.</li></ul><h3>When to Use Hexagonal Architecture</h3><p>Hexagonal Architecture shines when:</p><ul><li>You’re working with <strong>complex domains</strong> or <strong>multiple interfaces</strong> (e.g., web, mobile, admin tools).</li><li>You want to <strong>future-proof</strong> your application against changing technology stacks.</li><li>You need <strong>clean separation</strong> between core logic and infrastructure.</li></ul><p>For simple CRUD apps, it might feel overkill — but for long-lived or critical systems, it’s a solid investment.</p><h3>Conclusion</h3><p>Hexagonal Architecture empowers developers to build robust, adaptable systems by placing the business logic at the center and keeping all technical concerns on the outside. By thinking in terms of ports and adapters, you gain flexibility, improved testing, and long-term maintainability.</p><p>As your applications grow, this approach helps you scale cleanly — without accumulating tight coupling and tech debt.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4716fcfcfbec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SIGTERM and SIGKILL in Java Tomcat-Based Applications with Kubernetes]]></title>
            <link>https://medium.com/@vsengar/understanding-sigterm-and-sigkill-in-java-tomcat-based-applications-with-kubernetes-ca6e5e4d0cdc?source=rss-397f5d56d41f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca6e5e4d0cdc</guid>
            <dc:creator><![CDATA[Vikas Sengar]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 05:19:35 GMT</pubDate>
            <atom:updated>2025-09-20T10:58:37.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Tomcat on Kubernetes: How SIGTERM and SIGKILL Affect Your Applications</h3><p>In production environments — especially when deploying <strong>Java Tomcat applications</strong> on <strong>Kubernetes</strong> — understanding how termination signals like SIGTERM and SIGKILL affect your pods is essential. These signals directly impact how gracefully (or abruptly) your applications shut down during scaling, rolling updates, or pod evictions.</p><p>When running Java web applications in production, especially with <strong>Apache Tomcat</strong> as the servlet container, it’s important to understand how your application behaves during shutdown. Two of the most critical Unix signals involved in process termination are SIGTERM and SIGKILL. They determine whether your app shuts down gracefully—or not at all.</p><h4>What Are SIGTERM and SIGKILL?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ov22tsum-wVD3nP9HnvzEA.png" /></figure><h4>SIGTERM: Graceful Attempt</h4><p>By default, kill PID sends SIGTERM. Processes can intercept it to:</p><ul><li>Close database pools</li><li>Flush logs</li><li>Complete in-progress work</li><li>Run shutdown hooks</li></ul><p>SIGTERM is the recommended method for application shutdown — giving code the opportunity to clean up</p><h4>SIGKILL: The Final Bolt</h4><p>SIGKILL immediately terminates the process at kernel level — no cleanup, no hooks, no mercy. This can lead to:</p><ul><li>Orphaned threads and child processes</li><li>Leaked connections</li><li>Uncommitted transactions and data corruption</li></ul><h4>Signal Flow in Tomcat</h4><p>When SIGTERM hits a Java process running Tomcat:</p><ol><li>JVM starts shutdown sequence</li><li>Tomcat stops accepting new requests</li><li>Inflight requests are served to completion</li><li>ServletContextListener and Spring @PreDestroy beans execute</li><li>Runtime.getRuntime().addShutdownHook() callbacks fire</li><li>JDBC pools close, background threads wind down</li></ol><p>If shutdown exceeds timeline or hook hangs, SIGKILL may follow.</p><h4>SIGTERM and SIGKILL in Docker &amp; Kubernetes</h4><p>Both Docker and Kubernetes leverage a two-phase termination:</p><h4>▪ Docker</h4><p>docker stop sends SIGTERM, waits 10s by default, then SIGKILL. Use --time to extend grace.</p><h4>▪ Kubernetes</h4><p>Kubernetes pod termination process:</p><ol><li>Pod marked “Terminating”</li><li>preStop hook executes</li><li>SIGTERM sent to PID 1</li><li>Waits terminationGracePeriodSeconds (default 30s)</li><li>If not shutdown, sends SIGKILL</li></ol><h4>How Kubernetes Handles Shutdown</h4><p>When a Kubernetes pod is terminated (due to a Deployment update, kubectl delete pod, or node drain), Kubernetes sends a <strong>SIGTERM</strong> to the main process in the container.</p><p>Here’s the default termination flow:</p><ol><li>Kubernetes sends SIGTERM to the container</li><li>Waits for <strong>terminationGracePeriodSeconds</strong> (default: 30s)</li><li>If the process hasn’t exited, it sends SIGKILL</li></ol><h4>Kubernetes YAML Example</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: tomcat-app<br>spec:<br>  replicas: 2<br>  template:<br>    spec:<br>      containers:<br>      - name: tomcat<br>        image: tomcat:10.1<br>        lifecycle:<br>          preStop:<br>            exec:<br>              command: [&quot;/bin/sh&quot;, &quot;-c&quot;, &quot;echo &#39;Shutting down...&#39; &amp;&amp; sleep 5&quot;]<br>      terminationGracePeriodSeconds: 30</pre><h4>How Your Java App Should Respond</h4><p>To handle SIGTERM properly inside Tomcat or Spring Boot, make sure to:</p><ul><li>Use Runtime.getRuntime().addShutdownHook() to release resources</li><li>Implement Spring’s DisposableBean or @PreDestroy</li><li>Configure a proper terminationGracePeriodSeconds to allow cleanup</li></ul><h4>Shutdown Hook Example</h4><pre>Runtime.getRuntime().addShutdownHook(new Thread(() -&gt; {<br>    System.out.println(&quot;Shutdown started...&quot;);<br>    myConnectionPool.close();<br>}));</pre><h4>Common Pitfall: SIGKILL Without Grace</h4><p>If your app takes too long to shut down or ignores SIGTERM, Kubernetes will escalate to SIGKILL, terminating the JVM instantly. This can cause:</p><ul><li>Lost database transactions</li><li>Unflushed logs</li><li>Orphaned threads or locks</li></ul><h4>Best Practices in Kubernetes for Java Tomcat Apps</h4><h4>1. Set Sufficient Grace Period</h4><pre>spec:<br>  terminationGracePeriodSeconds: 60</pre><h4>2. Use `preStop` Hooks</h4><p>These run before SIGTERM is sent and give you a chance to notify external services, deregister from load balancers, etc.</p><h4>3. Health Probes Matter</h4><p>Liveness and readiness probes control routing and can affect termination logic.</p><h4>Java &amp; Tomcat Best Practices</h4><ul><li>Register <strong>JVM shutdown hooks</strong>: Runtime.getRuntime().addShutdownHook(...)</li><li>Use Spring‘s @PreDestroy or DisposableBean</li><li>Clean up with ServletContextListener</li><li>Ensure all background threads are daemon or shutdown-aware</li><li>Ensure shutdown completes within grace period</li><li>Log receipt of SIGTERM and cleanup progress</li></ul><h4>Handling SIGKILL Scenarios</h4><p>If SIGKILL occurs you can’t catch it. Avoidable causes include:</p><ul><li>Missed grace period due to slow cleanup</li><li>OOMKill due to container memory limits</li><li>Unresponsive native code blocking threads</li></ul><p>Monitoring logs for “NEGSIGNAL.SIGKILL” or exit code 137 and tuning resource limits/grace periods helps avoid unexpected kills.</p><h4>Best Practice Summary</h4><ul><li>Use <strong>SIGTERM</strong> for graceful shutdowns.</li><li>Handle cleanup in hooks and listeners.</li><li>Configure sufficient grace time in Docker/K8s.</li><li>Use <strong>preStop</strong> hooks to signal external systems.</li><li>Monitor for <em>SIGKILL</em> events and investigate them.</li></ul><h4>Conclusion</h4><p>SIGTERM and SIGKILL are critical to understand when deploying Java Tomcat applications on Kubernetes. Always handle SIGTERM cleanly, test your shutdown logic, and configure Kubernetes appropriately to give your app enough time to clean up.</p><p>This results in more resilient deployments, fewer surprises during restarts, and better uptime across rolling updates and autoscaling.</p><h4>Key Takeaways</h4><ul><li><strong>SIGTERM:</strong> Sent by Kubernetes to trigger graceful shutdown</li><li><strong>SIGKILL:</strong> Sent if the pod doesn’t terminate in time</li><li><strong>Always handle shutdown in Java using hooks</strong></li><li><strong>Use Kubernetes lifecycle + grace periods to avoid SIGKILL</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca6e5e4d0cdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>