<?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 Huang Yu Ti on Medium]]></title>
        <description><![CDATA[Stories by Huang Yu Ti on Medium]]></description>
        <link>https://medium.com/@huangyudi?source=rss-ad8b27291ba0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Br6VlJfJBTxggi4B.</url>
            <title>Stories by Huang Yu Ti on Medium</title>
            <link>https://medium.com/@huangyudi?source=rss-ad8b27291ba0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:15:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@huangyudi/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[PostgreSQL Optimization for Backend Engineers]]></title>
            <link>https://huangyudi.medium.com/postgresql-optimization-for-backend-engineers-1fae886214fc?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fae886214fc</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[explain-analyze]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 01:45:56 GMT</pubDate>
            <atom:updated>2026-01-25T01:45:56.281Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve all been there: A feature works perfectly in the development environment. It’s snappy, instant, and clean. Then, you deploy to Production. As the data volume grows, that 200ms page load creeps up to 2 seconds, 5 seconds, and eventually starts timing out.</p><p>When this happens, the knee-jerk reaction for many developers is: Maybe I should add an index? So, they sprinkle a few indexes on random columns. Sometimes it works; often it doesn’t.</p><p>SQL optimization shouldn’t be a game of Guesswork or trial-and-error. There is a distinct set of physical laws behind in. In this post, I want to share the mental model for SQL performance — moving from blindly trying fixes to surgically optimizing your queries in SQL.</p><h3>The optimization priority pyramid</h3><p>When you encounter a slow query, stop and access it through these three layers. This hierarchy helps you filter out the noise:</p><ul><li>Access Path(The critical layer): How is SQL finding the data? Is it using a map(index), or is it reading every single page of the book(sequential scan)?</li><li>Frequency: How often are you asking?(The N+1 query)</li><li>Data payload: Are you hauling unnecessary data across the wire?</li></ul><p>Let’s dive into the most misunderstood technical aspect: indexes</p><h3>The physics of indexing: The Phone Book Theory</h3><p>To understand why an index fails, you need to visualize a standard B-Tree Index. Think of it exactly like a Phone Book sorted by Last Name, then First Name.</p><p>Imagine we have a composite index: [:last_name, :first_name]</p><h4>The left-most prefix rule</h4><p>Because the book is sorted primarily by last_name :</p><ul><li>Scenario A: You want to find everyone with the last name Smith : <br>✅ Index Effective. You jump straight to the S section.</li><li>Scenario B: You want to find John Smith<br>✅ Index Effective. You jump to Smith , then look for John</li><li>Scenario C: You want to find everyone named John (ignore the last name)<br>❌ Index failed. The phone book is not sorted by first name. You can’t jump to John . You must read every single entry in the book to find the Johns. In SQL, this is called Sequential Scan.</li></ul><p>In Rails, if you define add_index :users, [:last_name, :first_name] but your query is User.where(first_name: &#39;John&#39;) , that index is useless.</p><h4>The golden rule of column order</h4><p>Based on the physics, the order of columns in your composite index matters. A good rule of thumb for ordering columns is:</p><ul><li>Equality: Columns used in strict Where x = ? clauses.</li><li>Selectivity: Columns that filter out the most data should come before low-cardinality columns</li><li>Range: Columns used in ranges should go last.</li></ul><h4>The 3 most common performance traps</h4><p>Once you understand the physics, watch out for these implementation patterns that kill performance:</p><ul><li>The function Trap:<br>This is the most common reason for index failure in valid queries.<br>❌ User.where(&#39;EXTRACT(YEAR FROM created_at) = ?&#39;, 2023) when you wrap a column in a function, SQL must calculate that value for every single row. The standard B-Tree index on created_at cannot be used.<br>✅ User.where(created_at: Time.zone.parse(&#39;2023-01-01&#39;).all_year) This is a range query. SQL uses the index to instantly find the start and end points of that date range.</li><li>The Greedy SELECT * with jsonb<br>SQL handle large text and jsonb columns efficiently using a technique called TOAST , but fetching them still consumes I/O and memory. If you don’t need the heavy JSON blob for the list view, don’t ask for it.</li><li>The hidden Loop(N+1)<br>This is a application architecture error, common in Rails<br>User .includes(:profile) to turn 11 queries into 2.</li></ul><pre>users = User.limit(10)<br>users.each do |user|<br>  puts user.profile.bio<br>end</pre><h3>Verification: How to read EXPLAIN analyze</h3><p>Don’t guess — ask the database. In the Rails console, you can inspect the plan. For SQL, EXPLAIN ANALYZE is your best friend because it actually runs the query and gives you real timing.</p><pre>puts User.where(email: &#39;test&#39;).explain</pre><p>Look for these keywords in the output:</p><ul><li>Seq Scan<br>- Meaning: Sequential scan. The DB is reading the table from top to bottom.<br>- Action: Unless the table is tiny, you likely need an index.</li><li>Index Scan or Bitmap Heap Scan <br>- Meaning: it’s using the index</li><li>Filter vs Index Cond <br>- If you see a lot of rows being removed by a filter after the can, your index might not be specific enough(low selectivity)</li></ul><h3>Conclusion</h3><p>SQL optimization is not about memorizing syntax; it’s about understanding the physics of you database.</p><p>Remember the three layers of our pyramid:</p><ul><li>Access Path: Are you helping SQL find the needle or making it search the haystack?</li><li>Frequency: Are you asking once, or asking 1,000 times?</li><li>Payload: Are you carrying a backpack or a truckload?</li></ul><p>The next time you see a slow query, don’t just throw an index at it and hope for the base. Use EXPLAIN ANALYZE , visualize the B-Tree, and engineer a solution that lasts. Stop guessing, and start measuring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fae886214fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance vs Composition]]></title>
            <link>https://huangyudi.medium.com/inheritance-vs-composition-61d17b9f6b14?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d17b9f6b14</guid>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 19:23:23 GMT</pubDate>
            <atom:updated>2026-01-15T19:23:23.620Z</atom:updated>
            <content:encoded><![CDATA[<p>In OOP, we essentially have two ways to reuse code:</p><ul><li>Inheritance( Is-A ): Creating a specialized version of an existing class</li><li>Composition( Has-A ): Assembling an object from smaller, independent parts</li></ul><p>For many Rails developers, inheritance is the default hammer because frameworks like ActiveRecord rely on it heavily. However, relying exclusively on inheritance can lead to rigid structures, while relying exclusively on composition can lead to excessive boilerplate.</p><p>The mark of a senior engineer isn’t choosing one over the other — it is knowing exactly which trade-off to accept.</p><h3>The case for inheritance(Is-A)</h3><p>Inheritance is powerful when you are defining a strict Core indentity . It works best when the child class is a true specialization of the parent and shares the same underlying structure.</p><p>The ticketing system:</p><pre>class Ticket<br>  # THE TEMPLATE: The parent strictly controls the calculation flow.<br>  # This guarantees consistency across all ticket types.<br>  def final_price<br>    base_price * multiplier<br>  end<br><br>  # Hook methods (Defaults)<br>  def base_price<br>    100<br>  end<br><br>  def multiplier<br>    1.0<br>  end<br>end<br><br>class VipTicket &lt; Ticket<br>  def base_price<br>    150 # Specialization: VIPs have a different base<br>  end<br>end<br><br>class StudentTicket &lt; Ticket<br>  def multiplier<br>    0.8 # Specialization: Students have a different multiplier<br>  end<br>end</pre><h4>Where inheritance shines</h4><ul><li>Enforced structure: The Ticket parent guarantees that every subclass calculates final_price exactly the same way</li><li>Simplicity: It requires very little code to create a new type</li><li>Explicit identity: When you see VipTicket , you immediately know what it is and where it fits in the hierarchy</li></ul><h4>Where inheritance breaks down</h4><p>The limitation of inheritance is that it is single-dimensional.</p><p>What happens if we have a VIP student ?</p><ul><li>We can’t inherit from both VipTicket and StudentTicket</li><li>We are forced to create a new class VipStudentTicket that manually duplicates logic from both.</li></ul><p>If we add a Holiday variable, we force combinatorial explosion: HolidayVipStudent , HolidayStudent , HolidayVipStudent</p><p>Inheritance struggles when you need to mix and match multiple orthogonal features.</p><h3>The case for Composition (Has-A)</h3><p>Composition takes a different approach. Instead of defining what an object is, it defines what an object has. We treat the Ticket as a container that holds a collection of rules.</p><p>Instead of creating new classes for every combination, we create small, independent rules and stack them together.</p><pre># Independent Logic Blocks (Strategies)<br>class VipRule<br>  def apply(price)<br>    price * 1.5<br>  end<br>end<br><br>class StudentRule<br>  def apply(price)<br>    price * 0.8<br>  end<br>end<br><br>class HolidayRule<br>  def apply(price)<br>    price - 10<br>  end<br>end<br><br># The Container<br>class Ticket<br>  attr_accessor :rules<br><br>  def initialize(rules = [])<br>    @rules = rules<br>  end<br><br>  def price(base_price)<br>    # The container doesn&#39;t know the logic.<br>    # It simply pipes the data through the rules it &quot;has&quot;.<br>    @rules.reduce(base_price) do |current_price, rule|<br>      rule.apply(current_price)<br>    end<br>  end<br>end</pre><h4>Where composition shines</h4><ul><li>Dynamic flexibility: We can combine logic at runtime without defining new classes.</li></ul><pre># VIP + Student + Holiday<br>ticket = Ticket.new([VipRule.new, StudentRule.new, HolidayRule.new])</pre><ul><li>Separation of concerns: StudentRule knows nothing about Ticket . It can be reused for Popcorn or Merchandise</li><li>No explosion: We only have 3 rule classes, yet we can create infinite combinations</li></ul><h4>Where composition break down</h4><ul><li>Lack of structure: Unlike the inheritance example, there is no ‘Template’ guaranteeing how the price is calculated. The flow depends entirely on how the rules are stacked</li><li>Mental overhead: To understand what a specific ticket object does, you can’t just look at its class name. You have to inspect its rules array at runtime</li><li>Boilerplate: You often need to write more code to make the parts work together.</li></ul><h3>How to choose</h3><p>Neither approach is universally ‘better’. They solve different problems.</p><h4>Use inheritance when:</h4><ul><li>The model is static: A User is always a User , they rarely transform into a Product</li><li>The hierarchy is shallow: One or two levels of depth</li><li>You need to White-Box reuse: You specifically want the children to depend on the parent’s internal implementation</li></ul><h4>Use composition when:</h4><ul><li>The logic is dynamic: Rules change based on context</li><li>You have Cross-Cutting concerns: Features that need to be shared across unrelated classes</li><li>You face combinatorial explosion: You find yourself creating classes name A_with_B_and_C</li></ul><h3>Conclusion</h3><p>Inheritance is about Classification . Composition is about Assembly .</p><p>If you are building the core backbone of your application, inheritance provides a solid, explicit structure. But when you start adding business rules that need to be mixed and matched, composition offers the flexibility you need to keep your system clean.</p><p>The best systems usually employ a heathy mix of both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d17b9f6b14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Duck typing in Rails]]></title>
            <link>https://huangyudi.medium.com/duck-typing-in-rails-57d77dc8f112?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/57d77dc8f112</guid>
            <category><![CDATA[duck-typing]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 16:49:21 GMT</pubDate>
            <atom:updated>2026-01-15T16:49:21.742Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>If it walks like a duck and quacks like a duck, it’s a duck.</blockquote><p>If you have been writing Rails for a while, you are likely using <strong>Duck Typing </strong>every single day, perhaps without even realizing it.</p><p>Think about the link_to helper. You can pass it a User object, a Post object, or even Comment object. Rails doesn’t check the class name, it simply asks: “Do you behave like a resource?” and “Can I turn you into a route?”</p><p>However, while we consume this flexibility in Rails, we often forgot to apply it to out own business logic. Instead of designing flexible interfaces, we retreat to strict type checking.</p><p>Let’s learn how we can use the Duck Type in our own services.</p><h3>The Trap of Identity Check</h3><p>There is a common feature: Exporting Reports.</p><p>The origin Code:</p><pre>class ReportService<br>  def export(data, format)<br>    if format == &#39;pdf&#39;<br>      generator = PdfGenerator.new<br>      # We know exactly who this is, so we call its specific method<br>      generator.render_pdf(data) <br>    elsif format == &#39;csv&#39;<br>      generator = CsvExporter.new<br>      # Different class, different method name<br>      generator.create_csv(data) <br>    elsif format == &#39;html&#39;<br>      generator = HtmlBuilder.new<br>      # Another different name<br>      generator.build(data)      <br>    end<br>  end<br>end</pre><p>Reflecting on the pattern:</p><ul><li>Inconsistency: Every class has a different method name( render_pdf , create_csv , build ). The service has to memorize them all.</li><li>High maintenance: If we want to add an Excel export, we have to modify the ReportService class.</li><li>Micro-management: The service knows too much about the specific classes implementation.</li></ul><h4>Embracing Duck Type</h4><p>To fix this, we simply need to agree on a contract</p><p>Let’s decide that any object capable of exporting data must implement a method called export(data)</p><blockquote>I don’t care who you are, I only care what you can do</blockquote><h4>The Trusting Code</h4><p>First, we define our Ducks . They are completely unrelated classes, but that speak the same language:</p><pre>class PdfGenerator<br>  def export(data)<br>    # Logic to generate PDF...<br>    &quot;PDF Generated&quot;<br>  end<br>end<br><br>class CsvGenerator<br>  def export(data)<br>    # Logic to generate CSV...<br>    &quot;CSV Generated&quot;<br>  end<br>end<br><br>class HtmlGenerator<br>  def export(data)<br>    # Logic to generate HTML...<br>    &quot;HTML Generated&quot;<br>  end<br>end</pre><p>Now, look at how the Service transforms:</p><pre>class ReportService<br>  def generate(data, generator)<br>    # We don&#39;t ask &quot;Are you a PDF generator?&quot;<br>    # We just tell it: &quot;Export this.&quot;<br>    # We trust that the object responds to &quot;export&quot;.<br>    generator.export(data)<br>  end<br>end</pre><p>Moving to the style brought three major improvements to daily work:</p><ul><li>Zero dependencies(decoupling): The ReportService no longer cares if you pass in a PDF generator, a CSV generator, or something completely new. It only knows that it can call export . This makes the code incredibly loose and flexible.</li><li>Painless testing: This is my favorite part. Because the Service doesn’t check for specific classes(like is_a? ), I don’t need to mock complex libraries in my unit tests. I can just create a “Fuck Duck”.</li><li>Open/Closed Principle: If my manager ask for a “XML Export”, I don’t need to touch the ReportService code at all. I simply create an XMLGenerator class with an export method and pass it in. The system is <strong>open for extension, but closed for modification</strong>.</li></ul><h3>Conclusion</h3><p>Duck typing isn’t just a feature of Ruby, it’s a mindset. It encourages us to design <strong>roles</strong>, not types.</p><p>When we stop worrying about “what” an object is and start focusing on “how” it behaves, our code becomes simpler, easier to test, and much more fun to write.</p><p>We don’t need a strict family tree to work together. We just need to speak the same language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57d77dc8f112" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Sending Messages shifted my perspective]]></title>
            <link>https://huangyudi.medium.com/how-sending-messages-shifted-my-perspective-f23c5da5a10b?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f23c5da5a10b</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 19:24:44 GMT</pubDate>
            <atom:updated>2026-01-10T19:24:44.010Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of us hit a plateau after years of working with Ruby on Rails. While we use classes and objects every day, it is easy for out application to remain procedural under the hook. I noticed this is my own code: logic often felt rigid, and services became cluttered with conditional checks, missing out on the clarity that Object-Oriented design offers.</p><p>The turning point for me wasn’t learning a new gem. It was revisiting a fundamental concept at the heart of Ruby: <strong>The difference between calling methods and sending messages.</strong></p><h3>A different perspective: Command vs. Request</h3><p>Coming from static languages, it is natural to think of object.method() as direct command. However, Ruby offers a different perspective. When we write user.save , we can think of it as <strong>sending a message </strong>(:save) to the object.</p><ul><li>The Procedural Approach: We control the flow, checking the object’s internal state and making decision for it.</li><li>The Message-base Approach: We trust the object, sending a request and letting the receiver handle the implementation details.</li></ul><p>This shift in thinking leads to an architectural style often referred to as <strong>Tell, Don’t Ask</strong></p><h3>The challenge of Asking</h3><p>Let’s look at a common scenario: Applying a coupon</p><p>A common pattern involves a Service Object that acts as a <strong>Micromanager</strong>. It asks the coupon for its data, check its validity, and then perform the calculation.</p><pre># app/services/apply_coupon_service.rb<br>class ApplyCouponService<br>  def perform(order, coupon)<br>    # 1. Checking Expiry (Asking for private details)<br>    # The Service is reaching inside the coupon to check the date.<br>    if coupon.expired_at &amp;&amp; coupon.expired_at &lt; Time.current<br>      return { success: false, message: &#39;Coupon expired&#39; }<br>    end<br><br>    # 2. Checking Usage Limit (Asking again)<br>    # The Service is managing the logic of what &quot;out of stock&quot; means.<br>    if coupon.usage_limit &gt; 0 &amp;&amp; coupon.used_count &gt;= coupon.usage_limit<br>      return { success: false, message: &#39;Coupon fully redeemed&#39; }<br>    end<br><br>    # 3. Calculating Discount (Asking about the type)<br>    if coupon.category == &#39;fixed&#39;<br>      order.total_price -= coupon.amount<br>    elsif coupon.category == &#39;percentage&#39;<br>      discount = order.total_price * (coupon.amount / 100.0)<br>      order.total_price -= discount<br>    end<br><br>    order.save<br>  end<br>end</pre><p>Reflecting on the pattern:</p><ul><li>Leaking Logic: The definition of ‘validity’ (dates, limits), is leaked into the Service. If we use coupon in another place, we have to copy-paste these check.</li><li>Coupling: The Service needs to know exactly how each coupon type calculates its discount.</li></ul><h3>Exploring Telling with STI</h3><p>By embracing the <strong>Message</strong> mindset, w can delegate these responsibility back to Coupon model. The service shouldn’t need to know why a coupon is invalid or how it calculates math.</p><p>We can use Rails’ STI to handle the different calculation strategies.</p><pre># app/models/coupon.rb<br>class Coupon &lt; ApplicationRecord<br>  # Encapsulating the state check<br>  # The outside world simply asks: &quot;Are you usable?&quot;<br>  def usable?<br>    !expired? &amp;&amp; !out_of_stock?<br>  end<br><br>  # Defining a common interface for STI subclasses<br>  def calculate_discount(total_amount)<br>    raise NotImplementedError<br>  end<br><br>  private<br><br>  def expired?<br>    expired_at &amp;&amp; expired_at &lt; Time.current<br>  end<br><br>  def out_of_stock?<br>    usage_limit &gt; 0 &amp;&amp; used_count &gt;= usage_limit<br>  end<br>end</pre><pre>class FixedCoupon &lt; Coupon<br>  def calculate_discount(total_amount)<br>    amount<br>  end<br>end<br><br>class PercentageCoupon &lt; Coupon<br>  def calculate_discount(total_amount)<br>    total_amount * (amount / 100.0)<br>  end<br>end</pre><pre># app/services/apply_coupon_service.rb<br>class ApplyCouponService<br>  def perform(order, coupon)<br>    # Step 1: Tell the coupon to check itself<br>    unless coupon.usable?<br>      return { success: false, message: &#39;Coupon is not valid&#39; }<br>    end<br><br>    # Step 2: Tell the coupon to calculate<br>    # We don&#39;t care if it is Fixed or Percentage.<br>    discount = coupon.calculate_discount(order.total_price)<br>    <br>    order.total_price -= discount<br>    order.save<br>  end<br>end</pre><h3>Why This Approach Resonated with me</h3><p>Adopting <strong>Message Passing </strong>helped me evolve from writing instructions to designing interactions between objects.</p><ul><li>Cohesion: The rules about expiry and usage limits now live inside the Coupon , where they belong</li><li>Flexibility: Because we use STI, Rails automatically instantiates the correct class. We can add new coupon types without touching the Service</li><li>Readability: The code reads like conversation: “Are you usable? If so, give me the discount”</li></ul><h3>Conclusion</h3><p>Writing Object-Oriented Ruby is less about writing strict intructions and more about designing a conversation.</p><p>When we stop micromanaging our objects and start trusting them to handle their own responsibilities, the code naturally becomes cleaner and more expressive. It shifts the focus from ‘How do I do this?’ to ‘Who should be responsible for this?’</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23c5da5a10b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Use hey]]></title>
            <link>https://huangyudi.medium.com/why-you-should-use-hey-0bdc99105489?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bdc99105489</guid>
            <category><![CDATA[hey]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 19:22:02 GMT</pubDate>
            <atom:updated>2026-01-05T19:22:02.278Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a simply question you should always ask:</p><blockquote>Does this endpoint behave normally under a bit of pressure?</blockquote><p>This is where hey belongs.</p><h3>What hey is?</h3><p>hey is a minimal HTTP load generator.</p><p>It is designed to be:</p><ul><li>Easy to turn</li><li>Easy to understand</li></ul><p>You don’t need to learn a configuration language.</p><p>You don’t need to think about threads or event loops.</p><p>You run a command, and you get feedback.</p><h3>How to use hey</h3><p>Here are the 6 most common ways you will use hey in your daily workflow.</p><ul><li>The Quick Pulse check<br>Goal: You just deployed a new feature and want to ensure the page or api loads quickly under a small amount of load.</li></ul><pre>hey https://www.your-website.com/<br># The default settings (200 requests, 50 works)</pre><ul><li>The stress test(Heavy load)<br>Goal: You want to see if your database crashes when 100 users hit the site exactly at the same time.</li></ul><pre># Simulate 100 concurrent users sending 2000 requests total<br>hey -n 2000 -c 100 https://www.your-website.com/<br># c is the number of workers, n is the total number of requests</pre><ul><li>The time-boxes test<br>Goal: You want to monitor your server logs(or CPU usage) while traffic is hitting the system for a specific amount of time(e.g. 30s). You don’t care about the total number of requests.</li></ul><pre># Hammer the server for 30 seconds straight<br>hey -z 30s https://www.your-website.com/</pre><ul><li>Testing APIs(post json)<br>Goal: Most modern web development involves APIs. You need to test a POST endpoint that accepts JSON data.</li></ul><pre>hey -m POST \<br>    -d &#39;{&quot;item_id&quot;: 123, &quot;quantity&quot;: 1}&#39; \<br>    -T &quot;application/json&quot; \<br>    https://api.yourshop.com/cart/add</pre><ul><li>Testing with Authentication<br>Goal: Your API is protected. You need to simulate a logged-in user.</li></ul><pre>hey -H &quot;Authorization: Bearer YOUR_ACCESS_TOKEN&quot; \<br>    -H &quot;User-Agent: Test-Bot&quot; \<br>    https://api.yourshop.com/profile</pre><ul><li>Throttled requesting(Rating limiting)<br>Goal: You don’t want to crash the server, you just want to generate a steady stream of traffic to test your own rate-limiter logic.</li></ul><pre># Limit to 5 requests per second per worker<br>hey -q 5 https://www.your-website.com/</pre><h3>How to read the output</h3><h4>The Summary</h4><pre>Summary:<br>  Total: 5.0045 secs<br>  Slowest: 1.2405 secs<br>  Fastest: 0.0081 secs<br>  Average: 0.0342 secs<br>  Requests/sec: 890.15<br><br>Requests/sec is your score. Higher is better. It means your server handled<br>356 requests every seconds.</pre><h4>The Histogram</h4><pre>Response time histogram:<br>  0.009 [1] |<br>  0.022 [85] |■■■■■■■■■■■■■■■■■■■■■■■■■■■<br>  0.034 [87] |■■■■■■■■■■■■■■■■■■■■■■■■■■■■<br>  0.135 [2] |■2<br><br>The Shape: you want a tight cluster near the top(fast)<br>The Tail: If you see bars at the bottom, those are &#39;slow outliers&#39;.<br>Even if your avarage speed is fast, these outliers frustrate users.</pre><h4>Latency Distribution</h4><p>For normal static web:</p><ul><li>Excellent: &lt; 100ms</li><li>Good: 100ms ~ 300ms</li><li>Mid/Average: 300m ~ 1s</li><li>Danger: &gt; 1s</li><li>Critical: &gt; 3s</li></ul><pre>Latency distribution:<br>  10% in 0.0150 secs<br>  95% in 0.0487 secs<br>  99% in 0.1265 secs<br><br>95%: It means &#39;95% of your users saw a page load faster than 0.04s&#39;<br>99%: If this number is wildly higher than your 95%, then you have a specific<br>     bottlenect affecting a small number of unlucky users</pre><p>It means ‘95% of your users saw a page load faster than 0.04s’.</p><p>But, if your Latency distribution like this:</p><pre>Response time histogram:<br>  0.050 [100] |■■■■■<br>  ...<br>  1.000 [50]  |■■       &lt;-- This gap is bad<br>  5.000 [5]   |■        &lt;-- Extreme outliers<br></pre><p>It means your server performs well <em>usually</em>, but occasionally locks up completely.</p><h4>Status code distribution</h4><pre>Status code distribution:<br>  [200] 950 responses<br>  [500] 40 responses   &lt;-- DANGER (Server Error)<br>  [502] 10 responses   &lt;-- DANGER (Gateway Error / Restarting)</pre><h4>Error Distribution</h4><p>If you server is perfect, this section won’t even appear. If you see this section, something failed. hey groups errors by type.</p><pre>Error distribution:<br>  [25] Get &quot;http://localhost/&quot;: dial tcp [::1]:80: connect: connection refused<br>  [10] Get &quot;http://localhost/&quot;: context deadline exceeded<br><br>or for HTTP errors:<br>Status code distribution:<br>  [200] 480 responses<br>  [500] 15 responses<br>  [502] 5 responses</pre><h3>Why should you use hey?</h3><ul><li>Before launch, run a stress test to guess how many users your server can hold.</li><li>After refactoring, if you rewrite a function to make it ‘faster’, run hey before and after to prove it.</li><li>Debugging latency, if users complain ‘the site slow sometimes’, run hey and look at the Histogram . If the histogram is spread out, your performance is inconsistent.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bdc99105489" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nginx — Basic setting]]></title>
            <link>https://huangyudi.medium.com/nginx-024e0220401a?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/024e0220401a</guid>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 14:24:57 GMT</pubDate>
            <atom:updated>2026-01-04T15:44:14.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Nginx is often described simply as a “Web server”, but that description significantly understate its role in modern infrastructure. In practice, Nginx is a high-performance traffic manager that sits as the front of countless production systems, quietly handling concurrency, routing, and reliability at scale.</p><h3>Core Architecture: Event-Driven and Non-blocking</h3><p>At a high level, Nginx consists of:</p><ul><li>One master process, responsible for configuration and worker management</li><li>Multiple worker processes, responsible for handling client requests</li></ul><p>Each worker run a single-threaded event loop. Rather than blocking while waiting for I/O(such as network or disk operations), the worker registers events and continues processing other connections.</p><p>The result:</p><ul><li>One worker can handle thousands of concurrent connections</li><li>Memory usage remains stable under load</li><li>Performance degrades predictably instead of collapsing</li></ul><h3>Nginx configs</h3><p>Nginx configs work like Russian nesting dolls. Settings “inherit” downwards.</p><ul><li>http {...} : Universal rules. If you set gzip on; here, every site you host uses it.</li><li>server {...} : Represents one website (e.g domain or ip)</li><li>location {...} : Specific instructions for a specific URL path (e.g /images/ or /api/...)</li></ul><h3>The Routing Logic</h3><p>When a request comes in, Nginx doesn’t just read your configs top-to-bottom. It uses a specific priority algorithm to choose which location {} block handles the request. This is where 90% of bugs happen.</p><p>The order of operations:</p><ul><li>Exact match = : Stop searching, this is it</li><li>Prefix match ^~ : This is the best prefix, stop searching</li><li>Regex match ~ or ~* : Analyzed in order of appearance</li><li>Standard Prefix / : The fallback (Catch all)</li></ul><pre>location = /images/logo.png { <br>    # Priority 1: Only matches this EXACT file. Very fast.<br>}<br><br>location ^~ /images/ { <br>    # Priority 2: Matches /images/anything. Nginx stops checking Regexes here.<br>}<br><br>location ~ \.(png|jpg)$ {<br>    # Priority 3: Matches any image ending in .png or .jpg<br>}<br><br>location / {<br>    # Priority 4: The Catch-All. Matches everything else.<br>}</pre><h3>Nginx for static web</h3><pre>server {<br>    root /var/www/my-react-app/dist;<br>    <br>    location / {<br>        # The Magic Line:<br>        # 1. Try to find the exact file ($uri)<br>        # 2. Try to find the directory ($uri/)<br>        # 3. If neither exists, fallback to index.html (Client-side routing takes over)<br>        try_files $uri $uri/ /index.html;<br>    }<br>}</pre><h3>Nginx for the Reverse Proxy</h3><pre>server {<br>    listen 80;<br>    server_name api.example.com;<br><br>    location / {<br>        proxy_pass http://localhost:3000;<br>        <br>        # CRITICAL: Forward the headers<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        <br>        # WebSocket support (for socket.io)<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>    }<br>}</pre><h3>Advanced settings</h3><h4>DDoS Protection</h4><p>The nginx is an excellent first line of defense against flood attacks. We can use the “Leaky Bucket” algorithm to handle this.</p><pre># HTTP CONTEXT<br># Create a memory zone &#39;api_limit&#39; (10MB) allowing 10 requests/sec per IP<br>limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;<br><br># Limit connections: Max 10 simultaneous open connections per IP<br>limit_conn_zone $binary_remote_addr zone=addr_limit:10m;<br><br># SERVER CONTEXT<br>server {<br>    location /api/ {<br>        # Apply Connection Limit<br>        limit_conn addr_limit 10;<br><br>        # Apply Rate Limit<br>        # burst=20: Allow a spike of 20 requests<br>        # nodelay: Process the burst INSTANTLY (good UX), but enforce the rate over time.<br>        limit_req zone=api_limit burst=20 nodelay;<br>    }<br>}</pre><h4>Kill Slow Connection</h4><pre># Prevents slowloris attacks<br>client_body_timeout 10s;</pre><h4>Enable Gzip</h4><pre># Reduces bandwidth<br>gzip on; gzip_types text/css application/json;</pre><h4>Cache assets file</h4><pre># Match common static file extensions (case-insensitive)<br>location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg)$ {<br>    # 1. Tell browser to keep it for 30 days<br>    expires 30d;<br><br>    # 2. Privacy &amp; Compression Control<br>    # &#39;public&#39;: Proxies (like CDNs) can also cache this.<br>    # &#39;no-transform&#39;: Don&#39;t let mobile operators compress images badly.<br>    add_header Cache-Control &quot;public, no-transform&quot;;<br><br>    # 3. Turn off logging for these files to save disk space<br>    access_log off;<br>}</pre><p>By the way, the HTTP headers are the only thing that matters to the browser, we can also set the Cache from the application.</p><p>You might think: Can&#39;t I just set the Cache-Control headers in my application?</p><p>Technically, yes. But in a proper Nginx setup, your application code never runs for statics files.</p><p>While Nginx receices a requst for /image.jpg , it checks the disk first. If the file exists, Nginx sends it immediately(using sendfile) and marks the request as completed.</p><p>Also, you shouldn’t let Rails handle the assets file, even thought it’s just a simple logo.png , the request still has to travel through the entire Rack Middleware stack in rails.</p><h3>Conclusion: The Gatekeeper of Your Infrastructure</h3><p>We have seen that Nginx is more than just a web server, it an efficient manager that sits between your users and your code. By offloading static files, and compression to Nginx, you free up your application to focus on what it does best: business logic.</p><p>Whether you are protecting against DDos attacks with rate limiting or speeding up assets with cache headers, a well-tuned Nginx config is the cheapest perforemance upgrade you can give your infracture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=024e0220401a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When is the right time to use SOLID?]]></title>
            <link>https://huangyudi.medium.com/when-is-the-right-time-to-use-solid-9a9a3052ac79?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9a3052ac79</guid>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 19:38:40 GMT</pubDate>
            <atom:updated>2025-12-13T19:38:40.246Z</atom:updated>
            <content:encoded><![CDATA[<p>The SOLID principles are powerful. They improve maintainability, reducing coupling, and make change safer.</p><p>However, like any tool, timing matter.</p><p>Used too early, SOLID can increase complexity, slow development, and force you to maintain abstractions and interfaces that turn out to be wrong.</p><p>Used at right time, it can save you months of refactoring and pain.</p><p>So, the key question is not whether SOLID is good, but when it is actually need.</p><h3>The real cost of using SOLID too early</h3><p>Early in a project, requirements are uncertain:</p><ul><li>you don’t yet know how the system will evolve</li><li>You don’t know which behaviors will vary</li><li>You don’t know which parts will need to be extended</li></ul><p>If you introduce interfaces, abstractions and dependency inversion before these forces are visible, you often end up with:</p><ul><li>Interfaces with only one implementation</li><li>Abstractions that reflect guesses, not reality</li><li>Extra indirection that makes code harder to read</li><li>Time spent designing structures that later delete</li></ul><p>That is not ‘Clean Architecture’, it is <strong>speculative design</strong>.</p><h3>Better approach:</h3><ul><li>First time you need something<br>Write it concretely. No interfaces, no abstractions. Just solve the problem clearly.<br>Your goal here is correctness and clarity, not flexibility.</li><li>Second time (duplication appears)<br>Copy paste. At this stage, you’re learning what is actually similar. And you’re seeing what might change and what stays the same. And you’re gathering real data, not guessing.</li><li>Third time<br>Refactor using the relevant SOLID principles.<br>Now, you will have evidence:<br>- You know what changes<br>- You know what stays stable<br>- You know where extension is required<br>The abstractions now reflect real requirements — not guesses.</li></ul><p>This approach helps you:</p><ul><li>Avoid premature abstraction</li><li>Keep early code simple and readable</li><li>Apply SOLID where it provides actual value</li><li>Design based on real requirements, not assumptions</li></ul><p>Most importantly, it keeps your focus where it should be early on:</p><blockquote>Solving the problem, not designing frameworks.</blockquote><p>SOLID is not a starting point. It’s a refinement tool.</p><p>Let your code grow naturally.</p><p>When the pain appears repeatedly, SOLID tell you how to fix it — not when to start.</p><p>Use SOLID <strong>when the problem asks for it</strong>, not when the tutorial tells you to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9a3052ac79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lock in Rails]]></title>
            <link>https://huangyudi.medium.com/lock-in-rails-db11be57d0bd?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/db11be57d0bd</guid>
            <category><![CDATA[pessimistic-locking]]></category>
            <category><![CDATA[optimistic-locking]]></category>
            <category><![CDATA[locks]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 16:34:10 GMT</pubDate>
            <atom:updated>2025-12-08T16:34:10.686Z</atom:updated>
            <content:encoded><![CDATA[<h3>What does lock mean in Rails?</h3><p>Rails use database-level locking to ensure data consistency when multiple processes try to modify the same record or table at the same time.</p><p>There are two main categories:</p><ul><li>Optimistic Locking</li><li>Pessimistic Locking</li></ul><h4>Optimistic Locking</h4><blockquote>Prevent overwrite conflicts — assume conflicts are rare</blockquote><p>Rails auto build-in if your table has a lock_verison column.</p><p>workflow:</p><ol><li>Rails will read a record with lock_version</li><li>Update it → Rails checks if database has same version</li><li>If someone updates it meanwhile → conflict error</li></ol><p>Example:</p><pre># assume products table has lock_version column<br>product = Product.find(1)<br>product.update!(price: 100)<br># If someone already updated this row, you&#39;ll get:<br># ActiveRecord::StaleObjectError</pre><h4>Pessimistic Locking</h4><blockquote>Force one process to wait — assume conflicts are common</blockquote><p>You explicitly lock the row so others must wait.</p><p>workflow:</p><pre>product = Product.lock.find(1)<br>product.quantity -= 1<br>product.save!<br><br># or<br>product = Product.find(1)<br>product.with_lock do<br>  product.update(price: 100)<br>end</pre><p>This will issue SELECT .. FOR UPDATE and other transactions can’t update the same row until transaction ends.</p><h3>Migration Locking</h3><p>When you run migrations, table structure changes lock the table:</p><ul><li>Adding a column without default value — Metadata lock and query still can run</li><li>Adding a column with default value — full table rewrite lock and read and write blocked.</li><li>Index creation — often long-running lock blocking write.</li></ul><h3>Conclusion</h3><ul><li>Rails does not do the locking — the database does.</li><li>Locking is used to protect data consistency when many processes access the same records.</li><li>There are two major approaches in Rails: Optimistic locking and Pessimistic locking</li><li>Schema changes in migrations can cause tables locks</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db11be57d0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solid — Dependency Inversion Principle(DIP)]]></title>
            <link>https://huangyudi.medium.com/solid-dependency-inversion-principle-dip-1ac84ef8a83e?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ac84ef8a83e</guid>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 14:23:05 GMT</pubDate>
            <atom:updated>2025-12-08T11:13:21.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solid — Dependency Inversion Principle(DIP)</h3><p>Have you ever worked on a project where one tiny change breaks five other features you didn’t even know existed?</p><p>It’s like your codebase has become a Jenga tower, touch the wrong block, and whole thing wobbles. Why?</p><p>Because everything depends directly on everything else.</p><p>Time to cut the right wire with the <strong>Dependency Inversion Principle</strong>.</p><h3>What is Dependency Inversion Principle(DIP)</h3><blockquote>High level modules shouldn’t depend on low level modules. Both should depend on abstractions</blockquote><p>Simply put:</p><blockquote>Don’t tie your logic directly to the tools you’re using.</blockquote><p>Instead, depend on interfaces, not implements.</p><h3>What happens without DIP?</h3><p>Image you have a PaymentsController directly call LinePay:</p><pre>class PaymentsController &lt; ApplicationController<br>  def create<br>    gateway = Linepay.new<br>    gateway.charge(params[:amount])<br>  end<br>end</pre><p>The business logic is hard-coded to Linepay.</p><p>If you switch to PayPal, you need to rewrite everything.</p><p>This causes problems:</p><ul><li>You can never replace Linepay with Paypal without modifying controllers.</li><li>Hard to test — you must stub Linepay directly</li><li>Business logic tightly depends on a low-level implementation.</li><li>Every part of the system knows about the details.</li></ul><p>This violates DIP.</p><h3>Enter Dependency Inversion</h3><p>We invert the direction of dependency, the business layer define rule, not the concrete service:</p><pre>class PaymentsController &lt; ApplicationController<br>  def create<br>    gateway = PaymentGatewayResolver.resolve(params[:provider])<br>    gateway.charge(params[:amount])<br>  end<br>end<br><br># app/services/payment_gateway.rb<br>class PaymentGateway<br>  def charge(amount:, order_id:)<br>    raise NotImplementedError<br>  end<br>end<br><br># app/services/gateways/linepay_gateway.rb<br>class Gateways::LinepayGateway &lt; PaymentGateway<br>  def charge(amount:, order_id:)<br>    # LinePay logic…<br>  end<br>end<br><br><br># app/services/payment_gateway_resolver.rb<br>class PaymentGatewayResolver<br>  def self.resolve(provider)<br>    {<br>      linepay: Gateways::LinepayGateway.new,<br>      paypal:  Gateways::PaypalGateway.new<br>    }.fetch(provider.to_sym)<br>  end<br>end</pre><p>Now, the controller depends on the abstraction, never on the implement.</p><p>If we want to swap Linepay to Paypal, we can swap directly.</p><p>No controller changes need.</p><h3>Signs you are violating DIP</h3><p>Look out for:</p><ul><li>High-level code instantiates low-level classes directly</li><li>Changing a low-level class breaks multiple unrelated features.</li><li>You can’t swap an implementation without edit multiple files</li><li>You have fat controllers because they contain infrastructure logic.</li></ul><p>All of these indicate tight coupling.</p><h3>Benefits of following DIP</h3><ul><li>Decoupling — High-level logic becomes independent of infrastructure details.</li><li>Easy to replace implementation — swap linepay to paypal or fakegateway without rewriting business logic</li><li>Improve testaility — mock only the abstraction.</li><li>More stable codebase — details can change freely without breaking core logic.</li></ul><h3>Conclusion</h3><p>The Dependency Inversion Principle prevents your code from becoming a tangled web of fragile dependencies.</p><p>By depending on abstractions instead of concrete implementations, you gain:</p><ul><li>flexibility</li><li>stability</li><li>testability</li><li>long-term maintainability</li></ul><blockquote>DIP isn’t about writing more layer, it’s about giving your system the freedom to evolve.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ac84ef8a83e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solid — Interface Segregation Principle (ISP)]]></title>
            <link>https://huangyudi.medium.com/solid-interface-segregation-principle-isp-1b75e01fbc05?source=rss-ad8b27291ba0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b75e01fbc05</guid>
            <category><![CDATA[interface-segregation]]></category>
            <category><![CDATA[isp]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Huang Yu Ti]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 17:41:40 GMT</pubDate>
            <atom:updated>2025-12-02T17:41:40.632Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solid — Interface Segregation Principle (ISP)</h3><p>Have you ever opened a class and thought,</p><blockquote>Why does this class have over 20 methods… and why am I responsible for all of them…</blockquote><p>That’s exactly the problem the Interface Segregation Principle tries to solve.</p><h3>What does ISP Really mean?</h3><blockquote>Client should not be force to depend on methods the do not use.</blockquote><p>Following ISP helps you avoid giant classes that try to handle every possible scenario.</p><p>A common violation of ISP is the everything service:</p><pre>class Notifier<br>  def send_email(to:, subject:, body:); end<br>  def send_sms(number:, message:); end<br>  def send_line(user_id:, message:); end<br>  def send_push(device_token:, message:); end<br>end</pre><p>At first, this looks convenient.</p><p>But in reality:</p><ul><li>The services depend on more methods than they need.</li><li>Tests become complex because you must be mock a massive interface.</li><li>Change one method risks breaking unrelated features.</li><li>The service grow uncontrollably over time.</li></ul><p>Instead of one bloated class, we can define smaller, focused modules:</p><pre>module EmailNotifiable<br>  def send_email(to:, subject:, body:); end<br>end<br><br>module SmsNotifiable<br>  def send_sms(number:, message:); end<br>end<br><br>module LineNotifiable<br>  def send_line(user_id:, message:); end<br>end</pre><p>Then, concrete implementations only include what they need:</p><pre>class EmailService<br>  include EmailNotifiable<br>end<br><br>class LineBotService<br>  include LineNotifiable<br>end</pre><p>Now each client depends only on the behavior it actually needs.</p><p>Some example like:</p><pre>class PaymentService<br>  def charge_credit_card; end<br>  def refund; end<br>  def payout; end<br>  def credit_points; end<br>  def debit_points; end<br>end</pre><p>Developer often create one service to rule them all, but different parts of system use only a subset of these.</p><p>According to the ISP, we split it:</p><ul><li>CardPaymentService</li><li>RefundService</li><li>PayoutService</li><li>PointsWalletService</li></ul><p>Each class is smaller, clearer, and safer to modify.</p><h3>Benefits</h3><ul><li>Smaller and safer APIs — fewer things can break.</li><li>Less coupling — clients depends only on relevant behaviors</li><li>Easier testing — mock only what you use</li><li>Faster development — changes become local instead of risky</li></ul><h3>Conclusion</h3><p>The Interface Segregation Principle helps you avoid bloated, fragile interfaces by encouraging small, role-focused APIs.</p><p>It improves readability, reduces coupling, and keeps your codebase clean and maintainable.</p><blockquote>ISP is not just about splitting interfaces — it’s about respecting the people who have to read, use, and maintain your code.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b75e01fbc05" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>