<?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 Raphael Fernandes on Medium]]></title>
        <description><![CDATA[Stories by Raphael Fernandes on Medium]]></description>
        <link>https://medium.com/@raphael.lima05?source=rss-682f8f4575d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y_3n-WgzbmMHoh-MCDW4Mw.png</url>
            <title>Stories by Raphael Fernandes on Medium</title>
            <link>https://medium.com/@raphael.lima05?source=rss-682f8f4575d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:17:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raphael.lima05/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[Why You Should Never Use float for Money (and What to Use Instead)]]></title>
            <link>https://medium.com/everything-for-developers/why-you-should-never-use-float-for-money-and-what-to-use-instead-42f113a2dc84?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/42f113a2dc84</guid>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 15:57:14 GMT</pubDate>
            <atom:updated>2026-09-02T15:57:14.619Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever added 0.1 + 0.7 in code and been surprised that the result isn’t exactly 0.8, you’ve run into one of the most common—and costly—pitfalls in software development: using floating-point types to store monetary values.</p><p>In this post, you’ll see why float (and double) are a bad fit for money, what can go wrong in real systems, and what you should use instead in languages like C#, Python, Java, and others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixG66fgzHivANLi1erPCHg.png" /></figure><h3>The problem: 0.1 + 0.7 doesn’t equal 0.8</h3><p>Try this in many languages:</p><pre>float a = 0.1f;<br>float b = 0.7f;<br>Console.WriteLine(a + b); // Often prints 0.7999999...</pre><p>Or:</p><pre>a = 0.1<br>b = 0.2<br>print(a + b)  # 0.30000000000000004</pre><p>You expect 0.8 or 0.3, but you get something slightly off.</p><p>This happens because float and double are <strong>binary floating-point</strong> types. They store numbers in base 2 using a fixed number of bits, optimized for speed and memory, not exact decimal representation.</p><p>Many common decimal fractions like 0.1, 0.2, and 0.7 cannot be represented exactly in binary. The computer stores the <em>closest</em> binary approximation, which introduces tiny rounding errors. For a single calculation, that might not matter. For money, it absolutely does.</p><h3>Why binary floating-point is a bad fit for money</h3><p>Floating-point types are designed for scientific and engineering calculations where:</p><ul><li>A small relative error is acceptable.</li><li>Performance and memory usage matter more than exact decimal precision.</li></ul><p>Money, on the other hand, has very different requirements:</p><ul><li><strong>Exactness matters</strong>: €10.99 must be exactly €10.99, not €10.989999....</li><li><strong>Rounding rules are strict</strong>: Financial systems often have legally defined rounding behavior.</li><li><strong>Errors compound</strong>: Small inaccuracies can accumulate over many transactions, leading to noticeable discrepancies in balances, reports, and taxes.</li></ul><p>Using float or double for currency means your system is fundamentally unable to represent many monetary values exactly. That’s not a “corner case”; it’s baked into how these types work.</p><p><strong>Real-world consequences: when rounding errors become expensive</strong></p><p>Floating-point inaccuracies aren’t just academic. In safety-critical and financial systems, they can cause serious problems.</p><p>One famous example often cited in engineering circles is the <strong>Patriot missile incident</strong> during the Gulf War. A small rounding error in time calculations — due to how floating-point values accumulated over long uptime — contributed to a failure to intercept an incoming missile, with tragic consequences. While that case involved time and not money, it illustrates the same principle: tiny representation errors in floating-point math can grow and lead to catastrophic outcomes in real systems.</p><p>In financial software, similar issues show up as:</p><ul><li>Customers being overcharged or undercharged by a cent or more.</li><li>Reconciliation failures between systems.</li><li>Incorrect tax calculations.</li><li>Audit and compliance problems when ledgers don’t add up exactly.</li></ul><p>None of these are acceptable in production systems handling real money.</p><p><strong>How to fix it: use the right type for money</strong></p><p>You have two main strategies:</p><h3>1. Store money as integers (e.g., cents)</h3><p>A simple, robust approach is to avoid decimals entirely and store monetary values as <strong>integers in the smallest currency unit</strong>:</p><ul><li>€10.99 → 1099 cents</li><li>$0.01 → 1 cent</li><li>£123.45 → 12345 pence</li></ul><p>All arithmetic then uses integer math, which is exact:</p><pre>int priceCents = 1099;<br>int quantity = 3;<br>int totalCents = priceCents * quantity; // 3297 cents = €32.97</pre><p>Pros:</p><ul><li>Exact arithmetic, no rounding surprises.</li><li>Very fast and memory-efficient.</li><li>Works in any language with integer types.</li></ul><p>Cons:</p><ul><li>You must remember to convert to/from decimal for display.</li><li>You need to handle currency-specific rules (e.g., JPY has no minor unit, some currencies use 3 decimal places).</li></ul><p>This pattern is widely used in payments, accounting, and fintech systems.</p><p><strong>2. Use decimal / money types provided by the language</strong></p><p>Most modern languages offer a <strong>decimal</strong> or <strong>money</strong> type designed for precise base-10 arithmetic.</p><p>Examples:</p><ul><li><strong>C#</strong>: decimal</li><li><strong>Python</strong>: decimal.Decimal</li><li><strong>Java</strong>: java.math.BigDecimal</li><li><strong>PostgreSQL</strong>: NUMERIC / DECIMAL</li><li><strong>JavaScript</strong>: libraries like decimal.js or big.js (native number is floating-point)</li></ul><p>These types:</p><ul><li>Store numbers in a <strong>base-10</strong> representation (often conceptually similar to “text” or digit arrays).</li><li>Perform arithmetic digit-by-digit in decimal, not binary.</li><li>Can represent 0.1, 0.2, 10.99 exactly.</li></ul><p>Example in C#:</p><pre>decimal a = 0.1m;<br>decimal b = 0.7m;<br>Console.WriteLine(a + b); // 0.8 exactly</pre><p>Example in Python:</p><pre>from decimal import Decimal<br><br>a = Decimal(&quot;0.1&quot;)<br>b = Decimal(&quot;0.7&quot;)<br>print(a + b)  # 0.8 exactly</pre><p>Note: In Python and some other languages, you should construct Decimal from <strong>strings</strong> (&quot;0.1&quot;) rather than floats (0.1) to avoid importing the floating-point error in the first place.</p><p>Pros:</p><ul><li>Exact decimal arithmetic.</li><li>Built-in support for rounding modes and precision control.</li><li>Clear intent in the code: “this is money”.</li></ul><p>Cons:</p><ul><li>Slower than float/double.</li><li>Use more memory.</li><li>Slightly more verbose API in some languages.</li></ul><p><strong>Performance and memory: when is </strong><strong>float okay?</strong></p><p>Decimal types are <strong>slower</strong> and <strong>heavier</strong> than binary floating-point. That’s by design: they trade performance for exactness.</p><p>So when <em>should</em> you use float or double?</p><ul><li>Scientific simulations where small relative errors are acceptable.</li><li>Graphics, games, and ML where performance is critical and exact decimal representation isn’t required.</li><li>Any domain where you don’t need exact base-10 values and can tolerate rounding noise.</li></ul><p>When should you <strong>not</strong> use them?</p><ul><li>Prices, balances, taxes, invoices.</li><li>Anything that gets audited, reconciled, or shown to customers as money.</li><li>Any domain where “off by a cent” is a bug, not a feature.</li></ul><p>A good rule of thumb:</p><blockquote><em>If the value represents money or anything that must be exactly representable in base 10, don’t use </em><em>float or </em><em>double.</em></blockquote><p><strong>Key takeaways</strong></p><ul><li>float and double cannot exactly represent many common decimal values like 0.1, 0.2, and 0.7, leading to surprising results like 0.1 + 0.7 != 0.8.</li><li>These types are optimized for speed and memory, not exact decimal arithmetic, making them unsuitable for money.</li><li>Real systems have suffered serious consequences from floating-point rounding errors; financial software cannot afford this risk.</li><li>Use either:</li><li>Integers in the smallest currency unit (cents, pence, etc.), or</li><li>Decimal/money types (decimal, BigDecimal, Decimal, DB NUMERIC).</li><li>Accept the performance and memory cost of decimal types where accuracy is required; reserve float/double for domains where small errors are acceptable.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42f113a2dc84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/why-you-should-never-use-float-for-money-and-what-to-use-instead-42f113a2dc84">Why You Should Never Use float for Money (and What to Use Instead)</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 8 Fallacies of Distributed Systems Every Microservices Architect Must Know]]></title>
            <link>https://medium.com/everything-for-developers/the-8-fallacies-of-distributed-systems-every-microservices-architect-must-know-e0d04e5fc020?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0d04e5fc020</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 20:50:41 GMT</pubDate>
            <atom:updated>2026-08-30T20:50:41.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8Hj0OHmLScAyrMulyUStA.png" /></figure><p>You’ve probably heard it before: <em>“Microservices are always the best choice. Every architect should design with them.”</em></p><p>But as Mark Richards and Neal Ford remind us in <em>Fundamentals of Software Architecture</em>, the first rule of software architecture is</p><blockquote><strong>Everything is a trade-off.</strong></blockquote><p>And as someone else said:</p><blockquote><strong>If you think something has no trade-offs, you just haven’t discovered them yet.</strong></blockquote><p>Microservices are no exception. If you’re chasing high availability, scalability, and performance, you need to understand what you’re giving up — and why distributed systems are hard.</p><p>Back in the 1990s, a group at Sun Microsystems, led primarily by L. Peter Deutsch, codified the hidden traps of distributed computing into what we now call <strong>the 8 fallacies of distributed systems</strong>. These are the myths that trip up even experienced teams when they first build distributed applications.</p><p>If you’re designing or operating microservices, these fallacies should be on your wall.</p><h3>1. The network is reliable</h3><p>It isn’t.</p><p>Networks fail — constantly. Requests time out, connections drop, DNS glitches happen, load balancers hiccup, and databases become temporarily unreachable. It doesn’t matter if you’re using REST, gRPC, or message queues: <strong>every remote call can and will fail</strong>.</p><p>Design for failure:</p><ul><li>Use retries with backoff and jitter.</li><li>Implement circuit breakers and bulkheads.</li><li>Assume partial failure is the norm, not the exception.</li></ul><h3>2. Latency is zero</h3><p>It never is.</p><p>A local function call is orders of magnitude faster than a remote one. In microservices, every hop across the network adds latency — and that latency is variable. As an architect, you should know your service’s <strong>p95 and p99 latencies</strong>, not just the averages.</p><p>Remember:</p><ul><li>Local = shared memory/CPU/cache.</li><li>Remote = network, serialization, context switches, and more.</li></ul><p>Optimize chatty calls, batch where possible, and always measure real-world latency under load.</p><h3>3. Bandwidth is infinite</h3><p>It isn’t — and overfetching kills it fast.</p><p>Consider this common scenario: Service A needs a person’s name, so it calls Service B’s “get person” endpoint. Service B returns the entire Person object with 45 properties, totaling 500 KB per response.</p><p>At 2,000 requests per second, that’s <strong>1 GB/s</strong> of unnecessary traffic — just because one service needed a single field.</p><p>This is <strong>stamp coupling</strong> in action: you’re coupled to a large composite data structure when you only need a slice of it.</p><p>Mitigate it by:</p><ul><li>Designing field-selective APIs (?fields=name).</li><li>Creating lean, purpose-built endpoints.</li><li>Using GraphQL or similar projection mechanisms where appropriate.</li></ul><h3>4. The network is secure</h3><p>It’s not — especially in microservices.</p><p>Every service-to-service call, every database connection, every internal API is a potential attack surface. More services = more endpoints = more opportunities for misconfiguration, credential leaks, or lateral movement after a breach.</p><p>Secure your mesh:</p><ul><li>Enforce mutual TLS (mTLS) between services.</li><li>Use short-lived credentials and robust secret management.</li><li>Apply zero-trust principles: authenticate and authorize every call.</li></ul><h3>5. Topology doesn’t change</h3><p>It does — constantly.</p><p>Teams refactor, scale, migrate, and optimize. A new cache layer here, a database shard there, a region failover, a CDN change — any of these can subtly (or dramatically) alter how your system behaves.</p><p>Even small topology changes can:</p><ul><li>Introduce new latency hotspots.</li><li>Break assumptions about data locality.</li><li>Cause cascading failures if timeouts and retries aren’t tuned.</li></ul><p>Document your topology, test change scenarios, and treat topology as dynamic, not static.</p><h3>6. There is one administrator</h3><p>There never is — at least not in large organizations.</p><p>In enterprise environments, multiple teams own different slices of the network: cloud platform, security, SRE, database ops, networking, and more. If you assume a single point of contact or control, you’ll be blindsided by changes you didn’t know about.</p><p>Stay aligned by:</p><ul><li>Building relationships across platform and infra teams.</li><li>Subscribing to change-management channels and incident reports.</li><li>Designing systems that are resilient to infra changes, not dependent on perfect coordination.</li></ul><h3>7. Transport cost is zero</h3><p>It isn’t — someone pays for every byte and every hop.</p><p>Behind each microservice and database are servers, NICs, switches, subnets, load balancers, and private networks. All of that consumes power, cooling, licensing, and human effort.</p><p>Inefficient communication patterns — chatty APIs, overfetching, unbounded retries — directly increase your cloud bill and operational complexity.</p><p>Optimize transport cost by:</p><ul><li>Reducing unnecessary calls.</li><li>Compressing payloads where it matters.</li><li>Choosing the right consistency and durability guarantees for the use case.</li></ul><h3>8. The network is homogeneous</h3><p>It’s not — your network is a patchwork of different devices, providers, and behaviors.</p><p>One service might run on bare metal in one data center, another in a managed Kubernetes cluster in a different region, another on edge devices with spotty connectivity. Hardware, hypervisors, NICs, MTUs, and even TCP stacks can differ.</p><p>This heterogeneity shows up as:</p><ul><li>Inconsistent latency and throughput across paths.</li><li>Protocol or compatibility issues between components.</li><li>Different failure modes and timeout behaviors.</li></ul><p>Design for the weakest link:</p><ul><li>Test across realistic, varied environments.</li><li>Avoid assumptions about uniform performance or capabilities.</li><li>Use open standards and explicit contracts between services.</li></ul><h3>Designing microservices with eyes open</h3><p>Microservices can deliver incredible scalability, resilience, and team autonomy — but only if you respect the realities of distributed systems.</p><p>The 8 fallacies aren’t just academic; they’re a checklist for the hidden costs and risks you’ll face when you decompose a monolith or greenfield a distributed system.</p><p>Before you draw your next architecture diagram, ask:</p><ul><li>Where am I assuming the network is reliable, fast, or uniform?</li><li>What happens when this call fails, slows down, or returns too much data?</li><li>How will this design behave when the topology or team structure changes?</li></ul><p>If you can answer those honestly, you’re already thinking like an architect who understands the trade-offs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0d04e5fc020" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/the-8-fallacies-of-distributed-systems-every-microservices-architect-must-know-e0d04e5fc020">The 8 Fallacies of Distributed Systems Every Microservices Architect Must Know</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract Factory Pattern in C#: Building Families of Related Payment Operations]]></title>
            <link>https://medium.com/everything-for-developers/abstract-factory-pattern-in-c-building-families-of-related-payment-operations-be54b2a17816?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/be54b2a17816</guid>
            <category><![CDATA[abstract-factory-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 17:20:47 GMT</pubDate>
            <atom:updated>2026-08-26T17:22:38.687Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An extension of the Factory Method pattern for scalable payment systems</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqXkZ1KVz28scSXjpMFaNg.png" /></figure><h3>The Problem: When Factory Method Isn’t Enough</h3><p>Imagine you’ve already implemented a <a href="https://medium.com/everything-for-developers/the-factory-method-pattern-writing-flexible-maintainable-code-ec319d9cf3e8">Factory Method pattern</a> for a payment system supporting PayPal and credit card payments. Everything works fine — until stakeholders ask for <strong>refunds</strong> and <strong>transfers</strong> alongside payments.</p><p>Your instinct might be to add Refund() and Transfer() methods directly to your existing payment classes. But this breaks two critical SOLID principles:</p><ul><li><strong>Single Responsibility Principle</strong>: Each class now handles payment, refund, <em>and</em> transfer logic</li><li><strong>Open/Closed Principle</strong>: Every new operation requires modifying existing classes</li></ul><p>This is where the <strong>Abstract Factory pattern</strong> shines.</p><h3>How Abstract Factory Solves It</h3><p>Instead of bloating individual classes, Abstract Factory lets you create <strong>families of related operations</strong> (Payment, Refund, Transfer) for each payment system (Credit Card, PayPal). Each family stays cohesive, and adding new operations doesn’t touch existing code.</p><p>The key insight: <strong>Concrete factories produce entire product families</strong>, not just single objects.</p><h3>The Architecture</h3><h3>Abstract Products: Defining the Operation Interfaces</h3><p>First, we define interfaces for each operation type:</p><pre>public interface IPaymentMethod<br>{<br>    void Pay(decimal amount);<br>}<br><br>public interface IRefund<br>{<br>    void Refund(decimal amount, string transactionId);<br>}<br><br>public interface ITransfer<br>{<br>    void Transfer(decimal amount, string recipientAccount);<br>}</pre><p>These interfaces represent the <em>abstract products</em> — the contracts that all concrete implementations must follow.</p><p>Concrete Products: Credit Card Family</p><pre>public class CreditCardPayment : IPaymentMethod<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paying {amount:C} via Credit Card&quot;);<br>    }<br>}<br><br>public class CreditCardRefund : IRefund<br>{<br>    public void Refund(decimal amount, string transactionId)<br>    {<br>        Console.WriteLine($&quot;[CreditCard] Refunding {amount:C} for {transactionId}&quot;);<br>    }<br>}<br><br>public class CreditCardTransfer : ITransfer<br>{<br>    public void Transfer(decimal amount, string recipientAccount)<br>    {<br>        Console.WriteLine($&quot;[CreditCard] Transferring {amount:C} to {recipientAccount}&quot;);<br>    }<br>}</pre><p>Notice how each class has <strong>one responsibility</strong>. CreditCardPayment only pays, CreditCardRefund only refunds, and so on.</p><p>Concrete Products: PayPal Family</p><pre>public class PayPalPayment : IPaymentMethod<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paying {amount:C} via PayPal&quot;);<br>    }<br>}<br><br>public class PayPalRefund : IRefund<br>{<br>    public void Refund(decimal amount, string transactionId)<br>    {<br>        Console.WriteLine($&quot;[PayPal] Refunding {amount:C} for {transactionId}&quot;);<br>    }<br>}<br><br>public class PayPalTransfer : ITransfer<br>{<br>    public void Transfer(decimal amount, string recipientAccount)<br>    {<br>        Console.WriteLine($&quot;[PayPal] Transferring {amount:C} to {recipientAccount}&quot;);<br>    }<br>}</pre><p>PayPal has its own family of implementations, keeping payment-system-specific logic isolated.</p><p>The Abstract Factory</p><pre>public interface IPaymentSystemFactory<br>{<br>    IPaymentMethod CreatePaymentMethod();<br>    IRefund CreateRefund();<br>    ITransfer CreateTransfer();<br>}</pre><p>This interface declares <strong>creation methods for every product in the family</strong>. Any concrete factory must implement all three.</p><p>Concrete Factories</p><pre>public class CreditCardPaymentSystemFactory : IPaymentSystemFactory<br>{<br>    public IPaymentMethod CreatePaymentMethod() =&gt; new CreditCardPayment();<br>    public IRefund CreateRefund() =&gt; new CreditCardRefund();<br>    public ITransfer CreateTransfer() =&gt; new CreditCardTransfer();<br>}<br><br>public class PayPalPaymentSystemFactory : IPaymentSystemFactory<br>{<br>    public IPaymentMethod CreatePaymentMethod() =&gt; new PayPalPayment();<br>    public IRefund CreateRefund() =&gt; new PayPalRefund();<br>    public ITransfer CreateTransfer() =&gt; new PayPalTransfer();<br>}</pre><p>Each concrete factory produces <strong>only its own family</strong> of products. CreditCardPaymentSystemFactory never creates PayPal objects, and vice versa.</p><p>The Client: Using the Abstract Factory</p><pre>public class PaymentService<br>{<br>    private readonly IPaymentSystemFactory _factory;<br><br>    public PaymentService(IPaymentSystemFactory factory)<br>    {<br>        _factory = factory;<br>    }<br><br>    public void ProcessPayment(decimal amount)<br>    {<br>        var payment = _factory.CreatePaymentMethod();<br>        payment.Pay(amount);<br>    }<br><br>    public void ProcessRefund(decimal amount, string transactionId)<br>    {<br>        var refund = _factory.CreateRefund();<br>        refund.Refund(amount, transactionId);<br>    }<br><br>    public void ProcessTransfer(decimal amount, string recipientAccount)<br>    {<br>        var transfer = _factory.CreateTransfer();<br>        transfer.Transfer(amount, recipientAccount);<br>    }<br>}</pre><p>The PaymentService depends <strong>only on abstractions</strong>. It doesn&#39;t know whether it&#39;s working with Credit Card or PayPal—just that the factory provides compatible products.</p><p>Wiring It All Together</p><pre>public class Program<br>{<br>    public static void Main()<br>    {<br>        IPaymentSystemFactory factory = new CreditCardPaymentSystemFactory();<br>        // Or: new PayPalPaymentSystemFactory();<br><br>        var service = new PaymentService(factory);<br><br>        service.ProcessPayment(100.00m);<br>        service.ProcessRefund(50.00m, &quot;TXN-999&quot;);<br>        service.ProcessTransfer(75.00m, &quot;ACC-12345&quot;);<br>    }<br>}</pre><p>Switching payment systems requires changing <strong>only one line</strong> — the factory instantiation. The rest of the code remains untouched.</p><h3>Why This Matters</h3><h3>✅ Open/Closed Principle Preserved</h3><p>Adding a new operation (say, ICancel) means:</p><ol><li>Add the interface</li><li>Create CreditCardCancel and PayPalCancel</li><li>Update factories to implement CreateCancel()</li></ol><p><strong>No existing payment, refund, or transfer classes change.</strong></p><h3>✅ Single Responsibility Enforced</h3><p>Each class does one thing:</p><ul><li>CreditCardPayment → pays</li><li>PayPalRefund → refunds</li><li>CreditCardPaymentSystemFactory → creates Credit Card family</li></ul><h3>✅ Easy to Extend Payment Systems</h3><p>Want to add Stripe? Create StripePayment, StripeRefund, StripeTransfer, and StripePaymentSystemFactory. The client code doesn&#39;t care.</p><h3>✅ Consistent Product Families</h3><p>The factory guarantees that all products come from the same family. You’ll never accidentally mix CreditCardPayment with PayPalRefund.</p><h3>When to Use Abstract Factory</h3><p>Use this pattern when:</p><ul><li><strong>You have families of related products</strong> that must be used together</li><li><strong>Your system should be independent</strong> of how products are created and composed</li><li><strong>You want to enforce constraints</strong> that only certain product combinations are valid</li><li><strong>You anticipate adding new product families</strong> without touching client code</li></ul><h3>Trade-offs to Consider</h3><p>Abstract Factory isn’t free:</p><ul><li><strong>More classes</strong>: Every product and factory needs its own class</li><li><strong>Indirection</strong>: Debugging requires tracing through factory layers</li><li><strong>Overkill for simple cases</strong>: If you only have one product type, Factory Method may suffice</li></ul><p>In our payment example, the complexity pays off because refunds and transfers are <strong>first-class operations</strong> that deserve their own abstractions.</p><h3>Key Takeaways</h3><ol><li><strong>Abstract Factory extends Factory Method</strong> by creating families of related products, not just one product type</li><li><strong>Each concrete factory produces one complete family</strong> (e.g., all Credit Card operations)</li><li><strong>Client code depends on abstractions</strong>, making it easy to swap entire product families</li><li><strong>SOLID principles stay intact</strong>: Single Responsibility and Open/Closed are preserved</li><li><strong>Best for complex domains</strong> where operations naturally group into families</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be54b2a17816" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/abstract-factory-pattern-in-c-building-families-of-related-payment-operations-be54b2a17816">Abstract Factory Pattern in C#: Building Families of Related Payment Operations</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Factory Method Pattern: Writing Flexible, Maintainable Code]]></title>
            <link>https://medium.com/everything-for-developers/the-factory-method-pattern-writing-flexible-maintainable-code-ec319d9cf3e8?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec319d9cf3e8</guid>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 17:13:17 GMT</pubDate>
            <atom:updated>2026-08-25T17:13:17.872Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR: The Factory Method pattern lets you delegate object creation to subclasses, removing hard-coded dependencies and keeping your code open for extension but closed for modification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehDPwbcy4O-A1YIpK2oaHw.png" /></figure><h3>The Problem: When Your Code Knows Too Much</h3><p>Imagine you’re building a notification system. Your controller receives a request and needs to send different types of notifications based on the client’s preference:</p><pre>if (request.Type == &quot;text&quot;)<br>    return new SmsNotificationService();<br>else if (request.Type == &quot;slack&quot;)<br>    return new SlackNotificationService();<br>else if (request.Type == &quot;email&quot;)<br>    return new EmailNotificationService();<br><br>notificationService.Send();</pre><p>This approach works — until it doesn’t. Here’s what’s wrong:</p><h3>1. Primitive Obsession</h3><p>You’re using strings (&quot;text&quot;, &quot;slack&quot;, &quot;email&quot;) to make critical decisions. This is fragile: a typo, a case mismatch, or a missing value and your application breaks at runtime.</p><h3>2. Violates Single Responsibility Principle</h3><p>Your controller now has two jobs: handling the request <strong>and</strong> deciding which service to instantiate. It’s doing more than it should.</p><h3>3. Violates the Open-Closed Principle</h3><p>Every time you add a new notification type (WhatsApp, Teams, push notifications), you have to modify the controller. The class is <strong>open to modification</strong> when it should be <strong>closed</strong>.</p><h3>The Solution: Factory Method Pattern</h3><p>The Factory Method pattern solves this by <strong>decoupling object creation from object usage</strong>. Instead of your controller knowing which concrete class to instantiate, it delegates that decision to a subclass.</p><h3>Key Benefits</h3><ul><li><strong>Removes hard-coded dependencies</strong>: The controller works with abstractions, not concrete implementations.</li><li><strong>Follows Open-Closed Principle</strong>: Add new types without modifying existing code.</li><li><strong>Improves testability</strong>: You can inject mock factories for unit testing.</li><li><strong>Clearer separation of concerns</strong>: Creation logic lives in one place, business logic in another.</li></ul><h3>How It Works: A Payment Processing Example</h3><p>Let’s walk through a concrete example using payment methods.</p><h3>Step 1: Define the Product Interface</h3><p>First, create an interface that all concrete products will implement:</p><pre>public interface IPaymentMethod<br>{<br>    void Pay(decimal amount);<br>}</pre><h3>Step 2: Create Concrete Products</h3><p>Implement the interface for each payment type:</p><pre>public class CreditCardPayment : IPaymentMethod<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paying {amount:C} via Credit Card&quot;);<br>    }<br>}<br><br>public class PayPalPayment : IPaymentMethod<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Paying {amount:C} via PayPal&quot;);<br>    }<br>}</pre><h3>Step 3: Create the Creator with the Factory Method</h3><p>The creator defines the <strong>factory method</strong> as an abstract method. Subclasses will override it to decide which product to create:</p><pre>public abstract class PaymentProcessor<br>{<br>    // Factory method – subclasses decide which IPaymentMethod to create<br>    protected abstract IPaymentMethod CreatePaymentMethod();<br><br>    public void ProcessPayment(decimal amount)<br>    {<br>        var paymentMethod = CreatePaymentMethod();<br>        paymentMethod.Pay(amount);<br>    }<br>}</pre><p>Notice that ProcessPayment doesn&#39;t know <strong>which</strong> payment method it&#39;s using—it just knows it implements IPaymentMethod.</p><h3>Step 4: Create Concrete Creators</h3><p>Each concrete creator overrides the factory method to return its specific product:</p><pre>public class CreditCardPaymentProcessor : PaymentProcessor<br>{<br>    protected override IPaymentMethod CreatePaymentMethod()<br>    {<br>        return new CreditCardPayment();<br>    }<br>}<br><br>public class PayPalPaymentProcessor : PaymentProcessor<br>{<br>    protected override IPaymentMethod CreatePaymentMethod()<br>    {<br>        return new PayPalPayment();<br>    }<br>}</pre><h3>Step 5: Client Code</h3><p>Now the client code is clean and flexible:</p><pre>public class Program<br>{<br>    public static void Main()<br>    {<br>        PaymentProcessor processor = new CreditCardPaymentProcessor();<br>        processor.ProcessPayment(99.99m);<br><br>        processor = new PayPalPaymentProcessor();<br>        processor.ProcessPayment(49.50m);<br>    }<br>}</pre><p>Output:</p><pre>Paying €99.99 via Credit Card<br>Paying €49.50 via PayPal</pre><h3>Why This Matters</h3><h3>Before: Tightly Coupled</h3><pre>// Controller knows about concrete classes<br>if (type == &quot;credit&quot;) <br>    new CreditCardPayment();<br>else if (type == &quot;paypal&quot;) <br>    new PayPalPayment();</pre><p>After: Decoupled and Extensible</p><pre>// Controller only knows about the abstraction<br>PaymentProcessor processor = GetProcessorFromConfig(); // Could be any subclass<br>processor.ProcessPayment(amount);</pre><p>Adding a new payment method (e.g., CryptoPayment) now requires:</p><ol><li>Create CryptoPayment : IPaymentMethod</li><li>Create CryptoPaymentProcessor : PaymentProcessor</li><li>Wire it up in your dependency injection or configuration</li></ol><p><strong>No changes to existing code.</strong></p><h3>When to Use Factory Method</h3><p>✅ You don’t know ahead of time which concrete types your code will need<br>✅ You want to give library users a way to extend your framework<br>✅ You’re trying to reduce coupling between high-level and low-level modules<br>✅ You need to centralize object creation logic for consistency or logging</p><p>❌ You only have one concrete product (over-engineering)<br>❌ You’re introducing it into simple CRUD operations without clear benefit</p><h3>Key Takeaways</h3><ol><li><strong>Factory Method delegates creation to subclasses</strong>, keeping the creator decoupled from concrete products.</li><li>It enforces the <strong>Open-Closed Principle</strong>: open for extension, closed for modification.</li><li>Use it when you need <strong>flexibility</strong> and <strong>extensibility</strong> without tight coupling.</li><li>It’s a foundational pattern in object-oriented design and pairs well with dependency injection.</li></ol><h3>Further Reading</h3><ul><li><em>Design Patterns: Elements of Reusable Object-Oriented Software</em> (Gamma et al.)</li><li><a href="https://refactoring.guru/design-patterns/factory-method">Refactoring.Guru — Factory Method</a></li><li>Microsoft Docs: <a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/factory-pattern">Factory Pattern in C#</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec319d9cf3e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/the-factory-method-pattern-writing-flexible-maintainable-code-ec319d9cf3e8">The Factory Method Pattern: Writing Flexible, Maintainable Code</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Calisthenics: 9 Rules to Write Cleaner Object-Oriented Code]]></title>
            <link>https://medium.com/everything-for-developers/object-calisthenics-9-rules-to-write-cleaner-object-oriented-code-96a22bd5a43a?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a22bd5a43a</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[object-calisthenics]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 17:43:12 GMT</pubDate>
            <atom:updated>2026-08-16T17:43:12.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*qGs0UEvlrYkO0LWNs8sctA.png" /></figure><p>Object Calisthenics was introduced in 2004 by Jeff Bay, a Technology Principal at ThoughtWorks, in an essay published in <em>The ThoughtWorks Anthology</em>. The idea was simple but deliberately extreme: define a small set of strict rules and follow them without exception on a practice project, so the discipline they enforce becomes second nature in your everyday code.</p><p>There are nine rules in total. None of them are meant to be dogma you apply everywhere, all the time — they’re a training exercise, like literal calisthenics for your code. But together, they push you toward the same outcomes that principles like SOLID aim for: smaller, more focused classes, less coupling, stronger encapsulation, and code that’s easier to read, test, and extend. Below is each rule with a C# example of the violation and the fix.</p><h3>1. One Level of Indentation per Method</h3><p>A method with multiple nested conditionals forces the reader to track several branches in their head at once. As the logic grows, so does the number of paths through the method, and each new if inside another if compounds that complexity.</p><pre>// Wrong: multiple nested levels of indentation<br>public void ProcessOrder(Order order)<br>{<br>    if (order != null)<br>    {<br>        if (order.IsPaid)<br>        {<br>            if (order.HasStock)<br>            {<br>                Ship(order);<br>            }<br>        }<br>    }<br>}</pre><pre>// Correct: one level of indentation, guard clauses handle the exits<br>public void ProcessOrder(Order order)<br>{<br>    if (order == null) return;<br>    if (!order.IsPaid) return;<br>    if (!order.HasStock) return;<br><br>    Ship(order);<br>}</pre><p>The second version reads top to bottom as a single level of logic. Each guard clause states a precondition explicitly, and the “happy path” is the last line rather than being buried three levels deep. This makes the method easier to read, easier to maintain, and easier to extend if a new precondition is needed later.</p><h3>2. Don’t Use the ELSE Keyword</h3><p>Closely related to the previous rule, avoiding else pushes you toward early returns or polymorphism instead of branching logic. It reduces the number of paths a reader has to hold in mind and often exposes cases better modeled as separate types.</p><pre>// Wrong: relies on else to branch behaviour<br>public string GetShippingCost(Order order)<br>{<br>    if (order.IsInternational)<br>    {<br>        return &quot;50.00&quot;;<br>    }<br>    else<br>    {<br>        return &quot;10.00&quot;;<br>    }<br>}</pre><pre>// Correct: early return removes the need for else<br>public string GetShippingCost(Order order)<br>{<br>    if (order.IsInternational) return &quot;50.00&quot;;<br><br>    return &quot;10.00&quot;;<br>}</pre><p>For more complex branching, polymorphism replaces the else entirely:</p><pre>// Correct: polymorphism instead of conditional branching<br>public abstract class ShippingPolicy<br>{<br>    public abstract decimal GetCost();<br>}<br><br>public class InternationalShipping : ShippingPolicy<br>{<br>    public override decimal GetCost() =&gt; 50.00m;<br>}<br><br>public class DomesticShipping : ShippingPolicy<br>{<br>    public override decimal GetCost() =&gt; 10.00m;<br>}</pre><h3>3. Wrap All Primitives and Strings</h3><p>Encapsulating primitive types into their own objects gives the object control over its own validation and behavior, instead of leaving every caller responsible for checking whether a raw string or int is actually valid.</p><pre>// Wrong: raw string with no validation or behaviour<br>public class User<br>{<br>    public string Email { get; set; }<br>}<br><br>var user = new User { Email = &quot;not-an-email&quot; }; // compiles fine, but invalid</pre><pre>// Correct: Email enforces its own validity<br>public class Email<br>{<br>    private readonly string _value;<br><br>    public Email(string value)<br>    {<br>        if (string.IsNullOrWhiteSpace(value) || !value.Contains(&quot;@&quot;))<br>            throw new ArgumentException(&quot;Invalid email address.&quot;);<br><br>        _value = value;<br>    }<br><br>    public override string ToString() =&gt; _value;<br>}<br><br>public class User<br>{<br>    public Email Email { get; }<br><br>    public User(Email email) =&gt; Email = email;<br>}</pre><p>Now it&#39;s impossible to construct a User with an invalid email — the rule is enforced once, inside Email, instead of scattered across every place a User is created.</p><h3>4. First-Class Collections</h3><p>Any class that holds a List, Dictionary, or other collection should hold nothing else. Wrapping the collection in its own class keeps collection-related logic — filtering, totals, validation — encapsulated in one place instead of leaking out to every caller that touches the raw list.</p><pre>// Wrong: Order exposes a raw List that any caller can mutate freely<br>public class Order<br>{<br>    public List&lt;Item&gt; Items { get; set; } = new List&lt;Item&gt;();<br>}<br><br>// Calculating a total requires external logic scattered across the codebase<br>var total = order.Items.Sum(i =&gt; i.Price);</pre><pre>// Correct: Items encapsulates the collection and its behaviour<br>public class Items<br>{<br>    private readonly List&lt;Item&gt; _items;<br><br>    public Items(IEnumerable&lt;Item&gt; items) =&gt; _items = new List&lt;Item&gt;(items);<br><br>    public decimal TotalPrice() =&gt; _items.Sum(item =&gt; item.Price);<br><br>    public void Add(Item item) =&gt; _items.Add(item);<br>}<br><br>public class Order<br>{<br>    public Items Items { get; }<br><br>    public Order(Items items) =&gt; Items = items;<br>}<br><br>// The caller no longer needs to know how the total is calculated<br>var total = order.Items.TotalPrice();</pre><h3>5. One Dot per Line</h3><p>Chaining several method calls together on one line (a.GetB().GetC().GetD()) reduces readability and violates the Law of Demeter — it couples your code to the internal structure of objects that aren&#39;t directly related to it. It also makes debugging harder, since a single failing line could be failing at any of several points in the chain.</p><pre>// Wrong: reaching through multiple objects on one line<br>decimal taxRate = order.GetCustomer().GetAddress().GetCity().GetTaxRate();</pre><pre>// Correct: Order asks its own dependency, which knows how to resolve the detail<br>public class Order<br>{<br>    private readonly Customer _customer;<br><br>    public Order(Customer customer) =&gt; _customer = customer;<br><br>    public decimal GetTaxRate() =&gt; _customer.GetTaxRate();<br>}<br><br>public class Customer<br>{<br>    private readonly Address _address;<br><br>    public Customer(Address address) =&gt; _address = address;<br><br>    public decimal GetTaxRate() =&gt; _address.GetTaxRate();<br>}<br><br>// The caller talks only to Order<br>decimal taxRate = order.GetTaxRate();</pre><p>Each class only “talks” to its direct collaborator. If the internal structure of Customer or Address ever changes, the caller of order.GetTaxRate() is unaffected.</p><h3>6. Don’t Abbreviate</h3><p>Abbreviated names might save a few keystrokes, but they force every future reader to guess at intent. Full, descriptive names make the code self-documenting.</p><pre>// Wrong: abbreviated names hide intent<br>public class Emp<br>{<br>    public string Nm { get; set; }<br>    public decimal Sal { get; set; }<br><br>    public decimal CalcAnnSal() =&gt; Sal * 12;<br>}</pre><pre>// Correct: full names make the purpose obvious<br>public class Employee<br>{<br>    public string Name { get; }<br>    public decimal MonthlySalary { get; }<br><br>    public Employee(string name, decimal monthlySalary)<br>    {<br>        Name = name;<br>        MonthlySalary = monthlySalary;<br>    }<br><br>    public decimal CalculateAnnualSalary() =&gt; MonthlySalary * 12;<br>}</pre><h3>7. Keep All Entities Small</h3><p>Small classes and methods are easier to reason about, test, and reuse. When a class grows to handle several unrelated responsibilities, it becomes a magnet for more responsibilities over time and harder to change safely.</p><pre>// Wrong: one class doing generation, formatting, saving and printing<br>public class ReportGenerator<br>{<br>    public string GenerateReport(Order order) { /* ... */ return &quot;&quot;; }<br>    public string FormatAsHtml(string report) { /* ... */ return &quot;&quot;; }<br>    public void SaveToDisk(string report) { /* ... */ }<br>    public void Print(string report) { /* ... */ }<br>}</pre><pre>// Correct: each responsibility gets its own small, focused class<br>public class ReportGenerator<br>{<br>    public string Generate(Order order) { /* ... */ return &quot;&quot;; }<br>}<br><br>public class ReportFormatter<br>{<br>    public string ToHtml(string report) { /* ... */ return &quot;&quot;; }<br>}<br><br>public class ReportSaver<br>{<br>    public void SaveToDisk(string report) { /* ... */ }<br>}<br><br>public class ReportPrinter<br>{<br>    public void Print(string report) { /* ... */ }<br>}</pre><p>Each class now has one reason to change. Testing ReportFormatter no longer requires setting up disk access or a printer.</p><h3>8. No Class with More Than Two Instance Variables</h3><p>This rule is deliberately aggressive: it forces you to notice when a class’s fields aren’t actually one cohesive concept, and to decompose them into smaller, tightly related objects rather than a class that has quietly become a bag of unrelated state.</p><pre>// Wrong: four loosely related fields on one class<br>public class Car<br>{<br>    public string Make { get; set; }<br>    public string Model { get; set; }<br>    public int Year { get; set; }<br>    public string LicensePlate { get; set; }<br>}</pre><pre>// Correct: related fields grouped into their own cohesive types<br>public class CarInfo<br>{<br>    public string Make { get; }<br>    public string Model { get; }<br>    public int Year { get; }<br><br>    public CarInfo(string make, string model, int year)<br>    {<br>        Make = make;<br>        Model = model;<br>        Year = year;<br>    }<br>}<br><br>public class LicensePlate<br>{<br>    private readonly string _value;<br><br>    public LicensePlate(string value) =&gt; _value = value;<br><br>    public override string ToString() =&gt; _value;<br>}<br><br>public class Car<br>{<br>    public CarInfo Info { get; }<br>    public LicensePlate Plate { get; }<br><br>    public Car(CarInfo info, LicensePlate plate)<br>    {<br>        Info = info;<br>        Plate = plate;<br>    }<br>}</pre><p>Car now has exactly two instance variables, and each one represents a genuinely cohesive concept rather than an arbitrary group of primitives.</p><h3>9. No Getters and Setters</h3><p>Exposing raw state through getters and setters invites external code to manipulate an object’s internals directly, which is the opposite of encapsulation. Instead, the object itself should perform the operation — a principle often summarized as “tell, don’t ask.”</p><pre>// Wrong: Balance is exposed and can be mutated by any external code<br>public class Account<br>{<br>    public decimal Balance { get; set; }<br>}<br><br>// Nothing stops this from happening anywhere in the codebase<br>account.Balance -= 1_000_000;</pre><pre>// Correct: Account owns its own data and the rules for changing it<br>public class Account<br>{<br>    private decimal _balance;<br><br>    public void Deposit(decimal amount)<br>    {<br>        if (amount &lt;= 0) throw new ArgumentException(&quot;Deposit must be positive.&quot;);<br>        _balance += amount;<br>    }<br><br>    public bool Withdraw(decimal amount)<br>    {<br>        if (amount &gt; _balance) return false;<br>        _balance -= amount;<br>        return true;<br>    }<br>}</pre><p>Now the only way to change an account’s balance is through Deposit or Withdraw, both of which enforce the account&#39;s own business rules. There&#39;s no way for external code to push the balance negative or bypass validation.</p><h3>Conclusion</h3><p>Object Calisthenics isn’t a rulebook you’re expected to follow to the letter in production code — even Jeff Bay’s original essay frames it as a deliberately extreme constraint exercise, meant to be applied to a small practice project so its underlying discipline carries over into your everyday habits. Some rules, like capping every class at two instance variables, will feel impractical if applied literally everywhere. But the value isn’t in mechanically satisfying nine checkboxes; it’s in what each rule forces you to confront: bloated methods, leaky abstractions, primitive obsession, and classes that quietly take on more responsibility than they should.</p><p>Seen this way, the nine rules aren’t a separate philosophy from SOLID — they’re a more concrete, hands-on version of it. “Keep all entities small” and “one level of indentation” are single responsibility in disguise. “One dot per line” is the Law of Demeter. “No getters and setters” is encapsulation taken seriously. Practicing with these rules, even briefly, sharpens the instinct for <em>why</em> those principles matter — which tends to matter more in a design discussion than being able to recite them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a22bd5a43a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/object-calisthenics-9-rules-to-write-cleaner-object-oriented-code-96a22bd5a43a">Object Calisthenics: 9 Rules to Write Cleaner Object-Oriented Code</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What senior engineers actually do in the first minutes of a new problem]]></title>
            <link>https://medium.com/everything-for-developers/what-senior-engineers-actually-do-in-the-first-minutes-of-a-new-problem-846df6b8c840?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/846df6b8c840</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[senior-software-engineer]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 22:53:01 GMT</pubDate>
            <atom:updated>2026-07-11T22:53:01.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h364YC446gwJYNTRH0EfvA.png" /></figure><p>When a senior software engineer gets a new problem, they don’t do what you might expect. They don’t jump to conclusions or start writing code immediately. Instead, they try to shrink ambiguity, clarify impact, and sketch a plan before they touch the implementation. The whole point is to make sure they’re solving the right problem, not just the one that looks most urgent.</p><p>In my own experience — working on large distributed systems, and dealing with real production issues — that first minutes are usually the difference between a clean fix and a messy, half-baked reaction.</p><h3>Listen, restate, and narrow the scope</h3><p>In the very first minutes, a senior engineer tries to make sure everyone is on the same page. They want the scope to be clear, and they want to know exactly what “done” means.</p><p>They’ll often restate the problem in their own words:</p><blockquote>“So what you’re saying is, notifications are delayed by up to 10 minutes for users in Europe under high load.”</blockquote><p>They’ll ask about impact:</p><blockquote>“Is this a subset of users or the whole system? Just one region? Is it affecting revenue or is it mostly annoying?”</blockquote><p>And they’ll clarify timelines:</p><blockquote>“Do we need a fix by end of day, or is a few-hour patch acceptable if we understand the root cause and can follow up later?”</blockquote><p>By doing all of this, a senior engineer ends up with a much clearer picture of the problem. They’re not just solving a vague symptom; they’re solving the actual issue that was described.</p><h3>Build a mental model of the system</h3><p>Next, they try to understand how the system works, even if it’s not their day-to-day codebase. A senior should be able to navigate through unknown territory and sketch a rough map of the system.</p><p>They’ll identify the key components:</p><blockquote>“This involves the API, the queue, the worker, and the database.”</blockquote><p>They’ll ask about the flow:</p><blockquote>“What path does a request take from user to storage to notification?”</blockquote><p>And they’ll note where the unknowns are:</p><blockquote>“I don’t know how retry logic works here, or if there’s rate limiting in place.”</blockquote><p>This is less about drawing a perfect diagram and more about building a rough map of the system. They’re trying to understand where the problem could be, and what pieces are likely relevant. Often, they’ll ask one or two targeted questions to a teammate or check existing docs to fill in gaps.</p><h3>Enumerate hypotheses and constraints</h3><p>Once they have a rough mental model, they shift to reasoning about causes and constraints.</p><p>They list hypotheses:</p><blockquote>“Possibility 1: queue backlog. Possibility 2: worker slow due to a new dependency. Possibility 3: DB lock or index issue.”</blockquote><p>They think about what’s observable:</p><blockquote>“Do we have logs, metrics, or traces that can confirm or rule out each hypothesis?”</blockquote><p>They note constraints:</p><blockquote>“We can’t restart the workers right now. We can’t change the schema. We need to preserve existing data.”</blockquote><p>This step is where first-principles and second-order thinking come in:</p><blockquote>“What’s the minimal set of things that could cause this, and what will happen if we try to fix it quickly?”</blockquote><p>They’re also starting to think about trade-offs: a quick fix might be fragile, while a robust fix might take longer. That tension is exactly what senior engineers spend most of their time navigating.</p><h3>Decide on next steps and communicate them</h3><p>In the last few minutes, they convert their thinking into action.</p><p>They choose a small set of high-value checks:</p><blockquote>“I’ll check queue depth, worker latencies, and error logs for the last hour.”</blockquote><p>They decide what to try, and what not to do:</p><blockquote>“I won’t restart anything yet; I want data first.”</blockquote><p>And they communicate their plan:</p><blockquote>“I’m going to X, Y, and Z. If I see W, I’ll do an A; if not, I’ll go for B. I’ll update everyone in 10 minutes.”</blockquote><p>This is where senior engineers show their value: they don’t just react; they create a short, clear plan and make it visible. That gives the team confidence, reduces chaos, and prevents multiple people from trying random fixes at the same time.</p><h3>Why not jump straight into code?</h3><p>The first minutes are basically the setup phase for everything that follows. If you jump straight to code, you might:</p><ul><li>Fix the symptom instead of the cause.</li><li>Make a change that breaks something else.</li><li>Waste time on a solution that doesn’t match the real constraints.</li></ul><p>Senior engineers know that good code usually comes from good problem framing. By the end of those first minutes, they’ve already done most of the thinking that prevents major mistakes later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=846df6b8c840" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/what-senior-engineers-actually-do-in-the-first-minutes-of-a-new-problem-846df6b8c840">What senior engineers actually do in the first minutes of a new problem</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP Isn’t Enough: Why PACELC Matters for Database Choice]]></title>
            <link>https://medium.com/everything-for-developers/cap-isnt-enough-why-pacelc-matters-for-database-choice-e058175a7f9e?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e058175a7f9e</guid>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 21:30:53 GMT</pubDate>
            <atom:updated>2026-07-10T21:30:53.210Z</atom:updated>
            <content:encoded><![CDATA[<p>CAP leaves some questions unanswered. It only covers partition scenarios. That’s where PACELC comes in, covering the gap and handling the “else” scenario — when there is no partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaX3rksLJ_Ivca86JqGonA.png" /></figure><h3>CAP recap</h3><p>I wrote about CAP in my previous post, so go check it out for a more detailed explanation. In summary, CAP states that when there is a partition, you need to pick between Availability or Consistency.</p><h3>What PACELC adds to the equation?</h3><p>PACELC means:</p><ul><li><strong>P</strong>: Network partition — a failure scenario where nodes get cut off from each other</li><li><strong>A/C</strong>: During a partition, the system must trade off availability against consistency, same as classic CAP</li><li><strong>E</strong>: “Else,” meaning the normal, non-partitioned operating state</li><li><strong>L/C</strong>: During normal operation, the system must trade off latency against consistency</li></ul><p>So, when there is no partition (the normal operating state), the trade-off is between Latency and Consistency. Going back to the bank payment system mentioned in my CAP article, in a normal operating state, consistency is still more important than latency, while in the social media example, latency is more important than consistency.</p><h3>Why does the “Else” matter?</h3><p>In distributed systems, replication takes time — there is a cost to it. Hence, latency vs consistency is still relevant even without failures. For example, when a transaction happens, the trade-off to be investigated is:</p><ul><li>Should I wait for all the nodes to have the latest data?<br>→ Then you are sacrificing latency.</li><li>Can I return to the client as soon as possible and replicate the data in the background?<br>→ Then you are sacrificing consistency.</li></ul><h3>Real-world database classification</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*nAYwyy7zAfL7ruv1y5GtbA.jpeg" /></figure><p>*MongoDB’s behavior depends heavily on readPreferencereadPreference configuration.</p><h3>Cassandra: AP/EL in detail</h3><p>Cassandra is fundamentally an AP system that emphasizes availability and partition tolerance, but it exposes tunable consistency so teams can dial the trade-off per operation. The core mechanic is the formula R + W &gt; N for strong consistency, versus R + W ≤ N for eventual consistency, where R and W are read/write consistency levels and N is the replication factor. A common pattern is writing at ONE for speed and reading at QUORUM, or vice versa, letting you shift a single Cassandra cluster anywhere between &quot;fast but stale&quot; and &quot;slower but consistent&quot; without changing databases.</p><h3>DynamoDB: AP/EL in detail</h3><p>DynamoDB inherits its design from Amazon’s original Dynamo paper and defaults to eventual consistency, which is why it’s the textbook AP/EL example. During normal operation, reads don’t wait for all replicas to confirm the latest write, so latency stays low, and during a partition, the system keeps accepting writes and serving reads rather than blocking. DynamoDB does offer strongly consistent reads as an option, but choosing that shifts individual operations toward the consistency side of the latency/consistency trade-off, illustrating that PACELC classification can be tuned per request rather than fixed for the whole system.</p><h3>MongoDB: the nuanced middle case</h3><p>MongoDB is the most commonly misclassified system because its behavior depends entirely on readPreference settings. With the default readPreference: primary, a minority partition simply refuses reads, which behaves like CP/EC; but if you configure readPreference: secondary, reads during a partition become available (from secondaries) at the cost of potential staleness, making it AP/EC. This flexibility is a good talking point in interviews since it shows PACELC classification isn&#39;t always a fixed label — it depends on configuration.</p><h3>Spanner: CP/EC in detail</h3><p>Spanner is the clearest CP/EC example, because it prioritizes correctness in both states rather than trading it away. Its signature mechanism is “Commit Wait,” where the system deliberately pauses each transaction based on TrueTime’s clock-uncertainty bound before confirming a commit, ensuring external consistency across globally distributed replicas. This means Spanner accepts a small, bounded latency penalty on every write during normal operation, and during a partition it will reject or stall requests in the minority partition rather than risk serving inconsistent data.</p><h3>Normal operation vs partitions</h3><p>“Normal operation” is simply when all your nodes can talk to each other without major failures — this is the state your system spends most of its time in. Here, the trade-off is purely latency vs consistency: you decide how much coordination to do before responding, based on your replication strategy, not on any failure.</p><p>A partition happens when nodes that should be able to talk suddenly can’t — the network splits into isolated groups. Partition events are rare in practice, but inevitable over a long enough timeline. In a partition, you must choose between availability (keep serving requests, risk divergence) and consistency (block or reject requests to avoid inconsistency).</p><p>Real causes of partitions include:</p><ul><li>Network switch or router failures inside a data center</li><li>Physical issues like cut or damaged cables</li><li>Cloud provider outages or regional network disruptions</li><li>Overloaded nodes that become unresponsive</li><li>Cross-region latency spikes or link failures</li></ul><p>The key point is that you cannot avoid partitions in a distributed system; you can only decide how to behave once they happen. This is why PACELC splits the model into two: one trade-off for normal operation (latency vs consistency), and another for failures (availability vs consistency).</p><h3>Practical takeaway: how to use PACELC in interviews and design docs</h3><p>In interviews, you can treat PACELC as a two-part framework that demonstrates you understand both failure behavior and normal-operation trade-offs. A strong answer is:</p><blockquote><em>“When designing this system, I’d first decide what we want during a partition: do we prioritize availability (AP) and accept stale data, or consistency (CP) and block/reject requests? Then, for normal operation, I’d choose between low latency (EL) and stronger consistency (EC). This maps directly to database choices: AP/EL systems like DynamoDB or Cassandra for high-throughput, low-latency workloads, and CP/EC systems like Spanner or CockroachDB when correctness is paramount.”</em></blockquote><p>To make this more concrete, tie it to your specific domain:</p><ul><li>If you’re building a high-cardinality metrics store or activity feed, you can argue:<br>“The system is AP/EL: during partitions we stay available and reconcile later, and during normal operation we favor low latency using eventually consistent reads.”</li><li>For financial or inventory systems, you can argue:<br>“We go CP/EC: during partitions we reject ambiguous requests, and during normal operation we accept higher latency to guarantee strong consistency.”</li></ul><p>In design docs, frame it as a clear decision checklist:</p><ul><li>Partition behavior: AP (accept divergent writes, reconcile later) vs CP (block or error to avoid inconsistency).</li><li>Normal-operation behavior: EL (favor speed, accept stale reads) vs EC (favor correctness, accept higher latency).</li><li>Selected mode: e.g., “AP/EL, using DynamoDB with eventually consistent reads for most operations, and strongly consistent reads for critical queries.”</li><li>Rationale: “This matches our business requirement of high availability and low latency, with reconciliation handles for edge cases.”</li></ul><p>This gives you a concise, structured way to talk about consistency trade-offs that shows both theoretical understanding and practical experience with real systems.</p><h3>Key takeaways</h3><ul><li>Every distributed system requires <strong>two</strong> trade-offs when it comes to databases:</li></ul><ol><li>What happens during a partition (availability vs consistency)</li><li>What happens during normal operation (latency vs consistency)</li></ol><h3>Which mode does your production database run in?</h3><p>Which mode does your production database run in — AP/EL, CP/EC, or something in between? What trade-offs have you made in your systems, and how did they evolve over time? If you had to re-architect your main store today, would you move more toward AP/EL or CP/EC, and why?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e058175a7f9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/cap-isnt-enough-why-pacelc-matters-for-database-choice-e058175a7f9e">CAP Isn’t Enough: Why PACELC Matters for Database Choice</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP Theorem: The Core Trade‑off in Distributed Systems]]></title>
            <link>https://medium.com/everything-for-developers/cap-theorem-the-core-trade-off-in-distributed-systems-3a68ccaca35f?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a68ccaca35f</guid>
            <category><![CDATA[consistency]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[cap-theorem]]></category>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[partition]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 20:16:26 GMT</pubDate>
            <atom:updated>2026-07-10T20:16:26.584Z</atom:updated>
            <content:encoded><![CDATA[<p>Whenever you design a distributed data store, CAP is the reality check that forces you to make explicit trade‑offs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6rkroxoEMZAhEMZdsZ1YQ.png" /></figure><h3>What Is the CAP Theorem?</h3><p>In database theory, the CAP theorem (also called Brewer’s theorem, after Eric Brewer) states that any distributed data store can provide at most two of the following three guarantees:</p><ul><li><strong>Consistency (C)</strong></li><li><strong>Availability (A)</strong></li><li><strong>Partition Tolerance (P)</strong></li></ul><h3>Consistency (C)</h3><p>Every read receives the most recent write or an error. In CAP terms, this means all clients see the same data at the same time, regardless of which node they connect to. For that to happen, a write to one node must be instantly forwarded or replicated to all other nodes before the write is considered successful.</p><p>Note: CAP consistency is not the same as ACID consistency in relational transactions. CAP is about <em>replicated</em> data across nodes, not about isolation levels or transactional semantics.</p><h3>Availability (A)</h3><p>Every request to a non‑failing node must eventually get a response. There’s no guarantee that the response contains the most recent write; it just has to be “some valid answer.”</p><p>This is also different from the “high availability” you hear in ops/SRE. In CAP, availability is about <em>not failing</em> when nodes are alive, even if the data is stale.</p><h3>Partition Tolerance (P)</h3><p>The system continues to operate even when the network arbitrarily drops or delays messages between nodes. In real distributed systems, partitions are inevitable, so in practice you almost always assume P and then choose between C and A when it happens.</p><p>When a partition occurs, you must decide:</p><ul><li>Cancel or delay operations → reduce availability, but keep consistency.</li><li>Proceed with operations → keep availability, but risk inconsistency.</li></ul><p>That’s the essence of CAP: <strong>when there’s a network partition, you must choose between consistency and availability.</strong></p><h3>The Core Trade‑off: What Happens During a Partition?</h3><p>Imagine a distributed database running on a cluster. Under normal conditions, every node can talk to every other node, so reads and writes can be coordinated.</p><p>A <strong>partition</strong> happens when a network failure (switch failure, cable cut, cloud‑region outage, etc.) splits the cluster into two or more groups that can’t talk to each other.</p><p>Now the system faces an unavoidable choice.</p><h3>CP: Favor Consistency, Sacrifice Some Availability</h3><p>If the system prioritizes <strong>consistency</strong> during the partition (CP behavior):</p><ul><li>Every read must return the most recent write or an error.</li><li>If nodes can’t communicate, the system:</li><li>Rejects or delays operations that can’t be safely coordinated.</li><li>Returns errors or timeouts instead of possibly stale data.</li></ul><p>From the client’s perspective, this looks like <strong>reduced availability</strong>: some requests fail or hang until the partition heals. But any successful operation is guaranteed to be consistent with the rest of the reachable system.</p><h3>AP: Favor Availability, Accept Temporary Inconsistency</h3><p>If the system prioritizes <strong>availability</strong> during the partition (AP behavior):</p><ul><li>Every request to a non‑failed node gets a response.</li><li>Reads and writes proceed independently on each side of the partition.</li><li>Replicas may diverge, so a read might not see the latest write from the other side.</li></ul><p>Clients see a highly available system — requests succeed even during the outage — but the data can be inconsistent for some time. Once the partition heals, the system reconciles updates (e.g., via version vectors, last‑write‑wins, or custom conflict resolution).</p><h3>No Partition? You Can Have Both C and A (With P)</h3><p>The CAP trade‑off only bites <strong>during a partition</strong>. When the network is healthy and all nodes can communicate, a well‑designed distributed system can provide:</p><ul><li><strong>Consistency</strong>: all clients see the same, up‑to‑date data.</li><li><strong>Availability</strong>: every request to a non‑failed node gets a response.</li><li><strong>Partition tolerance</strong>: the system is architected to survive partitions when they occur.</li></ul><p>So in normal operation, you can effectively have <strong>C + A + P</strong>. CAP forces a choice only when the network actually breaks.</p><h3>A Simple Visual</h3><p>Consider a minimal cluster with two nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUYKNiG_VgKd9TXeV_eMEQ.png" /></figure><p>Now a write arrives at Node A and a read arrives at Node B:</p><ul><li><strong>CP choice</strong>: Node B refuses to answer (or blocks) because it can’t confirm it has the latest write → consistent but less available.</li><li><strong>AP choice</strong>: Node B answers immediately, possibly with old data → available but inconsistent.</li></ul><p>This simple scenario captures the essence of CAP: once communication breaks, you must decide whether to protect correctness © or responsiveness (A).</p><h3>Short Definitions</h3><ul><li><strong>CP</strong>: Consistency + Partition tolerance. You give up availability during partitions; reads/writes may be rejected to preserve consistency.</li><li><strong>AP</strong>: Availability + Partition tolerance. You keep serving reads/writes during partitions, but accept temporary inconsistencies.</li><li><strong>CA</strong>: Consistency + Availability. Theoretical when there are no partitions; not realistic for truly distributed systems across networks. Often used to describe single‑node or tightly coupled setups where partitions are ignored.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdRloKqqyuTYAzNOhZCJww.png" /></figure><h3>Common Misunderstandings &amp; Nuances</h3><h3>“You always have to pick two”</h3><p>This is the most common mistake. You don’t permanently pick two and forget the third. In normal operation (no partition), you can have C + A + P. The “pick two” part only applies <strong>when a partition happens</strong>: you must choose between C and A.</p><h3>“NoSQL = AP, SQL = CP”</h3><p>That’s also wrong. These are not hard rules tied to technology. They’re more about <strong>configurations and trade‑offs</strong>:</p><p>Default configurations for some systems lean CP (e.g., MongoDB, PostgreSQL in strong setups). Default configurations for others lean AP (e.g., DynamoDB, Redis, Cassandra).</p><p>But you can change behavior:</p><ul><li>Tune MongoDB to be more AP‑like with lower consistency levels.</li><li>Configure Cassandra to behave more CP‑like with higher quorum requirements.</li></ul><p>So think in terms of <strong>CP‑leaning</strong> or <strong>AP‑leaning</strong> under partition, not as permanent labels.</p><h3>How CAP Relates to Other Models</h3><p>CAP captures the core trade‑off when a network partition occurs, but it doesn’t model the full range of design choices. Extensions like <strong>PACELC</strong> build on CAP by adding <em>latency</em> into the picture:</p><ul><li><strong>Without a partition</strong>: choose between <strong>Latency</strong> and <strong>Consistency</strong>.</li><li><strong>With a partition</strong>: choose between <strong>Availability</strong> and <strong>Consistency</strong> (the CAP trade‑off).</li></ul><p>This makes PACELC more practical for real system design, because it lets you reason about performance and correctness even when the network is healthy.</p><p>I’ll cover PACELC in detail in a separate article, so here it’s enough to treat CAP as a starting point, not a complete design guide.</p><h3>Real‑World Design Implications</h3><p>Before jumping into examples, it’s useful to see how CAP influences decisions:</p><ul><li>Choice of database for a given architecture</li><li>Consistency models (strong vs eventual)</li><li>Replication strategy and quorum design</li></ul><h3>Payment System Example</h3><p>Think about a bank payment system. If you design it as <strong>AP</strong>:</p><ul><li>A user’s balance might be misleading.</li><li>Someone could withdraw cash at an ATM without the balance being updated in time.</li><li>You could end up with double debits or insufficient funds going unnoticed for some time.</li></ul><p>That’s unacceptable for a bank. A payment system must prioritize <strong>strong consistency</strong> and design its databases in a <strong>CP</strong> configuration. In practice, this often means:</p><ul><li>Relational SQL databases with strong transactions.</li><li>Quorum‑based replication or consensus protocols if you go distributed.</li></ul><h3>Social Media Example</h3><p>For a social media platform:</p><ul><li>High availability is critical.</li><li>It’s acceptable if likes, comments, or follower counts are slightly delayed or inconsistent.</li></ul><p>Here, an <strong>AP</strong> configuration is more appropriate. The system stays available under failures, and inconsistencies are resolved later. This is exactly what you see in big social feeds:</p><ul><li>Counts drift, then converge.</li><li>Users see updates “soon enough,” not necessarily instantly.</li></ul><h3>Key Takeaways</h3><ul><li>CAP applies to <strong>distributed data stores</strong>.</li><li><strong>Partitions are inevitable</strong> in real systems; you must decide between C and A when they occur.</li><li>In normal operation (no partition), you can have <strong>C + A + P</strong>.</li><li>CAP is a <strong>mental model</strong> to reason about trade‑offs, not a strict label.</li><li>CAP is <strong>not tied to any specific technology</strong>; it’s about configuration and design choices.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a68ccaca35f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/cap-theorem-the-core-trade-off-in-distributed-systems-3a68ccaca35f">CAP Theorem: The Core Trade‑off in Distributed Systems</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The RU Mystery: How a Database Setting Was Quietly Costing Us 85% More Than It Should]]></title>
            <link>https://medium.com/everything-for-developers/the-ru-mystery-how-a-database-setting-was-quietly-costing-us-85-more-than-it-should-982a61e6a0ea?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/982a61e6a0ea</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[cosmosdb]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 20:44:59 GMT</pubDate>
            <atom:updated>2026-07-08T20:44:59.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uoSS4w0bf32XWS5XoBnGLg.png" /></figure><p>It started the way most infrastructure fires do: customer complaints.</p><p>Users reported that a core upload feature — one that handled large, hierarchical data structures — kept failing intermittently. No clear pattern, no obvious code bug. Just uploads that worked fine for small datasets and mysteriously choked on larger ones with a throttling error.</p><p>The initial theory was simple: we just didn’t have enough database throughput provisioned, and the fix was to throw more capacity at it. But before reaching for the “increase the limit” button, I wanted to actually understand <em>why</em> we were hitting the ceiling in the first place.</p><p><strong>Establishing a Baseline</strong></p><p>I built synthetic test scenarios that mimicked our largest real-world customers — hierarchies with 1,500 and 2,000 nodes, maxed-out configurations. Running these against the database confirmed the complaints: peak resource consumption per request was spiking to levels that blew straight past our provisioned throughput, triggering the exact throttling errors customers were seeing.</p><p><strong>Understanding How the Database Scales</strong></p><p>Before jumping to conclusions, I dug into how our database’s autoscale model actually behaves. Cosmos DB’s autoscale feature lets you set a maximum throughput ceiling, and the service automatically scales between roughly 10% and 100% of that ceiling based on real-time demand. Under the hood, Cosmos DB scales <em>horizontally</em> — distributing data and requests across partitions rather than relying on a single bigger machine — which is what allows throughput to expand elastically as load increases.</p><p>This mattered a lot for our diagnosis. Throttling errors are effectively the system telling you that demand has exceeded the configured maximum, not that the database itself is incapable of handling the load. And because autoscale billing is based on the peak throughput actually used within a given hour — scaling back down automatically when idle — raising the ceiling didn’t mean paying for capacity we weren’t using. That insight was important: it meant “just increase the max” wasn’t a wasteful stopgap, it was a legitimate lever, but it still didn’t explain <em>why</em> our requests were so expensive in the first place.</p><p><strong>Testing the Obvious Levers First</strong></p><p>I started with the usual suspects.</p><ul><li><strong>Batch size tuning:</strong> I tried inserting data in batches of 100, 50, and 25 records. Smaller batches did reduce the resource cost of each individual request, but the total resource consumption barely moved — and processing time actually got worse because we now needed far more round trips.</li><li><strong>Adding delays between requests:</strong> Next, I tested spacing requests out with 500ms and 1000ms waits. This smoothed out the instantaneous load, but at a steep cost: uploads took noticeably longer, sometimes ballooning by 10+ seconds. It solved the symptom while making the user experience worse.</li></ul><p>Neither approach addressed the root cause. They were band-aids that traded one problem for another, and neither leveraged the database’s actual scalability model in a meaningful way.</p><p><strong>The Real Culprit: Indexing</strong></p><p>The breakthrough came from stepping back and asking a different question — not “how do we spread out the load?” but “why is each request so expensive in the first place?”</p><p>The answer: the database was indexing <em>every single property</em> on every record by default. Most of that indexing was never actually used by our queries. We were paying full price to maintain indexes nobody needed, which meant every write and read was consuming far more throughput than the workload actually required.</p><p>I designed a custom indexing policy that indexed only the four fields actually used in queries — cutting out everything else.</p><p><strong>The results were dramatic:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ankPSrMfmtehMImo-EBTqA.png" /></figure><p>That’s roughly an <strong>85% reduction in resource consumption</strong> and a <strong>50% cut in processing time</strong> — without touching batch size or adding artificial delays.</p><p><strong>Bringing Scalability Back In</strong></p><p>With the indexing fix in place, the throughput math changed entirely. Instead of needing a massive ceiling just to survive spiky peak loads, we could set a much more modest, cost-efficient maximum and let autoscale handle the natural variation in demand. We ultimately landed on a throughput range that gave comfortable headroom above observed peaks — enough to absorb spikes without the system scaling all the way to expensive maximums.</p><p><strong>Validating Under Real Load</strong></p><p>Synthetic tests are one thing; production is another. I ran concurrent load tests in a pre-production environment to confirm the fix held up under realistic pressure. No throttling. No delays. The system comfortably handled load at throughput levels well above what we’d need for typical traffic, confirming that the scaling headroom we’d chosen was appropriate.</p><p><strong>The Takeaway</strong></p><p>The instinct when something breaks under load is usually to add more capacity or slow things down. Sometimes that’s the right call. But the biggest win here came from questioning a default setting nobody had scrutinized — proof that understanding <em>why</em> a system is expensive, and how its underlying scalability model actually works, often beats just paying to make it bigger.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=982a61e6a0ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/the-ru-mystery-how-a-database-setting-was-quietly-costing-us-85-more-than-it-should-982a61e6a0ea">The RU Mystery: How a Database Setting Was Quietly Costing Us 85% More Than It Should</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to approach a system design interview, step by step]]></title>
            <link>https://medium.com/everything-for-developers/how-to-approach-a-system-design-interview-step-by-step-8570786691f8?source=rss-682f8f4575d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8570786691f8</guid>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Raphael Fernandes]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 17:54:17 GMT</pubDate>
            <atom:updated>2026-07-07T17:54:17.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koidUvQDhVE7Bf7Ov2uoZQ.png" /></figure><p>Since I’ve sat on both sides of the table — being interviewed and interviewing candidates myself — I wanted to break down a structured, step-by-step approach to system design interviews that actually works under time pressure.</p><p>System design interviews are intentionally open-ended, which is exactly why they trip people up. Without a clear framework, even strong engineers ramble, run out of time, or design something that doesn’t match what the interviewer actually wanted. Having a repeatable structure turns a vague 45-minute conversation into something you can control.</p><h3>Step 1: Clarify Requirements First</h3><p>Never start designing before you understand the problem. This is the single biggest mistake candidates make.</p><ul><li>Ask about functional requirements (what should the system actually do)</li><li>Ask about non-functional requirements: latency, throughput, durability, availability</li><li>Explicitly state assumptions out loud so you and the interviewer stay aligned</li></ul><p>For example, if asked to design a chat system, clarify: Is this one-on-one or group chat? Do we need message history? Read receipts?</p><h3>Step 2: Estimate Scale</h3><p>Before you design anything, get a feel for scale — this shapes every decision you make afterward.</p><ul><li>Daily active users and growth rate</li><li>Queries per second (read vs write)</li><li>Storage and bandwidth estimates</li></ul><p>You don’t need exact numbers — rough back-of-envelope math is enough to show you’re thinking about scale intentionally.</p><h3>Step 3: Define Core APIs</h3><p>Sketch out the main endpoints your system needs, including inputs and expected outputs. This forces you to think concretely about how clients interact with your system before jumping into architecture.</p><p>Mentioning things like authentication tokens or rate-limiting keys here is a good way to signal senior-level thinking without over-engineering too early.</p><h3>Step 4: High-Level Architecture</h3><p>This is where you sketch the big picture: clients, API gateway, core services, databases, caches, and message queues. Keep it high level — just enough to show the major components and how they interact.</p><p>A typical flow might look like:</p><ul><li>Client → API Gateway → Service layer</li><li>Service layer → Database + Cache</li><li>Async work → Message queue (Kafka/SQS) for fanout or processing</li></ul><h3>Step 5: Data Model &amp; Database Design</h3><p>Decide between SQL and NoSQL based on access patterns, not habit. Sketch out your core tables or collections and how they’ll be indexed.</p><p>This is where your Cosmos DB/MongoDB experience becomes a strong talking point — explain the trade-off reasoning, not just the final choice.</p><h3>Step 6: Deep Dive Into One Component</h3><p>Interviewers often want you to go deep on one part rather than staying shallow everywhere. Pick the most interesting or bottleneck-prone component and explain it thoroughly.</p><p>For a feed system, this might mean explaining fanout-on-write vs fanout-on-read and the trade-offs between them.</p><h3>Step 7: Identify Bottlenecks &amp; Trade-offs</h3><p>Now stress-test your own design out loud.</p><ul><li>Is there a single point of failure?</li><li>What happens if a service or database node goes down?</li><li>Where would you add caching, partitioning, or replication?</li></ul><p>This step is where senior/staff-level candidates separate themselves — showing you understand trade-offs, not just happy-path design.</p><h3>Step 8: Walk Through the Happy Path, Then Edge Cases</h3><p>Explain the full flow once end-to-end (e.g., “when a user sends a message…”) before diving into failure scenarios. This keeps the conversation clear and lets the interviewer follow your reasoning easily.</p><h3>A Few Practical Tips</h3><ul><li>Treat it like a conversation, not a monologue — check in with the interviewer periodically</li><li>Don’t try to cover everything; focus depth where the interviewer shows interest</li><li>Use rough diagrams (even mental ones) to organize your thoughts before speaking</li><li>Always communicate trade-offs explicitly — don’t just state a decision, explain what you’re giving up and why it’s the right call for this context</li><li>Remember one of the software architect rules I picked up from a book: why is more important than how. Interviewers care less about the exact technology you pick and more about the reasoning behind why you picked it</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8570786691f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-for-developers/how-to-approach-a-system-design-interview-step-by-step-8570786691f8">How to approach a system design interview, step by step</a> was originally published in <a href="https://medium.com/everything-for-developers">The Distributed Mind</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>