<?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 Ahmet Atar on Medium]]></title>
        <description><![CDATA[Stories by Ahmet Atar on Medium]]></description>
        <link>https://medium.com/@ahmtatar?source=rss-07bd34e7a417------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-35YPu8-6cBsX-J5Cc7D_A.jpeg</url>
            <title>Stories by Ahmet Atar on Medium</title>
            <link>https://medium.com/@ahmtatar?source=rss-07bd34e7a417------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:35:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmtatar/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[Which Came First: The Chicken or the Egg? Mysterious Entry Point of a Java Program]]></title>
            <link>https://medium.com/@ahmtatar/which-came-first-the-chicken-or-the-egg-mysterious-entry-point-of-a-java-program-8c1c9b153ecb?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c1c9b153ecb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Sat, 05 Jul 2025 19:57:41 GMT</pubDate>
            <atom:updated>2025-07-05T19:57:41.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpnVgwKc5ztqNYZHMRbJ0g.png" /></figure><blockquote><strong>Lean in and listen carefully: the code is already moving long before the first object draws breath.</strong></blockquote><h3>Why a “Chicken-and-Egg” Article About Java?</h3><p>Software is full of tempting loops. Your program must <em>run</em> to create objects, yet objects are the very things that <em>run</em> the program. Much like the old riddle of the chicken and the egg, we stand before a paradox:<strong> Who, or what, kicks off an object-oriented application when no objects exist yet?</strong></p><p>In Java, the riddle is resolved by the static universe, yet that solution seems to contradict the core ideas of Object-Oriented Programming (OOP) principles and practice. This essay unpacks this tension</p><ul><li>What Object-Oriented Programming really promises and why Java strongly commits to it..</li><li>How the stack, the heap, and the garbage collector manage how memory is used and shared in Java.</li><li>Why static <em>appears</em> to betray OOP, and why reality demands it.</li><li>Design patterns, best practices, and anti-patterns that revolve around static.</li><li>How the canonical main method embodies the chicken-and-egg paradox—and how modern frameworks soften its edge.</li></ul><p>Along the way we will weave in bit of code, history, and philosophy, ending exactly where we began, because circles are the most honest shape in computing.</p><h3>1. What Is OOP, Really? (And Why Should We Care?)</h3><h3>The Paradigm in a Paragraph</h3><p>Object-Oriented Programming treats software as a society of entities (objects) that carry state and behavior together. Each object:</p><ul><li><strong><em>Knows</em></strong><em> something</em> (its fields).</li><li><strong><em>Does</em></strong><em> something</em> (its methods).</li><li><strong><em>Hides</em></strong><em> something</em> (its implementation details).</li></ul><p>The benefit is cognitive: humans prefer to reason about “things that act” rather than acres of disembodied functions and data.</p><h3>A Lightning-Speed Historical Tour</h3><ul><li><strong>1960s — Simula 67</strong> introduces the <em>class</em>, the first powerful way to model real-world entities.</li><li><strong>1970s — Smalltalk</strong> popularizes pure messaging and dynamic dispatch.</li><li><strong>1990s — Java 1.0</strong> re-packs the OOP promise for the internet era: write once, run anywhere.</li></ul><p>By the late 2000s, OOP had become the <em>de facto</em> language of enterprise software, and Java positioned itself squarely at the center.</p><h3>Java’s “Everything Is an Object” Claim</h3><p>Aside from eight primitive value types (int, double, etc.), every value in Java lives on the heap as an instance of some class:</p><pre>String user = &quot;Ahmet&quot;;        // an object<br>int[] scores = {1, 2, 3};     // arrays are objects<br>Runnable r = () -&gt; {};        // lambdas compile to objects<br>Class&lt;?&gt; meta = String.class; // even classes are objects of type java.lang.Class</pre><p>This pervasiveness gifts us reflection, metaprogramming, serialization, and a dynamic linking model, yet it intensifies the paradox of startup.</p><blockquote>If everything is an object, who builds the first object?</blockquote><h3>Enter the Static Universe — A Necessary Contradiction</h3><h3><strong>What Does </strong>&quot;<strong>static&quot; Mean, Exactly?</strong></h3><ol><li><strong>Static variables</strong> live once per class loader.</li><li><strong>Static methods</strong> have no receiver object, they are “global functions” tucked inside a class.</li><li><strong>Static blocks</strong> run exactly one, at class initialization time.</li><li><strong>Static nested classes</strong> behave like top-level classes scoped for convenience.</li></ol><p>Java’s designers borrowed the keyword from C++ but used it to solve the chicken-egg problem:</p><blockquote>A program needs a place to start before any objects exist; that place is the static realm.</blockquote><h3>The Class-Initialization Cycle</h3><ol><li><strong>Loading</strong> — Bytecode is read into memory by a <em>class loader.</em></li><li><strong>Linking</strong> — The Java Virtual Machine (JVM) verifies and prepares fields.</li><li><strong>Initialization</strong> — Static variables are assigned default values, then any static initializers run.</li></ol><p>Only after these steps can you create the first instance of the class.</p><h3>main: The Hen That Lays the First Egg</h3><pre>public class Bootstrap {<br>    public static void main(String[] args) {<br>        Application.launch(Bootstrap.class, args);<br>    }<br>}</pre><ul><li>The JVM looks for public static void main(String[]) .</li><li><strong>No object is present yet</strong>, so an instance method would be impossible.</li><li>main often delegates instantly (to Spring’s SpringApplication.run , a JavaFX launcher, or a bespoke AppContext ). After that, regular OOP reigns.</li></ul><p>Think of main as the stagehand who flips on the house lights, then ducks behind the curtains.</p><h3>Design Patterns, and Anti-Patterns in Static Land</h3><h3>Singleton Method</h3><p>One instance, lazily or eagerly created.</p><pre>private static final Singleton INSTANCE = new Singleton();</pre><h3>Factory Method</h3><p>Centralizes construction logic without callers using new.</p><pre>public static Product of(String type)</pre><h3><strong>Utility / Helper Class</strong></h3><p>Pure functions; stateless; no reason to instantiate.</p><pre>java.util.Objects, <br>java.lang.Math<br>...</pre><h3><strong>Flyweight Cache</strong></h3><p>Reuses heavy objects across the JVM.</p><pre>private static final Map&lt;Key, Flyweight&gt; CACHE</pre><h3><strong>Beware anti-patterns</strong>:</h3><ul><li><strong>God Objects</strong>: A massive static class that “knows everything.”</li><li><strong>Hidden Global State</strong>: Mutable statics that sabotage test isolation.</li><li><strong>Tight Coupling</strong>: Static calls that can’t be mocked in unit tests.</li></ul><p>Modern practice favors <em>dependency injection</em> and <em>functional purity</em> to minimize such problems.</p><h3>Static Variables, Memory Model, and Concurrency</h3><h3>Immutability Is Your Friend</h3><pre>public static final Charset UTF8 = StandardCharsets.UTF_8;</pre><p>An immutable static constant is inherently thread-safe.</p><h3>Mutable Statics Demand Discipline</h3><p><em>Use at most one of the following strategies — never none:</em></p><ol><li><strong>Synchronization</strong>: Guard every read/write with synchronized or explicit locks.</li><li><strong>Volatile</strong>: Ensure visibility for simple reads/writes (double‐checked locking pattern).</li><li><strong>Atomic References</strong>: AtomicInteger, AtomicReference&lt;T&gt; for non-blocking updates.</li></ol><h3>Class Loaders and “Duplicate” Statics</h3><p>Every class loader gets its <em>own</em> copy of a static field. This allows:</p><ul><li><strong>Servlet containers</strong> to isolate web apps.</li><li><strong>Plugin architectures</strong> (OSGi, IntelliJ) to hot-swap modules.</li></ul><p>Misunderstanding this can lead to subtle bugs — e.g., two UI plugins both believing they hold <em>the</em> singleton instance.</p><h3>Reunifying the Worlds — Philosophy Meets Practice</h3><ol><li><strong>Objects embody behavior; statics enable existence.</strong></li><li><strong>Statics are blueprints, not bricks.</strong> You still build with objects.</li><li><strong>A perfect OOP system without static would require an external meta-language</strong> (think Erlang’s BEAM or Smalltalk’s image), which Java purposefully avoids for portability and simplicity.</li></ol><p>Hence, <em>static</em> is not a betrayal but a bridge — a short-lived scaffolding that lets the living organism of objects emerge.</p><h3>Best-Practice Checklist for Real-World Projects</h3><ul><li>Keep static state immutable or at least idempotent after startup.. — <em>Thread safety, testability, predictability.</em></li><li>Prefer dependency-injected singletons over public static variables. — <em>Easier to mock, swap, and scope.</em></li><li>Use static factories (of, valueOf, from) instead of telescoping constructors. —<em> Improves clarity and allows caching.</em></li><li>Reserve static methods for pure utilities or true bootstrapping logic. — <em>Avoids needless coupling.</em></li><li>Hide static helpers behind interfaces if you must mock them. — <em>Example: wrap </em>Math.random()<em> in a </em>RandomProvider<em> interface.</em></li><li>Avoid static initialization cycles (class A depends on class B which depends back on class A). —<em> Leads to</em> ExceptionInInitializerError.</li></ul><h3>Conclusion — Reconciling the Paradox</h3><p>The chicken-and-egg riddle that haunts Java’s entry point turns out not to be a contradiction, but a clarifying lens. We began with OOP’s promise: a world where everything meaningful is an object endowed with state, behavior, and identity. We then zoomed out to the stack and heap, revealing the physical stage on which those objects perform. From there, we met Java’s static realm — the scaffolding that must exist before any object can crack its shell.</p><p>Seen in that light, static is neither a loophole nor a sin against object-orientation. It is the hinge on which the language swings from inert bytecode to a living graph of instances. Used deliberately—immutably for constants, sparingly for utilities, and cautiously for shared state—static constructs let us bootstrap without abandoning our object-centric ideals. Misused, they mutate into hidden globals and brittle dependencies, reminding us that power in software, as in biology, is always double-edged.</p><p>The practical lesson is simple: embrace static as a <em>bridge</em>, not a <em>campground</em>. Let it lift your program off the ground, then quickly hand the baton to well-encapsulated objects, dependency-injected services, and clear behavioral contracts. In doing so you resolve the paradox rather than wrestle with it — and you keep the spirit of OOP intact while honoring the realities of the JVM.</p><p>So the next time you type public static void main(String[] args), remember you are standing at the exact moment where potential becomes action, where theory bows to practice, and where the age-old question of what comes first is finally answered: both, in their own time, and each because of the other.</p><blockquote><strong>Lean in and listen carefully: the code is already moving long before the first object draws breath.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c1c9b153ecb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Luggage, No Past, Just Payload: The Philosophy Behind Stateless APIs]]></title>
            <link>https://medium.com/@ahmtatar/no-luggage-no-past-just-payload-the-philosophy-behind-stateless-apis-5b680fae168d?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b680fae168d</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Fri, 09 May 2025 14:10:48 GMT</pubDate>
            <atom:updated>2025-05-13T18:55:11.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJhzTng8V1mzbhd3Ddagcg.png" /></figure><p>We often treat technical terms like labels on an unfamiliar bottle of wine. REST, for many developers, starts out as one of those labels — something abstract, intimidating, and strangely capitalized.<br> “RESTful APIs,” “stateless communication,” “resources and representations” — what do these even mean, really?</p><p>The truth is: REST is not just a way to expose data. It’s a design philosophy, a mindset — one that prioritizes clarity, consistency, and simplicity over stateful cleverness. The more you live with it, the more you realize REST isn’t just a protocol. It’s a way of letting go.</p><h3>From Words to Meaning: What Does REST Stand For?</h3><p>To begin with: REST stands for “REpresentational State Transfer”. Coined by Roy Fielding in his doctoral dissertation in 2000, the term isn’t just a catchy acronym — it describes a very specific architectural style for distributed systems like the world wide web.</p><p>Let’s break it down:</p><ul><li><strong>Representational</strong> → Instead of accessing a resource directly, the client interacts with a <em>representation</em> of it. Think of it like a photo: you don’t see the mountain, you see an image of the mountain.</li><li><strong>State</strong> → Refers to the current status or condition of the resource, or of the interaction.</li><li><strong>Transfer </strong>→ This state is transferred between client and server, primarily through HTTP requests and responses.</li></ul><p>But here’s the twist: despite the word “state” in its name, REST is built around the concept of <strong>statelessness</strong>.</p><p>That’s not a contradiction — it’s a design principle.</p><h3>Statelessness: The Gateway to RESTful Thinking</h3><p>In REST, <strong>statelessness</strong> means that <strong>each HTTP request is independent</strong>. The server doesn’t store any information about previous interactions. There is no implicit memory of “what came before.” Every request must contain <em>all the context necessary</em> to be understood and processed in an isolated way.</p><p>At first, this may sound inefficient. Isn’t remembering helpful? Isn’t context everything?</p><p>Not in distributed systems.</p><p>In fact, forgetting is power. Statelessness is what makes REST simple, <strong>scalable</strong>, and robust.</p><h3>Let’s Talk About Coffee</h3><p>Imagine a world where every time you walk into a coffee shop, the barista has amnesia. You can’t just say, “The usual.” You have to say, “Hi, my name is Alex. I’d like a large oat milk latte, extra hot, no foam. Here’s my loyalty card number.” Every. Single. Time.</p><p>Annoying? Maybe.</p><p>But from the barista’s perspective, it’s <strong>safe</strong>. They <strong>don’t need to keep track</strong> of your order history, worry about forgetting something, or manage a queue of who’s who. Every interaction is fresh and self-contained.</p><p>Now imagine that coffee shop has ten baristas. Because the process is stateless, <strong>any of them can help you at any time</strong>, without needing a shared memory or a central system. The moment your request comes in, it’s actionable.</p><p>That’s the beauty of REST.</p><h3>Why Should Backends Be Stateless?</h3><h3>1. Scalability</h3><p>In a stateless backend, every server can handle any request. That means you can horizontally scale your infrastructure — just add more instances. No sticky sessions. No shared session stores. No memory juggling.</p><h3>2. Resilience</h3><p>Since the server doesn’t store session data, there’s nothing to lose if one instance goes down. Another one can step in immediately. No broken sessions or orphaned data.</p><h3>3. Predictability and Simplicity</h3><p>Each request is like a small, sealed box: clear input, clear output. No hidden state means fewer bugs, easier debugging, and more understandable systems.</p><h3>So Where Does the State Go?</h3><p>If the server forgets, <strong>someone has to remember</strong>. That responsibility falls on the <strong>client</strong>.</p><p>The frontend — be it a web app, mobile app, or even another service — is in the best position to <strong>manage state</strong>. It knows the user’s interactions, preferences, progress, and tokens. It can use local storage, memory, or even URL parameters to maintain the user’s current status.</p><p>This separation of responsibilities leads to clean, maintainable systems:</p><ul><li>The <strong>client</strong> handles state and experience.</li><li>The <strong>server</strong> handles logic and data.</li></ul><p>Modern frontend frameworks like React, Vue, SwiftUI, or Jetpack Compose are designed around <strong>state-driven views</strong>. They embrace the idea of local state and manage it gracefully. Pair that with stateless APIs, and you get clear boundaries, fewer bugs, and happier teams.</p><h3>REST Best Practices Every Developer Should Know</h3><ol><li><strong>Use Nouns, Not Verbs in URIs</strong><br> Good: GET /users/123<br> Bad: GET /getUserById</li><li><strong>Embrace HTTP Methods Properly</strong></li></ol><ul><li>GET → Read a resource</li><li>POST → Create</li><li>PUT → Replace</li><li>PATCH → Partial update</li><li>DELETE → Remove or soft delete</li></ul><ol><li><strong>Use HTTP Status Codes Meaningfully</strong></li></ol><p>The most common HTTP Status Codes and their meanings are listed below, we should use them accordingly.</p><ul><li>200 OK</li><li>201 Created</li><li>204 No Content</li><li>400 Bad Request</li><li>401 Unauthorized</li><li>403 Forbidden</li><li>404 Not Found</li><li>405 Method Not Allowed</li><li>409 Conflict</li><li>429 Too Many Requests</li><li>500 Internal Server Error</li></ul><ol><li><strong>Keep URIs Predictable and Hierarchical</strong><br> Example: /users/123/orders/456</li><li><strong>Enable Caching Where Possible</strong><br> Use appropriate headers: Cache-Control, ETag, etc.</li><li><strong>Content Negotiation</strong><br> Let clients specify what they accept: Accept: application/json</li><li><strong>HATEOAS (Optional but Elegant)</strong><br> Include links in responses to guide clients on what they can do next.</li></ol><h3>Common REST Anti-Patterns</h3><ul><li><strong>Verbs in URIs</strong> (/getAllUsers)<br> REST is not RPC. Resources should be represented as nouns.</li><li><strong>Overloading POST for Everything</strong><br>It’s tempting, but using POST for all operations defeats the purpose of REST’s method semantics.</li><li><strong>Server-Side Session Tracking</strong><br>This violates statelessness and makes scaling harder.</li><li><strong>Ignoring Status Codes</strong><br>Returning 200 OK for errors or 404 NOT FOUNDfor successful responses confuses clients and makes debugging harder.</li><li><strong>Too Much Nesting in URIs</strong><br>Avoid URIs like /users/123/orders/456/items/789/comments/999. You’re not building a file system.</li></ul><h3>REST as a Manifesto, Not a Checklist</h3><p>Writing good RESTful APIs isn’t about following a rigid set of rules. It’s about developing an instinct for clarity. You start to notice when an endpoint is too tightly coupled or when your API exposes internal logic it shouldn’t.</p><p>REST encourages systems that are easy to understand, easy to debug, and easy to scale.</p><p>You don’t really learn REST by reading docs. You learn it by building, making mistakes, and slowly figuring out what feels right.</p><p>In the end, REST is about restraint. It asks your server to forget, your client to take responsibility, and your system to communicate clearly, without assumptions.</p><h3>In a World Without Memory…</h3><p>A RESTful API doesn’t carry baggage. Every request is a clean slate.</p><p>No history, no guessing — just payload.</p><p>And in a world that’s already complicated enough, that’s a welcome kind of simplicity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b680fae168d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Secret Shared Is No Secret: The Role of Asymmetric Cryptography in JWT Authentication]]></title>
            <link>https://medium.com/@ahmtatar/a-secret-shared-is-no-secret-the-role-of-asymmetric-cryptography-in-jwt-authentication-e78223b93036?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/e78223b93036</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[asymmetric-encryption]]></category>
            <category><![CDATA[json-web-token]]></category>
            <category><![CDATA[statelessness]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 13:21:50 GMT</pubDate>
            <atom:updated>2025-03-20T13:23:18.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nWMOz-VOdqzv1pbRdW3bGg.png" /></figure><h3>Introduction</h3><p>You may have encountered the old adage, “A secret shared is no secret.” Nowhere is this more applicable than in the realm of cybersecurity. When multiple parties rely on the same secret key to authenticate users or safeguard data, that key becomes a single point of failure, and each additional party that holds it increases the risk of a devastating breach.</p><p>This risk is particularly evident in systems that use symmetric encryption for JWT (JSON Web Token) authentication. While symmetric methods like HMAC are straightforward and efficient, they hinge on a single shared secret key — opening the door to potential leaks, unauthorized access, and other security concerns. As the threat landscape evolves, the industry is gradually shifting toward asymmetric cryptography, specifically RSA, to mitigate these vulnerabilities.</p><p>In this article, we will explore:</p><ol><li>How symmetric encryption underpins JWT authentication.</li><li>Why asymmetric cryptography (especially RSA) provides superior security guarantees.</li><li>The historical background of the RSA algorithm and the problems it was designed to solve.</li><li>Practical examples and recommended best practices for secure JWT-based authentication.</li></ol><p>Let us delve deeper into these topics.</p><h3>1. Understanding Symmetric Encryption in JWTs</h3><h3>What Is Symmetric Encryption?</h3><p>Symmetric encryption operates on the principle of a single shared key used both to encrypt and decrypt data. In the context of JWTs, a popular symmetric approach is HMAC (Hash-based Message Authentication Code). The workflow typically looks like this:</p><ol><li>The authentication server generates a JWT containing relevant user data (claims).</li><li>That JWT is signed using a pre-shared secret key.</li><li>The client receives the signed JWT and includes it with subsequent API requests.</li><li>The backend service verifies the JWT by recalculating the HMAC signature with the same secret key.</li></ol><h3>The Security Problem with Shared Secrets</h3><p>Although HMAC-signed JWTs offer simplicity and minimal performance overhead, they also pose substantial security liabilities:</p><ul><li><strong>Key Exposure:</strong> Each service responsible for verifying JWTs requires access to the same secret key. If this key is compromised, an attacker can forge arbitrary tokens, effectively impersonating legitimate users.</li><li><strong>Scalability Issues:</strong> In a microservices architecture, distributing and safeguarding a universal secret key across multiple services is cumbersome and risky.</li><li><strong>Complex Key Rotation:</strong> If the key is compromised or needs updating, you must propagate the new key to every service rapidly. Any delay can disrupt authentication, leading to potential downtime or vulnerabilities during the transition.</li></ul><p>These challenges underscore why many modern architectures are increasingly turning to asymmetric cryptography.</p><h3>2. The Power of Asymmetric Cryptography</h3><h3>How Asymmetric Encryption Works</h3><p>Asymmetric cryptography employs a <strong>pair</strong> of keys:</p><ul><li><strong>Private Key</strong> — Held exclusively by the authentication server (or an authorized key management system), used to sign JWTs.</li><li><strong>Public Key</strong> — Disseminated freely to services and clients, used solely to verify JWT signatures.</li></ul><h3>Why RSA Is More Secure</h3><p>In an RSA-based system, each party that verifies tokens only needs the <strong>public key</strong>. Since the sensitive operation — signing the token — occurs solely with the <strong>private key</strong>, which never leaves a secure location, the entire verification process becomes more robust and easier to scale. Essentially:</p><ol><li>Compromising the public key has no effect on the attacker’s ability to forge valid tokens, because they lack the private key.</li><li>Each microservice or third-party integration can hold its own copy of the public key without increasing the vulnerability footprint.</li><li>Key rotation is more straightforward, as only the private key needs to be replaced. The public key can be updated independently without requiring every single entity in the network to share a secret.</li></ol><h3>3. The Birth of RSA: Addressing the Shared Secret Problem</h3><h4>The Pre-RSA Era</h4><p>Before public-key cryptography, securing communication was a massive challenge. If two entities wanted to communicate privately, they needed a secure way to exchange a secret key. If that key was intercepted, every message became fair game for an attacker. As networks expanded, the logistical nightmare of keeping secret keys truly secret became apparent.</p><h4>How RSA Revolutionized Secure Communication</h4><p>In 1977, cryptographers <strong>Ron Rivest</strong>, <strong>Adi Shamir</strong>, and <strong>Leonard Adleman</strong> introduced what we now call RSA, building on the concept of public-key cryptography. Their innovation hinged on the mathematical difficulty of factoring large numbers:</p><ul><li><strong>Private Key</strong>: Carefully guarded and used to sign or decrypt data.</li><li><strong>Public Key</strong>: Freely shared yet mathematically infeasible to reverse-engineer back into the private key.</li></ul><p>This landmark discovery eliminated the necessity for every entity to share the same secret, forging the path for more resilient cryptographic systems — JWT authentication included.</p><h3>How RSA Transformed Secure Communication</h3><p>RSA capitalized on a simple yet profound mathematical property: factoring large prime numbers is computationally prohibitive. This discovery facilitated a cryptographic system where:</p><ol><li>The <strong>private key</strong> remains safeguarded by the key’s owner (for instance, your authentication server).</li><li>The <strong>public key</strong> can be openly shared, even published, without jeopardizing the security of the private key.</li></ol><p>This innovation eliminated the need for shared secrets altogether. Instead, a single party (the private key holder) can sign messages (or JWTs), and anyone with the public key can verify them. Attempting to reverse-engineer the private key from the public key is astronomically difficult due to the intractability of factoring large integers.</p><h3>4. Implementing RSA-Signed JWTs in a Real System</h3><h3>How RSA-Signed JWTs Work</h3><ol><li><strong>User Authentication</strong> — Upon logging in, the user is authenticated by the server (e.g., via username/password or another mechanism).</li><li><strong>Token Generation and Signing</strong> — The server constructs a JWT embedding necessary user details and signs it with its private RSA key.</li><li><strong>Token Transmission</strong> — The user receives this JWT and includes it in requests to any service requiring authentication.</li><li><strong>Verification</strong> — Each service checks the incoming JWT using the <strong>public RSA key</strong>.</li></ol><ul><li>If the signature is valid, the service trusts the embedded claims.</li><li>If the signature fails verification, the token is deemed invalid.</li></ul><h3>Benefits in Practice</h3><ul><li><strong>Reduced Attack Surface</strong> — Even if an attacker intercepts the public key, it is useless for forging valid tokens.</li><li><strong>Stateless and Scalable</strong> — Verification is stateless; any number of microservices can verify tokens without maintaining a shared secret or constantly querying a central database.</li><li><strong>Easier Revocation and Rotation</strong> — You can rotate your private key without simultaneously updating every service that verifies tokens.</li></ul><h3>5. Deciding When to Use RSA Over HMAC</h3><p>Although HMAC-signed tokens can be effective for smaller projects or less distributed environments, RSA-based solutions shine in the following scenarios:</p><ol><li><strong>Multiple Services or Microservices</strong>: If your architecture involves numerous services, each one only needs the public key to validate tokens, greatly reducing risk.</li><li><strong>High-Security Requirements</strong>: Applications dealing with finance, healthcare, or other confidential data usually benefit from the added security that comes with asymmetric cryptography.</li><li><strong>Simplified Key Management</strong>: Only the private key needs replacement if compromised; public verification keys can remain constant or be updated independently.</li><li><strong>Stateless Verification</strong>: Tokens can be verified autonomously, without referencing a central database for shared secrets.</li></ol><h3>6. Everyday Example: How RSA Protects You in Real Life</h3><h4>The Symmetric Scenario</h4><p>Picture a high-security facility where every guard carries a universal master key. If an unauthorized person steals just one guard’s key, they can access everything.</p><h4>The Asymmetric Alternative</h4><p>Now imagine everyone has a badge bearing a special seal that only the facility manager can produce. Guards use a simple device to check whether that seal is genuine:</p><ul><li>Even if someone acquires the device, they still can’t replicate the official seal.</li><li>The private key (or the seal’s “mold”) is safe with the manager, ensuring no one else can issue counterfeit badges.</li></ul><h3>Conclusion</h3><p>Although HMAC-signed JWTs are easy to implement and relatively fast, the shared-secret nature creates a single point of failure — particularly troublesome for distributed applications. By contrast, RSA-based JWT authentication ensures the sensitive private key remains locked down, allowing public verification by any number of services without multiplying security risks.</p><p>As the cybersecurity environment becomes ever more complex, adopting RSA-signed JWTs isn’t just a technical preference; it’s a strategic move toward fortifying user data and reducing the likelihood of catastrophic breaches. If you’re building or refactoring a modern, distributed system, asymmetric JWT authentication using RSA deserves a place at the top of your design priorities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e78223b93036" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Cost of Convenience: The Silent Punishment of the N+1 Problem]]></title>
            <link>https://medium.com/@ahmtatar/the-cost-of-convenience-the-silent-punishment-of-the-n-1-problem-d1f12a10da1a?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1f12a10da1a</guid>
            <category><![CDATA[n-plus-1-problem]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[object-relational-mapping]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 13:13:00 GMT</pubDate>
            <atom:updated>2025-02-27T13:17:00.988Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwSgTNyGlSGutK15aj-Xfg.png" /></figure><p>As backend developers, we love abstractions. Frameworks like <strong>Spring Data JPA</strong>, <strong>Spring Data MongoDB</strong>, and <strong>Spring Data Elasticsearch</strong> promise to make data access seamless, reducing boilerplate and allowing us to focus on business logic rather than writing verbose SQL queries.</p><p>However, <strong>every layer of abstraction comes with a cost</strong> — sometimes, a hidden performance penalty that only reveals itself in production under heavy load.</p><blockquote>All problems in computer science can be solved by another level of indirection, except for the problem of too many layers of indirection.” — David Wheeler</blockquote><p>One of the most notorious pitfalls of high-level ORM tools is the <strong>N+1 problem</strong>. It sneaks into our applications when we least expect it, quietly degrading performance and increasing database load. If left unchecked, it can turn a well-designed application into a performance bottleneck, frustrating users and causing unnecessary infrastructure costs.</p><p>In this article, we will explore:</p><ul><li>What the N+1 problem is and why it happens.</li><li>How it manifests in Spring Data JPA.</li><li>How to solve it using JOIN FETCH, Entity Graphs, and DTO projections.</li><li>Why high-performance applications (e.g., banking systems) often bypass ORMs.</li><li>When to embrace abstraction and when to go low-level for efficiency.</li></ul><h3>Understanding the N+1 Problem</h3><p>The N+1 problem occurs when an ORM issues one query to fetch the parent entity and then N additional queries to fetch related entities, instead of executing a single optimized join query.</p><p>This results in a dramatic increase in database calls, leading to performance degradation.</p><h3>Example: A Social Media Application</h3><p>Imagine we are building a social media platform where users can create posts and receive comments. We define the following JPA entities:</p><pre>@Entity<br>public class Post {<br><br>    @Id <br>    @GeneratedValue<br>    private Long id;<br>    <br>    private String title;<br>    @OneToMany(mappedBy = &quot;post&quot;, fetch = FetchType.LAZY)<br>    private List&lt;Comment&gt; comments;<br>}<br><br>@Entity<br>public class Comment {<br><br>    @Id <br>    @GeneratedValue<br>    private Long id;<br><br>    private String text;<br><br>    @ManyToOne<br>    @JoinColumn(name = &quot;post_id&quot;)<br>    private Post post;<br><br>}</pre><p>Now, let’s fetch all posts along with their comments:</p><pre>List&lt;Post&gt; posts = postRepository.findAll();<br>for (Post post : posts) {<br>    List&lt;Comment&gt; comments = post.getComments(); // Triggers an additional query for each post<br>}</pre><ul><li>If we have 100 posts, this results in 1 query for posts + 100 separate queries for comments → 101 queries instead of just 1 efficient JOIN query!</li><li>This happens because Spring Data JPA defaults to lazy loading (FetchType.LAZY), meaning related entities are only loaded when accessed.</li></ul><h3>How to Fix It? Solutions to the N+1 Problem</h3><h3>1. Using JOIN FETCH to Reduce Queries</h3><p>We can <strong>fetch all posts along with their comments</strong> in a <strong>single query</strong> using JOIN FETCH:</p><pre>@Query(&quot;SELECT p FROM Post p JOIN FETCH p.comments&quot;)<br>List&lt;Post&gt; findAllWithComments();</pre><p><strong>Pros:</strong></p><ul><li>Simple and works well for small datasets.</li></ul><p><strong>Cons:</strong></p><ul><li><strong>Over-fetching:</strong> Loads all comments, even if we only need post titles.</li><li><strong>Doesn’t scale well</strong> for complex joins (e.g., fetching posts, comments, and likes).</li></ul><h3>2. Using Entity Graphs (Better than JOIN FETCH)</h3><p>Instead of hardcoding fetch behavior in queries, <strong>JPA Entity Graphs</strong> allow us to specify <strong>which relationships should be eagerly loaded dynamically</strong>.</p><pre>@EntityGraph(attributePaths = {&quot;comments&quot;})<br>@Query(&quot;SELECT p FROM Post p&quot;)<br>List&lt;Post&gt; findAllWithComments();</pre><p><strong>Pros:</strong></p><ul><li>More flexible than JOIN FETCH, allowing different fetch plans dynamically.</li><li>Avoids query duplication.</li></ul><p><strong>Cons:</strong></p><ul><li>Slightly more complex syntax.</li></ul><h3>3. Using DTO Projections (Best for Large Data)</h3><p>If we only need <strong>post titles and comment texts</strong>, we should fetch <strong>only required fields</strong> instead of loading entire entities.</p><h4>Define DTO interfaces:</h4><pre>public interface PostWithCommentsDTO {<br>    String getTitle();<br>    List&lt;CommentDTO&gt; getComments();<br>}<br><br>public interface CommentDTO {<br>    String getText();<br>}</pre><h4>Modify Repository Query:</h4><pre>@Query(&quot;SELECT p FROM Post p JOIN FETCH p.comments&quot;)<br>List&lt;PostWithCommentsDTO&gt; findAllWithCommentSummaries();</pre><p><strong>Pros:</strong></p><ul><li>Best for large datasets (fetches only needed data).</li><li>No risk of OutOfMemoryErrors from unnecessary entity loading.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires defining DTOs manually.</li></ul><h3>Why ORMs Are Risky for High-Performance Applications (e.g., Banking Systems)</h3><p>While ORMs are great for rapid development, they introduce hidden performance issues in high-traffic financial systems.</p><h4>Example: Fetching Customer Transactions in a Banking App</h4><pre>@Query(&quot;SELECT c FROM Customer c JOIN FETCH c.accounts a JOIN FETCH a.transactions&quot;)<br>List&lt;Customer&gt; findAllWithAccountsAndTransactions();</pre><p><strong>Why is this risky?</strong></p><ul><li>Loads excessive data into memory → OutOfMemoryErrors.</li><li>Increases lock contention on the database, slowing transactions.</li><li>Causes transactional inconsistencies under heavy load.</li></ul><h3>What is MyBatis and How Does It Differ from ORMs?</h3><p>MyBatis is a persistence framework that provides greater control over SQL queries while still offering some abstraction for database interaction. Unlike ORMs like Hibernate, which map Java objects to database tables and handle query generation automatically, MyBatis requires developers to write SQL queries manually but allows for dynamic query generation and result mapping.</p><h4>Why Use MyBatis?</h4><ul><li><strong>Fine-grained SQL control</strong> — Developers write optimized SQL, avoiding ORM overhead.</li><li><strong>Better performance for complex queries</strong> — Especially useful in high-load applications like banking systems.</li><li><strong>Explicit transaction management</strong> — More predictable behavior in multi-threaded environments.</li><li><strong>Flexible mapping</strong> — Maps SQL query results directly to Java objects, reducing unnecessary entity management overhead.</li></ul><h4>Similar Low-Level Tools</h4><ul><li><strong>JDBC (Java Database Connectivity):</strong> The lowest-level approach, requiring fully manual SQL handling and connection management.</li><li><strong>jOOQ (Java Object-Oriented Querying):</strong> A type-safe query builder that provides SQL control while reducing boilerplate.</li><li><strong>Spring JDBC Template:</strong> A simplified JDBC API for managing connections and queries efficiently without full ORM overhead.</li></ul><p>These tools are often preferred when performance, transaction control, and query optimization are top priorities over development speed and abstraction.</p><h3>Why Banks Prefer Low-Level SQL Like MyBatis</h3><p>Unlike social media platforms, banks prioritize strict control over performance &amp; transactions.</p><h3>Optimized MyBatis Query Example:</h3><pre>&lt;select id=&quot;findTransactionsByCustomerId&quot; resultMap=&quot;TransactionResultMap&quot;&gt;<br>    SELECT t.id, t.amount, t.timestamp, a.account_number<br>    FROM transactions t<br>    JOIN accounts a ON t.account_id = a.id<br>    WHERE a.customer_id = #{customerId}<br>&lt;/select&gt;</pre><p><strong>Benefits of MyBatis &amp; Native Queries</strong>:</p><ul><li>Only fetches necessary data</li><li>Explicit transaction control (better consistency)</li><li>Fine-tuned SQL performance</li></ul><h3>When to Use Spring Data JPA vs. MyBatis/Native Queries?</h3><p>There is no one-size-fits-all solution when it comes to database access. While Spring Data JPA offers convenience and rapid development, MyBatis and native SQL provide more control and performance optimizations. The choice depends on the specific needs of your application.</p><h4>Use Spring Data JPA when:</h4><p>✔ You are working with simple CRUD operations.<br>✔ Rapid development and maintainability are priorities.<br>✔ The system is read-heavy and can tolerate some ORM overhead.<br>✔ You don’t need full control over transactions and locking mechanisms.<br>✔ You want to leverage Spring’s built-in pagination and query abstraction.</p><h4>Use MyBatis or Native SQL when:</h4><p>✔ You need fine-grained control over SQL execution and performance.<br>✔ The system is write-heavy and requires strict consistency guarantees.<br>✔ Complex queries with multiple joins and aggregations are required.<br>✔ Performance is critical, and ORM-generated queries are inefficient.<br>✔ Explicit transaction and locking control are necessary to prevent deadlocks.<br>✔ Batch processing or bulk insert/update operations need to be optimized.</p><p>If your application is primarily a CRUD-based system with moderate data complexity, Spring Data JPA is a great choice due to its simplicity and developer productivity. However, if you are building a high-performance system, such as a financial application, where database efficiency is paramount, MyBatis or native queries will offer superior control and performance.</p><h3>Conclusion</h3><p>High-level abstractions like Spring Data JPA boost developer productivity, but at the cost of performance pitfalls like the N+1 problem. While solutions like JOIN FETCH or Entity Graphs can mitigate some issues, they don’t always scale well, especially in high-load environments like banking systems.</p><p>For performance-sensitive applications, understanding when to bypass ORM magic and use native queries or MyBatis is crucial. Choosing the right level of abstraction is a balancing act — one that requires deep architectural awareness rather than blindly following ORM defaults.</p><p>As backend developers, we should always ask ourselves:</p><p><em>“Is the convenience of high-level querying worth the hidden punishment it brings?”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1f12a10da1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Limitations in Distributed Systems: A Gentle Guide to the CAP Theorem]]></title>
            <link>https://medium.com/@ahmtatar/understanding-the-limitations-in-distributed-systems-a-gentle-guide-to-the-cap-theorem-96b548e5bdb1?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b548e5bdb1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[cap-theorem]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 12:58:58 GMT</pubDate>
            <atom:updated>2024-12-21T12:58:58.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGwcF-Fu7C4LsiP09Ub2bA.png" /></figure><h3>Why Do Limits Matter?</h3><p>In the world of distributed systems — where immense amounts of data need to be processed, stored, and accessed — one might ask: can we have it all? Can a system always stay consistent, available, and resilient to failures? The CAP theorem gives us a practical, if sobering, answer: not really. But don’t see this as defeat — it’s about making informed trade-offs.</p><p>Think of this: you’re booking a table at a popular restaurant using an online reservation app during peak dinner hours. You get conflicting information — the app says a table is available, but when you arrive, it’s already taken. Why does this happen? The CAP theorem has a lot to say about it.</p><blockquote>“You can have consistency and availability, but only if there are no partitions. Once a partition happens, you have to make a choice.”<br> — Eric Brewer, who introduced the CAP theorem.</blockquote><h3>What Is the CAP Theorem?</h3><p>Introduced by Eric Brewer in 2000, the CAP theorem states that a distributed system cannot fully achieve these three properties at the same time:</p><ul><li><strong>Consistency (C):</strong> Every read reflects the most recent write — or returns an error.</li><li><strong>Availability (A):</strong> Every request gets a response, even if it’s outdated.</li><li><strong>Partition Tolerance (P):</strong> The system keeps running even when communication between parts fails.</li></ul><p>In short, you can choose any two of these, but not all three. This drawbacks shapes how most systems are being designed today. It’s not just theory — it’s the daily reality of developers worldwide.</p><h3><strong>Breaking Down the Trade-offs</strong></h3><p><strong>1. Consistency vs. Availability</strong><br>Imagine an online shopping platform, especially during a big sale when hundreds of users are trying to buy the same popular item simultaneously. To ensure consistency, the system might lock the inventory database temporarily, ensuring no two users can purchase the last item at the same time. However, this lock also means the system becomes briefly unavailable to others, potentially frustrating buyers.</p><p>On the other hand, if the platform prioritizes availability, it might let everyone proceed with their purchases, even if the inventory data is slightly outdated. This could lead to overselling, where multiple customers buy an item that isn’t actually in stock.</p><p>This trade-off is especially noticeable in high-demand situations. Consider a concert ticketing platform during a ticket release for a major event. These systems often prioritize availability to handle the sheer volume of users simultaneously trying to secure tickets. The platform allows users to proceed to checkout, even if there’s a risk of backend inconsistencies. Unfortunately, this might mean some users receive notifications that their tickets are no longer available after they’ve already completed payment — a clear example of prioritizing availability over consistency.</p><p><strong>2. Consistency vs. Partition Tolerance</strong><br>Now, think about the ATM network of a bank. If a partition occurs — for example, if a specific region loses its connection to the central banking server — strict consistency would require the system to halt all transactions in that region until the connection is restored. While this ensures that the central system always reflects accurate and consistent data, it also means users cannot access their funds during the outage, which can be highly inconvenient.</p><p>To address this, many ATM networks prioritize partition tolerance while accepting temporary inconsistencies. This means the ATM allows users to withdraw cash locally, even when the server connection is down. Once the connection is restored, the system reconciles these transactions with the central server.</p><p>For instance, if a customer withdraws $100 during an outage, the ATM processes the transaction and debits the amount from the central account later. This approach balances customer convenience and operational accuracy, ensuring users can access their money while the system maintains eventual consistency. It’s not a perfect solution, but it’s one that puts customer experience first without completely compromising data integrity.</p><p><strong>3. Availability vs. Partition Tolerance</strong><br>Consider a social media platform, where millions of users are constantly posting, liking, and sharing content. When a partition happens — such as when a portion of the network is temporarily unable to communicate with the rest — prioritizing availability means that users can continue posting and interacting with content. However, the system may not update certain elements in real time. For instance, you might notice outdated likes, comments, or retweets on a post because the partition prevents those updates from syncing immediately.</p><p>This decision is critical to keeping users engaged. Platforms like Instagram or Twitter, for example, are designed to prioritize availability. If a network issue arises, they allow users to post and browse content as usual, even if the data isn’t fully synchronized. Once the partition is resolved, the system updates likes, shares, or comments that were delayed, ensuring the data reflects the activity accurately.</p><p>This approach works because it maintains the platform’s core functionality during disruptions. Users might notice minor delays or inconsistencies, but they can still enjoy the primary features of the app. By prioritizing availability and tolerating temporary partitions, these platforms ensure that engagement remains high, even in less-than-ideal network conditions.</p><h3><strong>Real-World Applications</strong></h3><p>To better understand how trade-offs in distributed systems play out, let’s compare two very different examples: a banking system and an e-commerce platform. Although both are distributed systems, their priorities and requirements vary significantly.</p><ul><li><strong>Banking System:</strong><br>In banking applications, consistency is of utmost importance. For example, when a user transfers money from one account to another, the system must ensure the funds are deducted from one account and credited to the other without any errors. Accuracy is non-negotiable in these transactions.</li><li>Partition tolerance is also crucial since customers often access their accounts from various locations, such as ATMs, mobile apps, or branches. However, the system can afford to sacrifice a bit of availability if it ensures consistent and accurate data, even during disruptions.</li><li>Consider loan processing as another example. Loan applications involve complex workflows where data consistency across different systems is critical. If a partition occurs, verifying the borrower’s eligibility and other details takes precedence over instant availability. Slight delays are acceptable to maintain data integrity and avoid errors.</li><li><strong>E-commerce Platform:</strong><br>In contrast, e-commerce systems prioritize availability over strict consistency, particularly during high-traffic events like flash sales. The user experience depends on allowing customers to browse and make purchases, even if inventory data isn’t perfectly up-to-date.</li><li>Partition tolerance is equally vital, as customers from different regions need simultaneous access to the platform. Temporary inconsistencies, such as showing an item in stock when it’s actually sold out, are considered acceptable trade-offs. These issues can be addressed post-purchase rather than disrupting the shopping experience in real time.</li><li>For instance, during a Black Friday sale, a customer might add an item to their cart that technically has limited stock. To maintain availability, the system may temporarily overcommit inventory, ensuring the purchase goes through. After the sale, backend processes reconcile inventory and issue refunds if necessary, preserving customer trust while ensuring smooth transactions during the sale.Expanding on Design Choices</li></ul><p>Each system’s design choices are driven by its specific needs and priorities. For the banking system, the potential risk of financial errors makes consistency paramount. For the e-commerce platform, the user experience demands high availability, even if it means tolerating temporary inconsistencies.</p><h4>Lessons from Industry Leaders</h4><ul><li><strong>Netflix:</strong> Netflix is an AP system, prioritizing availability and partition tolerance. If a partition happens, you might see an outdated movie list or delayed watch history updates, but streaming continues.</li><li><strong>Amazon Web Services (AWS):</strong> AWS DynamoDB lets developers choose between eventual consistency (for speed) or strong consistency (for accuracy).</li></ul><h3>Wrapping Up the Key Ideas</h3><p>The CAP theorem is like the laws of physics for distributed systems. It doesn’t limit us — it guides us. Whether you’re building a chat app, a trading platform, or a streaming service, CAP forces you to prioritize what matters most to your users.</p><p>So, the next time your app lags or a system hiccups, remember: it’s not broken — it’s balancing the unavoidable trade-offs CAP demands. These aren’t barriers — they’re opportunities to design smarter systems for real-world needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b548e5bdb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Speaking HTTP: Decoding Methods, Missteps, and Mastery]]></title>
            <link>https://medium.com/@ahmtatar/the-art-of-speaking-http-decoding-methods-missteps-and-mastery-4eb681c9f400?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb681c9f400</guid>
            <category><![CDATA[http-status-code]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[http-methods]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 12:51:24 GMT</pubDate>
            <atom:updated>2024-11-16T15:12:31.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnowBvWzroRVAtZbZSy9OQ.png" /></figure><p>The Hypertext Transfer Protocol (HTTP) is the silent hero of the internet, dictating how clients and servers communicate. Its methods — verbs like GET, POST, PUT, and others — serve as the foundation for RESTful APIs and modern web applications. While these methods might seem straightforward at first glance, nuances in their use, common misconceptions, and edge cases often trip up developers.</p><p>In this article, we’ll explore the correct use of HTTP methods, address frequently misunderstood concepts, and dive into best practices that every developer should know. Because, let’s face it — no one wants their API to be the digital equivalent of a spaghetti code nightmare.</p><h3>The Core HTTP Methods: Fundamentals and Misconceptions</h3><h4>1. GET</h4><p><strong>Purpose:</strong> Retrieve data from the server without causing any changes.</p><p><strong>Idempotence:</strong> Yes. Making the same GET request multiple times should yield the same result.</p><p><strong>Misconception:</strong> Can GET be used to perform actions like creating or deleting resources?<br>Technically, yes, you could use GET to trigger server-side actions — just like you could write your entire backend project in a single, unopinionated file of spaghetti code. But would that really reflect good engineering? Probably not.</p><ul><li><strong>Caching Issues:</strong> GET responses are often cached by browsers or intermediaries, potentially triggering unintended actions.</li><li><strong>Developer Confusion:</strong> It blurs the purpose of GET, making APIs harder to understand and maintain.</li><li><strong>Security Risks:</strong> Vulnerabilities like CSRF attacks become more likely when unsafe actions are exposed via GET.</li></ul><p><strong>Best Practice:</strong> Use GET only for data retrieval. For actions, prefer POST, PUT, or DELETE instead.</p><h4>2. POST</h4><p><strong>Purpose:</strong> Send data to the server to create or process something.</p><p><strong>Idempotence:</strong> No. Sending the same POST request twice can lead to multiple creations or processes.</p><p><strong>Misconception:</strong> Is POST only for creating new resources?<br>Not at all. POST is versatile — it’s ideal for non-idempotent operations, such as submitting a form, processing a payment, or triggering a workflow.</p><p><strong>Best Practice: </strong>Use POST when no other method fits the operation or when performing complex, non-idempotent tasks.</p><h4>3. PUT</h4><p><strong>Purpose:</strong> Replace an existing resource entirely or create it if it doesn’t exist.</p><p><strong>Idempotence:</strong> Yes. Sending the same PUT request repeatedly has the same effect as sending it once.</p><p><strong>Misconception:</strong> How is PUT different from POST?<br>PUT is used for creating or replacing a resource at a specific URI. It requires the client to send the entire resource representation. POST, on the other hand, is often used for creating resources where the server determines the resulting URI or for triggering actions without a strict resource representation.</p><pre>PUT /users/123<br>Content-Type: application/json<br><br>{<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john.doe@example.com&quot;,<br>  &quot;phone&quot;: &quot;+1234567890&quot;,<br>  &quot;address&quot;: &quot;123 Main St, Springfield&quot;<br>}</pre><p>If the user with ID 123 exists, this request will <strong>replace</strong> the entire resource, overwriting any existing data.</p><p>If the user doesn’t exist, the server will <strong>create</strong> a new resource at /users/123 with the provided data.</p><p><strong>Best Practice</strong>: Use PUT for updates or replacements where:</p><ol><li>The client knows the resource’s exact URI.</li><li>Idempotency is critical (repeating the request should yield the same result).</li></ol><p>This distinction ensures clarity in API design and prevents unintended behavior.</p><h4>4. PATCH</h4><p><strong>Purpose</strong>: Apply partial updates to a resource. Unlike PUT, PATCH is designed to modify only specific fields of a resource without overwriting the entire object.</p><p><strong>Idempotence</strong>: <strong>Yes</strong>. Repeatedly applying the same PATCH request results in the same changes being applied.</p><p><strong>Misconception:</strong> When should you use PATCH instead of PUT?<br>PATCH modifies only the fields specified in the request, leaving the rest of the resource untouched, while PUT requires a full representation of the resource.</p><p><strong>Example: </strong>Updating only a user’s email address with PATCH:</p><pre>PATCH /users/123<br>Content-Type: application/json<br><br>{<br>  &quot;email&quot;: &quot;new@example.com&quot;<br>}</pre><p>This request updates the email field while leaving the rest of the user&#39;s data (e.g., name, phone, address) unchanged.</p><p><strong>Best Practice</strong>: Use PATCH when:</p><ol><li>You need to update only specific fields of a resource.</li><li>Efficiency is critical, and sending the entire resource representation would be unnecessary or cumbersome.</li></ol><h4>5. DELETE</h4><p><strong>Purpose</strong>: Remove a resource from the server.</p><p><strong>Idempotence</strong>: <strong>Yes</strong>. Repeated DELETE requests for the same resource yield the same outcome — once deleted, it’s gone.</p><p><strong>Misconception:</strong> Does DELETE always physically remove a resource?<br>Not necessarily. DELETE can perform a soft delete, marking a resource as inactive without erasing it from the database. However, the client can assume the resource is no longer accessible.</p><p><strong>Example:</strong></p><pre>DELETE /users/123</pre><p>Removes user “123” or makes it inaccessible.</p><p><strong>Best Practice</strong>:</p><ol><li>Use <strong>204 No Content</strong> to indicate successful deletion without a response body.</li><li>Use 404 Not Found if the resource was already deleted.</li><li>Log DELETE operations for traceability, especially for irreversible actions.Underappreciated Methods: HEAD and OPTIONS</li></ol><h3>Underappreciated Methods: HEAD and OPTIONS</h3><h4>HEAD</h4><p><strong>Purpose</strong>: Retrieve metadata about a resource without downloading the full content. The server responds with the same headers as a GET request but leaves the body empty.</p><p><strong>Use Cases</strong>:</p><ol><li><strong>Check Resource Existence</strong>: Determine if a file, page, or endpoint exists without downloading the entire content.</li><li><strong>Retrieve Metadata: </strong>Fetch headers like Content-Length to get the size of a resource or Last-Modified to check for updates.</li><li><strong>Improve Efficiency:</strong> Avoid downloading large resources when only metadata is required, saving bandwidth and time.</li></ol><p><strong>Example:</strong></p><p>Request:</p><pre>HEAD /file.zip HTTP/1.1<br>Host: example.com</pre><p>Response:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/zip<br>Content-Length: 10567890<br>Last-Modified: Wed, 15 Nov 2023 10:00:00 GMT</pre><p>This confirms the file exists, its size is 10 MB, and it was last modified on the specified date.</p><h4>OPTIONS</h4><p><strong>Purpose</strong>: Discover what actions (HTTP methods) are supported for a given resource or endpoint.</p><p><strong>Use Cases</strong>:</p><ol><li><strong>CORS Pre-Flight Requests</strong>: Browsers automatically send OPTIONS requests to verify cross-origin permissions before executing actual requests.</li><li><strong>API Exploration:</strong> Allow developers to query an endpoint and understand which HTTP methods are supported without causing unintended side effects.</li><li><strong>Documentation and Debugging:</strong> Provide clear visibility into server capabilities.</li></ol><p><strong>Example:</strong></p><p>Request:</p><pre>OPTIONS /users/123 HTTP/1.1<br>Host: example.com</pre><p>Response:</p><pre>HTTP/1.1 200 OK<br>Allow: GET, PATCH, DELETE</pre><p>Alternatively, in a JSON-based API, the response could look like this:</p><pre>{<br>  &quot;methods&quot;: [&quot;GET&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;]<br>}</pre><p>This informs the client that the /users/123 endpoint supports GET, PATCH, and DELETE but not methods like POST or PUT.</p><h3>Common Missteps and Anti-Patterns</h3><h4>1. Using GET for Actions</h4><p>Example: /purchase?id=123 triggering a purchase violates GET&#39;s safety principle, risks caching issues, and introduces CSRF vulnerabilities.</p><h4>2. PUT vs. PATCH Confusion</h4><p>Using PUT for partial updates wastes bandwidth and may unintentionally overwrite fields.</p><h4>3. Overusing POST</h4><p>Using POST for idempotent operations (like updates) or deletions creates inconsistent and unclear APIs.</p><h3>Best Practices for HTTP Methods</h3><h4>1. Respect REST Principles</h4><ul><li>Use methods as intended, adhering to safety and idempotency rules.</li></ul><h4>2. Return Proper Status Codes</h4><ul><li><strong>200 OK</strong>: For successful retrievals.</li><li><strong>201 Created</strong>: When POST creates a resource.</li><li><strong>204 No Content</strong>: For successful but empty responses (e.g., DELETE).</li><li><strong>400 Bad Request</strong>: For invalid input.</li><li><strong>404 Not Found</strong>: When a resource doesn’t exist.</li><li><strong>500 Internal Server Error</strong>: For generic server-side errors.</li></ul><h4>3. Document Your API</h4><ul><li>Clearly explain each method’s purpose, parameters, and responses.</li></ul><h4>4. Secure Your API</h4><ul><li>Validate inputs and protect against vulnerabilities like CSRF and injection attacks.</li></ul><h3>Final Thoughts</h3><p>HTTP methods are more than just verbs; they’re the backbone of a well-designed API. Misusing them leads to confusion and inefficiency, while following best practices ensures clarity, security, and maintainability. Use HTTP methods wisely, and your APIs will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb681c9f400" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Docker without Docker Desktop: A Command-Line Guide for Backend Developers on Linux]]></title>
            <link>https://medium.com/@ahmtatar/managing-docker-without-docker-desktop-a-command-line-guide-for-backend-developers-on-linux-aa9a2afecac7?source=rss-07bd34e7a417------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9a2afecac7</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ahmet Atar]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 15:39:51 GMT</pubDate>
            <atom:updated>2024-11-17T12:13:42.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*V9-S66ng1sfqB1AveQSrNQ.jpeg" /></figure><h3>Introduction</h3><p>Docker is a powerful tool that has greatly streamlined software development and deployment, particularly for multi-service applications. However, the lack of Docker Desktop support on certain Linux distributions, such as Ubuntu 24.x versions, means developers are reliant on terminal commands to manage their Docker environments. In this article, I’ll share my experience troubleshooting a specific Docker issue through the command line without Docker Desktop, detailing the steps I took to resolve it.</p><p>This guide is especially targeted at developers who need to manage Docker containers via the command line, focusing on tasks like container management, restarting stopped containers, and resolving port conflicts. It’s designed to provide practical solutions for developers who are comfortable with basic Docker commands but may encounter occasional issues and seek straightforward, reliable steps to address them.</p><h3>Step-by-Step Guide</h3><p>This section outlines essential Docker commands and troubleshooting steps you’ll need to manage containers entirely through the Linux terminal. From viewing containers to restarting stopped instances and resolving port conflicts, these instructions are crafted to help you work effectively with Docker.</p><h3>1. Viewing, Starting, and Removing Containers</h3><p>To manage Docker containers efficiently, you’ll first want to know how to view, start, and remove them as necessary.</p><p>To list all active containers, use:</p><pre>sudo docker ps</pre><p>To view all containers, including those that have stopped, use:</p><pre>sudo docker ps -a</pre><p>The -a option displays every container regardless of its current state. This can be helpful for identifying containers that may have exited or encountered issues.</p><p>If you have containers that are stopped and no longer needed, remove them with:</p><pre>sudo docker rm &lt;container_name_or_id&gt;</pre><p>To remove all stopped containers at once:</p><pre>sudo docker container prune</pre><p>If, for example, your PostgreSQL container has stopped but you don’t want to remove it, simply restart it with:</p><pre>sudo docker start &lt;container_name_or_id&gt;</pre><p>These basic commands help you maintain an organized container environment, ensuring that only the necessary containers are active.</p><h3>2. Starting and Restarting a Stopped Container</h3><p>After identifying a stopped container, restart it with the following command:</p><pre>sudo docker start &lt;container_name_or_id&gt;</pre><p>If the container doesn’t start and you see an error message about port conflicts, such as bind: address in use, this typically means that another service or process is using the same port as the container.</p><h3>3. Resolving Port Conflicts</h3><p>To determine whether a specific port — such as port 5432for PostgreSQL — is already in use, run:</p><pre>sudo lsof -i :5432</pre><p>This command lists any processes currently using port 5432, which is especially useful when working with services like databases that often default to specific ports.</p><p>If you find that another process, like a locally running PostgreSQL service, is occupying this port, you can temporarily stop the service to free it for Docker. For instance:</p><pre>sudo service postgresql stop</pre><p>Once the PostgreSQL service is stopped, try starting the container again:</p><pre>sudo docker start &lt;container_name_or_id&gt;</pre><p>This approach should enable Docker to bind to the port without conflicts. To confirm, you can check the container’s status with sudo docker ps.</p><h3>4. Directly Killing a Process Using the Port (Alternative Solution)</h3><p>If stopping the service isn’t feasible, you can kill the specific process occupying the port. Be cautious with this approach, as it forcibly terminates the process, making it best used only when necessary.</p><p>Use lsof to find the Process ID (PID) for the port:</p><pre>sudo lsof -i :5432</pre><p>Kill the process by its PID:</p><pre>sudo kill &lt;process_id&gt;</pre><p>After ending the process, restart the container. This method also frees the port for Docker usage.</p><h3>5. Running a Container with Custom Settings</h3><p>To create a new container with custom configurations, such as environment variables and port mappings, use the docker run command. For example, to launch a PostgreSQL container with specific settings:</p><pre>sudo docker run -d -p 5432:5432 --name postgresql_container -e POSTGRES_PASSWORD=123456 postgres</pre><ul><li>-d runs the container in detached mode, meaning it operates in the background.</li><li>-p 5432:5432 maps port 5432 on your local machine to port 5432 within the container.</li><li>--name postgresql_container assigns a custom name to the container.</li><li>-e POSTGRES_PASSWORD=123456 sets an environment variable inside the container, in this case, specifying the password for the default PostgreSQL user (postgres).</li><li>postgres designates the Docker image to use—in this case, the official PostgreSQL image.</li></ul><h3>6. Using Docker Compose for Multi-Container Project</h3><p>If you’re working with applications that require multiple containers, Docker Compose simplifies management by allowing you to define and configure services in a single docker-compose.yml file. Here’s a basic example for a PostgreSQL service:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  db:<br>    image: postgres<br>    ports:<br>      - &quot;5432:5432&quot;<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: 123456<br>      POSTGRES_DB: my_postgresql_db</pre><p>To launch all services defined in docker-compose.yml:</p><pre>sudo docker compose up -d</pre><p>To stop them:</p><pre>sudo docker compose down</pre><p>Docker Compose enables you to start and stop multiple containers simultaneously, which is particularly beneficial for applications with dependencies, such as a backend service that requires a database.</p><h3><strong>Conclusion</strong></h3><p>Managing Docker on Linux without Docker Desktop might seem challenging at first, but getting comfortable with these essential commands can make it much more approachable. This guide aimed to offer a straightforward approach to container management, resolving port conflicts, and setting up custom configurations — all from the command line. With these basics, I hope you’ll feel more prepared to handle Docker in your development environment. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9a2afecac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>