<?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 Hao Kuang on Medium]]></title>
        <description><![CDATA[Stories by Hao Kuang on Medium]]></description>
        <link>https://medium.com/@kuangbyte?source=rss-18fe091d97fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*VeTgWvpmQYnD5JIZ.</url>
            <title>Stories by Hao Kuang on Medium</title>
            <link>https://medium.com/@kuangbyte?source=rss-18fe091d97fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:06:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kuangbyte/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[You Don’t Need a Scheduler Yet]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://kuangbyte.medium.com/you-dont-need-a-scheduler-yet-314bdc4cc2c0?source=rss-18fe091d97fa------2"><img src="https://cdn-images-1.medium.com/max/1244/1*WxgcpgsZRX5c15cB2QFseQ.jpeg" width="1244"></a></p><p class="medium-feed-snippet">What strange scheduler designs can teach us about infrastructure, technical debt, and engineering judgment</p><p class="medium-feed-link"><a href="https://kuangbyte.medium.com/you-dont-need-a-scheduler-yet-314bdc4cc2c0?source=rss-18fe091d97fa------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kuangbyte.medium.com/you-dont-need-a-scheduler-yet-314bdc4cc2c0?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/314bdc4cc2c0</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[engineering-judgment]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 04:24:56 GMT</pubDate>
            <atom:updated>2026-09-05T04:25:52.995Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Developer’s Warning On AI Coding Assistants]]></title>
            <link>https://kuangbyte.medium.com/a-developers-warning-on-ai-coding-assistants-47ffab38e660?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/47ffab38e660</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[critical-thinking]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 14:02:01 GMT</pubDate>
            <atom:updated>2025-11-02T14:02:01.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PesCHfYr5ftg7yQgax7-pA.png" /></figure><p>We’re all using AI to code faster, and it feels like a superpower. We’re closing tickets faster than ever, and our velocity metrics look great. But I’ve noticed a worrying trend, both in my own work and in the code I review: we’re starting to lose the plot.</p><h3>The Problem: We’re Outsourcing Our Thinking</h3><p>The hardest part of our job isn’t writing code. It’s the deep, messy work of understanding a problem. It’s reading a PRD and asking “what if?” It’s mentally tracing how a change will ripple through the system. This struggle is what builds our context and intuition as engineers.</p><p>AI assistants let us skip this struggle. We feed them a prompt, and out comes clean, plausible-looking code. The “translation” from requirement to code happens in a black box. We get the answer without ever having to truly understand the question.</p><h3>The Illusion of “Good Code”: Local vs. Global Correctness</h3><p>One of the biggest traps is that AI-generated code often appears “good” on the surface. It’s well-formatted, uses modern syntax, and correctly solves the problem in isolation. This creates an illusion of completeness.</p><p>However, there’s a critical difference between code that is <em>locally correct</em> and code that is <em>globally correct</em>.</p><ul><li><strong>Local Correctness:</strong> The code works perfectly for the specific task it was prompted to do.</li><li><strong>Global Correctness:</strong> The code integrates seamlessly and safely with the entire system, respecting its architecture, assumptions, and edge cases.</li></ul><p>True system robustness comes from global correctness. It requires a deep, holistic understanding — a “global vision” — of how different parts of the system interact. This vision isn’t innate; it’s built through the slow, deliberate work of reading existing code, tracing data flows, and internalizing architectural patterns.</p><p>This is where the real danger lies. Even a talented engineer, skilled at spotting corner cases in theory, cannot identify system-level integration issues without this global context. AI assistants allow us to generate code without ever doing the foundational work required to build that context. We get an answer that <em>looks</em> locally correct, compounding the illusion of safety. Lacking the global vision, we are unable to see why this plausible-looking code might be a globally incorrect — and dangerous — addition to the system.</p><h3>From Individual Habit to Organizational Threat</h3><p>When an entire team starts to outsource its thinking, the individual blind spots quickly compound into a significant organizational threat. The short-term boost in velocity creates a long-term deficit in robustness and expertise.</p><h3>1. A Predictable Rise in Incidents and Regressions</h3><p>When developers have a shallower understanding of the code they’re shipping, they cannot anticipate the downstream effects. The edge cases we fail to consider during a rushed, AI-assisted development cycle don’t just disappear. They lie in wait, ready to become the next high-priority bug or, worse, the next production outage.</p><h3>2. The Erosion of In-House Expertise</h3><p>The struggle to understand a complex system is what builds institutional knowledge. When we let AI handle the hard parts, we rob ourselves of that learning process.</p><ul><li><strong>A Widening Skills Gap:</strong> How will junior engineers develop the deep system understanding required to become senior architects if they never have to grapple with problems from first principles?</li><li><strong>Loss of Collective Knowledge:</strong> When the “why” behind a piece of code lives only in the AI’s black box, it never becomes part of the team’s shared context. This makes systems harder to maintain and evolve over the long term.</li></ul><h3>3. Misaligned Incentives and Performance Evaluation</h3><p>The reliance on AI assistants can also distort how we measure engineering performance, creating incentives that are counterproductive to long-term health.</p><ul><li><strong>The Flaw of Velocity Metrics:</strong> Traditional metrics like commit frequency, lines of code, or number of PRs become misleading. An engineer can appear highly productive by churning out AI-generated code, while their actual understanding of the system remains shallow. This creates a culture that rewards speed over thoughtfulness.</li><li><strong>Devaluing “Invisible” Senior-Level Work:</strong> The most critical contributions of senior engineers and team leads are often invisible if you only look at commit logs. Their value lies in asking hard questions during design reviews, mentoring junior engineers to think more critically, and preventing poorly-conceived code from ever being written. When the focus shifts to raw output, this essential work is devalued.</li><li><strong>Rethinking Engineering Excellence:</strong> We must adapt our evaluation criteria to reward the behaviors that lead to robust, maintainable systems. This means focusing on outcomes over output: the quality of design documents, the thoroughness of code reviews, the impact of mentorship, and the long-term reliability of the code we ship.</li></ul><h3>What This Means for Us</h3><p>This isn’t a call to abandon AI tools. It’s a call to be smarter about how we use them. Treat them as a pair programmer who is incredibly fast but has zero context and no long-term memory.</p><p>Our value as engineers is not in how fast we can type, but in our ability to think critically, understand context, and build robust systems. Let’s make sure we’re not automating away the very skills that make us effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47ffab38e660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Cron Job to Real-Time Processing: The Evolving Architecture of a Ranking System]]></title>
            <link>https://kuangbyte.medium.com/from-cron-job-to-real-time-processing-the-evolving-architecture-of-a-ranking-system-f2e778c5ae77?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e778c5ae77</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 18:03:07 GMT</pubDate>
            <atom:updated>2025-08-01T18:03:07.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*U0TaFixL_YTEDCcJm5tFHQ.png" /></figure><p><em>How to build a “trending” feature that scales from a simple script to a sophisticated, real-time stream processing engine.</em></p><p>When you browse a news website, a social media feed, or an e-commerce platform, you’re constantly met with lists of what’s “trending,” “popular,” or “most viewed.” These features feel intuitive, almost magical, in their ability to surface what’s relevant <em>right now</em>. But building them is a fascinating engineering challenge that reveals a fundamental truth of software architecture: the “right” solution is a moving target.</p><p>This article will guide you through that journey. We’ll start with a common use case — a “Trending Articles” leaderboard — and explore a spectrum of architectural patterns to implement it. We will evolve our solution from a humble script to a powerful real-time pipeline, and at each step, we will focus on the most important part of the process: the trade-offs.</p><p><strong>A Crucial Disclaimer:</strong> This is not a ladder you must climb. Think of it as a map of possibilities. For many businesses, a well-optimized database or a simple cache is the perfect, long-term solution. Sometimes, paying for a bigger database server is a far smarter business decision than taking on the complexity of a distributed system. Our goal is to arm you with the knowledge to make informed decisions for your own projects, so you can choose the right tool for the right job.</p><h3>The Use Case: Trending Articles</h3><p>Imagine we need to build a “Trending Articles” feature for a publishing platform. The core requirements are:</p><ul><li>Track user engagement events like views, claps, and comments.</li><li>Calculate a “trending score” for each article based on recent activity.</li><li>Display a ranked list of the top 10 articles to all users.</li></ul><p>Let’s begin our journey with the simplest possible solution.</p><h3>Level 1: The Nightly Cron Job (The “Good Enough” Start)</h3><p>This is the classic starting point. It’s often used for internal analytics or non-critical features where freshness isn’t a priority.</p><p><strong>The Idea:</strong> A script runs on a regular schedule (e.g., once a day via cron). It connects to a database, calculates the scores over the last 24 hours, and saves the results into a static trending_articles_snapshot table. The application backend simply has to read this pre-computed table. It&#39;s worth noting that at many companies, the engagement_events data would not be in the primary production database but would be collected in a data warehouse (like Snowflake, BigQuery) or a data lake (e.g., S3). The principle remains the same: a scheduled job queries this analytical store.</p><p><strong>The Code (Python &amp; SQL):</strong></p><pre># This script would be triggered by a scheduler like cron<br>import sqlalchemy<br>import pandas as pd<br><br>def update_trending_snapshot():<br>    # This engine could be connecting to a production replica or a data warehouse<br>    engine = sqlalchemy.create_engine(&quot;postgresql://user:password@host/db&quot;)<br>    <br>    # The text() construct is the recommended way to execute literal SQL<br>    query = sqlalchemy.text(&quot;&quot;&quot;<br>        SELECT <br>            article_id, <br>            COUNT(*) as score,<br>            &#39;24h&#39; as time_window<br>        FROM <br>            engagement_events<br>        WHERE <br>            event_timestamp &gt;= NOW() - INTERVAL &#39;24 hours&#39;<br>        GROUP BY <br>            article_id<br>        ORDER BY <br>            score DESC<br>        LIMIT 10;<br>    &quot;&quot;&quot;)<br>    <br>    with engine.connect() as conn:<br>        df = pd.read_sql(query, conn)<br>        # Overwrite the snapshot table with the new results<br>        df.to_sql(&#39;trending_articles_snapshot&#39;, conn, if_exists=&#39;replace&#39;, index=False)<br>        <br>    print(&quot;Successfully updated trending articles snapshot.&quot;)</pre><p><strong>The Trade-off:</strong></p><ul><li><strong>Pro:</strong> It’s simple, reliable, and has almost no impact on your main application database, especially if querying a separate data warehouse.</li><li><strong>Con:</strong> The data is always stale. An article can go viral, but no one will know about it from your feature until the next day’s run.</li></ul><h3>Level 2: The Live Query (The “Obvious but Dangerous” Step)</h3><p>When daily updates aren’t enough, the most straightforward next step is to ask the database for a live result.</p><p><strong>The Idea:</strong> Forget the snapshot table. Every time a user requests the trending list, the application executes a query directly to calculate the scores on the fly. The SQL logic is nearly identical to the one in Level 1, but it runs for every user request. The key risk here depends on <em>where</em> the data lives. If engagement_events is a table in your main production (OLTP) database, this pattern is extremely risky. If the events are in a specialized, high-performance analytical database (like ClickHouse or a well-tuned data warehouse), this pattern can be viable for much longer.</p><p><strong>The Trade-off:</strong></p><ul><li><strong>Pro:</strong> The data is perfectly fresh. The implementation is still trivial.</li><li><strong>Con:</strong> This is a performance time bomb. A GROUP BY ... ORDER BY query that runs occasionally is fine, but executing it on every page load—especially against a production OLTP database—places an immense load on a critical resource. It&#39;s a solution that works beautifully until it catastrophically doesn&#39;t.</li></ul><h3>Level 3: The Cache (The “Pragmatic Sweet Spot”)</h3><p>This is the most common and effective pattern for scaling read-heavy features. We offload the ranking work from our precious database to a system designed for this exact purpose: an in-memory cache like Redis.</p><p><strong>The Idea:</strong> We use the Redis Sorted Set (ZSET), a data structure that maintains a collection of items ordered by a score.</p><ol><li><strong>Write Path:</strong> When a user engages with an article, our application now does two things: it writes the event to the database (our source of truth) and it increments the article’s score in a Redis sorted set using the atomic ZINCRBY command. This is a good start, but a simple increment is naive. It&#39;s easily gamed by bots and doesn&#39;t distinguish between a new, hot article and an old, consistently popular one.</li><li><strong>Read Path:</strong> When a user needs the list, we ask Redis for the top 10 items using ZREVRANGE. This is a near-instantaneous operation.</li></ol><p><strong>The Code (Python &amp; Redis):</strong></p><pre>import redis<br><br># decode_responses=True makes redis-py return strings instead of bytes<br>r = redis.Redis(host=&#39;localhost&#39;, port=6379, db=0, decode_responses=True)<br>TRENDING_ARTICLES_KEY = &quot;trending:1h&quot;<br>WINDOW_EXPIRY_SECONDS = 3600 * 2 # Keep the set for 2 hours<br><br>def record_engagement(article_id):<br>    # The main database write would happen here first.<br>    <br>    # Use a pipeline to send multiple commands atomically<br>    with r.pipeline() as pipe:<br>        pipe.zincrby(TRENDING_ARTICLES_KEY, 1, article_id)<br>        pipe.expire(TRENDING_ARTICLES_KEY, WINDOW_EXPIRY_SECONDS)<br>        pipe.execute()<br><br>def get_trending_articles():<br>    # Returns a list of (article_id, score) tuples<br>    # e.g., [(&#39;101&#39;, 150.0), (&#39;205&#39;, 125.0)]<br>    return r.zrevrange(TRENDING_ARTICLES_KEY, 0, 9, withscores=True)</pre><p><strong>The Trade-off:</strong></p><ul><li><strong>Pro:</strong> Blazing fast reads and a happy, protected database. Redis is built for this.</li><li><strong>Con:</strong> This adds significant complexity.</li><li><strong>Data Richness:</strong> Our cache only stores IDs and scores. To display full article titles and author names, the application must perform a second lookup to the main database using the IDs from Redis. This can be inefficient and lead to N+1 query problems. The alternative is to store more data in the cache, increasing its complexity and memory footprint.</li><li><strong>Data Consistency:</strong> It introduces the classic “dual write” problem. If the application successfully writes to the database but fails to update the cache, the data becomes inconsistent. Solving this reliably is a non-trivial engineering challenge, often requiring advanced patterns like <strong>Change Data Capture (CDC)</strong>, the <strong>transactional outbox pattern</strong>, or periodic <strong>reconciliation jobs</strong> to fix data drift.</li><li><strong>Cache Stampede (Thundering Herd):</strong> What happens when a popular cache key expires? Thousands of concurrent requests might miss the cache simultaneously, all rushing to the database to recalculate the data. This stampede can instantly overload your database. Solutions involve sophisticated caching strategies, like having a background process that is the sole writer responsible for refreshing popular keys before they expire.</li></ul><h3>Level 4: Distributed Batch (The “Serious Data” Approach)</h3><p>When your data volume grows into terabytes and you need a more sophisticated algorithm than simple counting, you enter the world of distributed systems. This is the point where you shift from scaling a single machine (“scaling up”) to distributing the work across many machines (“scaling out”).</p><p><strong>The Idea:</strong> We move beyond simple counts to a more intelligent scoring algorithm. Two key concepts are:</p><ul><li><strong>Time-Decay:</strong> To truly find what’s “trending,” recent events must be worth more than old ones. A common way to model this is with a gravity formula: score = Σ (event_weight / (time_since_event)^gravity). The gravity constant controls how quickly scores decay.</li><li><strong>Event Weighting:</strong> Not all actions are equal. A “comment” is a stronger sign of engagement than a “view.” Our system should assign different weights to different event types.</li><li>A distributed engine like Apache Spark is perfect for this. It can process billions of events from a data lake (e.g., S3) on a schedule, apply this complex logic, and write the final rankings to a key-value store for the application to read.</li><li><strong>The Code (PySpark Concept):</strong></li></ul><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import col, current_timestamp, sum as _sum, when<br><br>spark = SparkSession.builder.appName(&quot;TrendingArticlesBatch&quot;).getOrCreate()<br>events_df = spark.read.parquet(&quot;s3://events-bucket/...&quot;)<br><br># 1. Apply event weights<br>weighted_df = events_df.withColumn(&quot;event_weight&quot;, <br>    when(col(&quot;event_type&quot;) == &quot;comment&quot;, 10)<br>    .when(col(&quot;event_type&quot;) == &quot;clap&quot;, 3)<br>    .otherwise(1)<br>)<br><br># 2. Apply time-decay formula<br>time_diff_seconds = current_timestamp().cast(&quot;long&quot;) - col(&quot;event_timestamp&quot;).cast(&quot;long&quot;)<br>gravity = 1.8<br>scored_df = weighted_df.withColumn(&quot;score&quot;, col(&quot;event_weight&quot;) / (time_diff_seconds + 3600)**gravity)<br><br>final_ranks = scored_df.groupBy(&quot;article_id&quot;).agg(_sum(&quot;score&quot;).alias(&quot;total_score&quot;))<br>final_ranks.write.format(&quot;redis&quot;).option(...).save()</pre><p><strong>The Trade-off:</strong></p><ul><li><strong>Pro:</strong> The ranking algorithm is now much more sophisticated and produces far more relevant results. It can process enormous datasets.</li><li><strong>Con:</strong> Latency is still present; it’s <em>near</em> real-time, not instant. The infrastructure complexity also grows significantly. You are now managing not just a computation engine (Spark) but also a high-throughput <strong>serving layer</strong> (the key-value store) that needs to be optimized for high QPS and low latency.</li></ul><h3>Level 5: Distributed Streaming (The “Truly Real-Time” Engine)</h3><p>For use cases that demand true, sub-second latency, batch processing isn’t enough. We need to process events as they arrive.</p><p><strong>The Idea:</strong> This is a fundamental architectural shift to a streaming model.</p><ol><li>Events are published to a streaming platform like Apache Kafka. A key advantage here is that a pre-processing step can filter the stream in real-time, removing events from known bots or low-quality signals (e.g., views lasting less than 3 seconds).</li><li>An Apache Flink job subscribes to this cleaned stream.</li><li>Flink uses powerful built-in functions to perform aggregations over a <strong>sliding time window</strong>, applying the same sophisticated scoring logic as the batch job, but continuously.</li><li>The Flink job writes the constantly updating rankings to a sink that the application reads from.</li></ol><p><strong>The Diagram:</strong><br>[Application Event] -&gt; [Kafka] -&gt; [Flink Job] -&gt; [Redis] -&gt; [Application]</p><p><strong>The Trade-off:</strong></p><ul><li><strong>Pro:</strong> True, low-latency real-time ranking at massive scale.</li><li><strong>Con:</strong> This is a major leap in operational complexity. You are now managing a full-blown distributed system with three distinct parts: a message queue (Kafka), a stateful stream processor (Flink), and a low-latency <strong>serving layer</strong> (Redis). Each component requires specialized expertise.</li></ul><h3>Level 6: Complex Real-time Event Processing</h3><p>This level showcases the true power of a mature stream processing architecture: creating personalized, contextual experiences.</p><p><strong>The Idea:</strong> We go beyond a single stream. We join multiple, live data streams in real-time to create a rich, contextual score. This often involves enriching the main event stream with data from a <strong>Feature Store</strong>, a specialized system designed to serve pre-computed user or item data (e.g., user interests, article tags) with very low latency. A Flink job can query this store in real-time to get the context needed for a truly personalized score.</p><ul><li><strong>Stream 1:</strong> The engagement_events from Kafka.</li><li><strong>Stream 2:</strong> A lookup to a Feature Store to get user/article attributes.</li><li>A Flink job can join these streams so that a “view” from a user interested in “Data Science” on an article tagged “Machine Learning” is weighted more heavily. The system is no longer just counting — it’s understanding context.</li></ul><p><strong>The Diagram:</strong><br>[Kafka] + [Feature Store] -&gt; [Flink Job with Enrichment] -&gt; [Personalized Redis Ranks] -&gt; [Application]</p><p><strong>The Trade-off:</strong></p><ul><li><strong>Pro:</strong> The ultimate in real-time, contextual processing.</li><li><strong>Con:</strong> The peak of implementation and operational complexity. This is a highly advanced architecture for sophisticated product goals.</li></ul><h3>Conclusion: A Map, Not a Mandate</h3><p>We have journeyed from a simple cron job to a complex, real-time processing engine. The key takeaway is that there is no single “best” answer. The choice is a classic engineering trade-off between capability and complexity. Start with the simplest, most “boring” solution that meets your product needs. Don’t chase complexity for its own sake. Only accept the cost of a more complex system when the business case for more scale, lower latency, or deeper intelligence is undeniable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e778c5ae77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Just Locks: A Guide to Pessimistic and Optimistic Concurrency Control in Python with MySQL]]></title>
            <link>https://kuangbyte.medium.com/beyond-just-locks-a-guide-to-pessimistic-and-optimistic-concurrency-control-in-python-with-mysql-51cbc2f6fab2?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/51cbc2f6fab2</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 01:54:37 GMT</pubDate>
            <atom:updated>2025-08-01T01:54:37.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4878MRlLFWCsHIzlR7KbQ.jpeg" /></figure><p>When we build applications that interact with a database, it’s easy to write code that works perfectly for a single user. But what happens when hundreds or thousands of users try to perform actions at the same time? How do we prevent them from overwriting each other’s changes and corrupting our data?</p><p>This is the challenge of concurrency control. The common answer you’ll find involves database “locks,” but this single term hides a world of strategy and trade-offs. The real question isn’t <em>whether</em> to use locks, but <em>how</em> and <em>when</em> to apply different locking strategies.</p><p>Most guides explain this from the bottom up: here’s a row lock, here’s a table lock, and so on. In this article, we’re going to do the opposite. We’ll start with a real-world problem and let the solution evolve, guiding you through the same thought process you’d have when building a real application. We’ll start with a simple, robust approach, expose its limitations, and then refactor our way to a more performant, scalable solution — exploring the critical trade-offs at each step.</p><h3>The Use Case: A Standard Product Purchase</h3><p>Imagine an e-commerce website featuring a popular product, the “Quantum Widget.” It’s not a limited-time flash sale, but it sells consistently, and multiple customers might try to purchase the last few items simultaneously. The problem? We have a limited quantity in stock.</p><p>Our database has a simple products table to track our inventory:</p><pre>CREATE TABLE products (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    name VARCHAR(255) NOT NULL,<br>    quantity INT NOT NULL,<br>    price DECIMAL(10, 2) NOT NULL<br>);<br><br>-- Let&#39;s stock our Quantum Widget<br>INSERT INTO products (name, quantity, price) VALUES (&#39;Quantum Widget&#39;, 10, 999.99);</pre><p>Our goal is to write a piece of Python code that handles a customer’s purchase. In its most basic form, the logic is simple:</p><ol><li>Check if quantity &gt; 0.</li><li>If it is, decrease the quantity by 1.</li><li>If not, tell the user it’s sold out.</li></ol><p>Let’s explore how we’d build this and why this simple logic is not enough.</p><h3>Attempt #1: The Race Condition and the Pessimistic Lock</h3><p>The naive approach is to select the data, check the quantity in our Python code, and then run an update. Let’s see what that looks like. We’ll use the mysql-connector-python library for this example.</p><blockquote><strong><em>Security Note:</em></strong><em> The following examples load database credentials from environment variables (</em><em>os.getenv). Hardcoding secrets directly in your code is a major security risk. In a real application, you should always load credentials from a secure source like environment variables or a secret management service.</em></blockquote><pre>import mysql.connector<br>import time<br>import os<br><br>def get_db_config():<br>    return {<br>        &#39;host&#39;: os.getenv(&#39;DB_HOST&#39;, &#39;localhost&#39;),<br>        &#39;user&#39;: os.getenv(&#39;DB_USER&#39;, &#39;user&#39;),<br>        &#39;password&#39;: os.getenv(&#39;DB_PASSWORD&#39;, &#39;password&#39;),<br>        &#39;database&#39;: os.getenv(&#39;DB_DATABASE&#39;, &#39;ecommerce&#39;)<br>    }<br>def purchase_item(user_id):<br>    db_config = get_db_config()<br>    try:<br>        with mysql.connector.connect(**db_config) as connection:<br>            with connection.cursor() as cursor:<br>                # 1. Check the quantity<br>                cursor.execute(&quot;SELECT quantity FROM products WHERE id = 1&quot;)<br>                (quantity,) = cursor.fetchone()<br>                if quantity &gt; 0:<br>                    # Simulate a small delay (e.g., processing payment)<br>                    time.sleep(0.1)<br>                    <br>                    # 2. Decrease the quantity<br>                    new_quantity = quantity - 1<br>                    cursor.execute(<br>                        &quot;UPDATE products SET quantity = %s WHERE id = 1&quot;, (new_quantity,)<br>                    )<br>                    connection.commit()<br>                    print(f&quot;User {user_id}: Purchase successful!&quot;)<br>                else:<br>                    print(f&quot;User {user_id}: Sorry, item is sold out.&quot;)<br>    except mysql.connector.Error as err:<br>        print(f&quot;User {user_id}: An error occurred: {err}&quot;)</pre><p>Imagine two users, <strong>Alice</strong> and <strong>Bob</strong>, trying to buy the last “Quantum Widget” at roughly the same time. In a web application, this would mean two concurrent requests executing the purchase_item function. If the stock level is at 1, both requests could read the quantity (1) before either has a chance to update it. Both would think the item is available, and both would process the purchase. The final quantity in the database would become -1. This is a classic race condition, and in business terms, this is an oversale.</p><p>We have now sold an item we don’t have, which leads to unhappy customers, operational overhead to fix the mistake, and a loss of trust. The core of our discussion is how to prevent this.</p><h3>The Solution: Pessimistic Locking</h3><p>The most direct way to solve this is with a <strong>pessimistic lock</strong>. It’s called “pessimistic” because we assume the worst: that someone else is likely to try and modify the same record at the same time. We, therefore, ask the database to lock the row for our exclusive use until we are finished with our transaction.</p><p>In MySQL (specifically, with the InnoDB storage engine), we do this with SELECT ... FOR UPDATE.</p><p>Let’s modify our function:</p><pre>def purchase_item_pessimistic(user_id):<br>    db_config = get_db_config()<br>    try:<br>        with mysql.connector.connect(**db_config) as connection:<br>            with connection.cursor() as cursor:<br>                try:<br>                    # Start a transaction<br>                    connection.start_transaction()<br># Lock the row and then select it<br>                    cursor.execute(&quot;SELECT quantity FROM products WHERE id = 1 FOR UPDATE&quot;)<br>                    (quantity,) = cursor.fetchone()<br>                    if quantity &gt; 0:<br>                        time.sleep(0.1)<br>                        new_quantity = quantity - 1<br>                        cursor.execute(<br>                            &quot;UPDATE products SET quantity = %s WHERE id = 1&quot;, (new_quantity,)<br>                        )<br>                        print(f&quot;User {user_id}: Purchase successful!&quot;)<br>                    else:<br>                        print(f&quot;User {user_id}: Sorry, item is sold out.&quot;)<br>                    <br>                    # Commit the transaction to release the lock<br>                    connection.commit()<br>                except mysql.connector.Error as e:<br>                    print(f&quot;User {user_id}: An error occurred during transaction: {e}&quot;)<br>                    connection.rollback()<br>    except mysql.connector.Error as err:<br>         print(f&quot;User {user_id}: Database connection error: {err}&quot;)</pre><p>Now, when Alice’s transaction executes the SELECT ... FOR UPDATE, the database places a lock on that specific row. When Bob&#39;s transaction attempts to do the same, it will be forced to wait. It cannot read or write to that row until Alice&#39;s transaction is either COMMITted or ROLLBACK&#39;d.</p><p><strong>The Downside:</strong> While this is safe, it has direct performance implications. If the work inside our transaction takes a long time (e.g., calling a slow payment gateway), other users are stuck waiting. Holding locks increases contention and resource usage on the database itself, which can degrade the overall performance of the entire system. This creates a bottleneck that limits the throughput of our application, which might be unacceptable for a high-traffic site.</p><h3>Attempt #2: An Alternative Strategy — The Optimistic Approach</h3><p>The pessimistic lock solved our race condition, guaranteeing that we’ll never oversell the Quantum Widget. However, it can create a performance bottleneck. Forcing concurrent users to wait in line can limit throughput, especially if the locked transaction involves slow operations.</p><p>This leads us to an alternative strategy: <strong>optimistic locking</strong>. This approach is built on a completely different philosophy. It is “optimistic” because we assume that conflicts are rare, and we, therefore, don’t lock the row at all. Instead, we proceed with our logic and, just before committing, we perform a quick check to see if the data has been modified by someone else since we first read it.</p><p>Let’s explore how this pattern works and analyze its trade-offs.</p><p>This is not a built-in database feature but a pattern you implement in your application. The most common way to do it is by adding a version or timestamp column to the table.</p><p>Let’s alter our table:</p><pre>ALTER TABLE products ADD COLUMN version INT NOT NULL DEFAULT 1;</pre><p>Now, the logic changes:</p><ol><li>Read the quantity and the version of the product.</li><li>In our application, perform the logic (check quantity, etc.).</li><li>When we’re ready to update, we issue an UPDATE command that <em>atomically</em> both checks the version and decrements the quantity.</li><li>Crucially, we also increment the version number in the same statement.</li><li>After the UPDATE, we check how many rows were affected. If 1 row was affected, our update was successful. If 0 rows were affected, it means another transaction changed the data (and thus the version number) between our SELECT and UPDATE.</li></ol><p>Here is the Python implementation, refactored to use a custom exception for better error handling.</p><pre># A custom exception for handling concurrency failures<br>class ConcurrencyConflictError(Exception):<br>    pass<br><br>def purchase_item_optimistic(user_id):<br>    db_config = get_db_config()<br>    try:<br>        with mysql.connector.connect(**db_config) as connection:<br>            with connection.cursor(dictionary=True) as cursor: # Use a dictionary cursor<br>                try:<br>                    # 1. Read the current state<br>                    cursor.execute(&quot;SELECT quantity, version FROM products WHERE id = 1&quot;)<br>                    product = cursor.fetchone()<br>                    if product and product[&#39;quantity&#39;] &gt; 0:<br>                        # 2. Try to update, checking the version<br>                        new_quantity = product[&#39;quantity&#39;] - 1<br>                        current_version = product[&#39;version&#39;]<br>                        <br>                        update_query = &quot;&quot;&quot;<br>                            UPDATE products <br>                            SET quantity = %s, version = version + 1 <br>                            WHERE id = 1 AND version = %s<br>                        &quot;&quot;&quot;<br>                        cursor.execute(update_query, (new_quantity, current_version))<br>                        # 3. Check if the update was successful<br>                        if cursor.rowcount &gt; 0:<br>                            connection.commit()<br>                            print(f&quot;User {user_id}: Purchase successful!&quot;)<br>                        else:<br>                            # The version was changed by someone else. Abort the transaction.<br>                            connection.rollback()<br>                            raise ConcurrencyConflictError(<br>                                f&quot;Failed to update product id 1 for user {user_id}. Version mismatch.&quot;<br>                            )<br>                    elif product:<br>                        print(f&quot;User {user_id}: Sorry, item is sold out.&quot;)<br>                    else:<br>                        print(f&quot;User {user_id}: Product not found.&quot;)<br>                except mysql.connector.Error as e:<br>                    print(f&quot;User {user_id}: An error occurred during transaction: {e}&quot;)<br>                    connection.rollback()<br>    except mysql.connector.Error as err:<br>        print(f&quot;User {user_id}: Database connection error: {err}&quot;)</pre><h3>The Trade-off: Handling Concurrency Conflicts</h3><p>With the optimistic approach, our code no longer blocks, but it can now fail with a ConcurrencyConflictError. This is the essential trade-off: instead of waiting, we fail fast. Now, the critical question is: what should the calling code do when it catches this exception?</p><p>There are two primary strategies:</p><ol><li><strong>Retry the Transaction</strong>: The most common approach is to retry the entire business operation. The calling code would catch ConcurrencyConflictError, and could re-run the purchase_item_optimistic function from the beginning. This works well if conflicts are rare. However, it&#39;s vital to include a limit on the number of retries (e.g., 3-5 attempts) and possibly a small, randomized delay between them (known as exponential backoff) to prevent hammering the database during high-contention periods.</li><li><strong>Fail and Propagate to the User</strong>: In some cases, retrying isn’t appropriate. If the conflict indicates that the state has changed significantly (e.g., the item is now truly out of stock), it’s better to fail immediately. The calling code would catch the exception and translate it into a user-facing message like, “The item you’re trying to purchase was just updated. Please review and try again.” This pushes the decision back to the user, which is often the safest option in a web UI.</li></ol><p>Choosing between these depends on the application. For our purchase function, a limited number of automatic retries might be a good balance, as it could successfully capture a sale for a user whose transaction failed by a millisecond. If it still fails after a few tries, then you would inform the user that the item is no longer available or that they should try again.</p><h3>Deeper Dive: The Technical Details</h3><p>Now that we understand the practical application of these two strategies, let’s explore the underlying mechanics.</p><h3>Pessimistic Locking: FOR UPDATE, Deadlocks, and More</h3><ul><li><strong>Lock Types</strong>: The SELECT ... FOR UPDATE we used acquires an <strong>exclusive lock</strong> (or a write lock). No other transaction can read (with FOR UPDATE), modify, or delete the row until the lock is released. MySQL also offers SELECT ... FOR SHARE (in older versions, LOCK IN SHARE MODE), which acquires a <strong>shared lock</strong> (or a read lock). Multiple transactions can acquire a shared lock on the same row, but no transaction can modify or delete it until all shared locks are released. This is useful when you need to read a value and ensure it doesn&#39;t change before you&#39;re done, but you don&#39;t intend to update it yourself.</li><li><strong>Row-level vs. Table-level</strong>: InnoDB is famous for its row-level locking, which is what we want. However, it can only lock specific rows if the WHERE clause in your SELECT ... FOR UPDATE statement uses an index to precisely identify the records. If there&#39;s no suitable index, or if the query is ambiguous, MySQL may have no choice but to <strong>escalate to a table lock</strong>. This is a worst-case scenario for performance, as it blocks all other transactions from accessing the entire table, not just one row. Always ensure your locking queries are backed by an index.</li><li><strong>New in MySQL 8: </strong><strong>NOWAIT</strong>: The default behavior of FOR UPDATE is to wait if a requested row is locked (until the innodb_lock_wait_timeout is exceeded). MySQL 8 introduces the NOWAIT clause to change this behavior. This is particularly useful for <strong>single-record contention</strong>, like our product purchase example. It tells the database not to wait at all; if the specific row you want is already locked, the query fails immediately with an error. This provides a database-level &quot;fail fast&quot; strategy, preventing application threads from piling up while they wait for a lock.</li><li><strong>Gap and Next-Key Locks</strong>: InnoDB is clever. If your WHERE clause doesn&#39;t use a unique index, it might lock not just the rows found but also the &quot;gaps&quot; between them to prevent insertions that would match the query (this is a Next-Key Lock). This prevents &quot;phantom reads&quot; but can lead to more locking than you might expect.</li></ul><h3>Optimistic Locking: Variations and ORMs</h3><p>Optimistic locking isn’t a single database feature but a pattern you implement. While the core idea remains the same, there are different ways to apply it.</p><p><strong>Implementation Variants:</strong></p><ul><li><strong>Integer Version Column</strong>: This is the most common approach. A dedicated version integer column is added to the table. With every UPDATE, the version is checked and incremented. It&#39;s simple, fast, and database-agnostic.</li><li><strong>Timestamp Column</strong>: A TIMESTAMP or DATETIME column can also be used. The WHERE clause of the UPDATE statement checks if the timestamp is unchanged. This can be useful as the timestamp might already exist for other auditing purposes. However, it can be less precise than an integer and can be affected by clock synchronization issues.</li><li><strong>Row Checksum</strong>: A more complex method involves creating a checksum (hash) of all the row’s values. The application recalculates the hash and compares it to the stored hash during the update. This is rarely used as it adds significant overhead.</li><li><strong>ORM Support</strong>: Modern Object-Relational Mappers (ORMs) can save you from writing the raw SQL and version-checking logic manually.</li><li><strong>SQLAlchemy</strong>: SQLAlchemy has robust, built-in support for version-based optimistic locking. You enable it by setting the version_id_col parameter in the __mapper_args__ dictionary of your model definition. SQLAlchemy will then automatically add a WHERE clause to all UPDATE statements to check the version number and will raise a StaleDataError if a conflict is detected.</li><li><strong>Django</strong>: While Django’s core ORM provides building blocks like F() expressions for manual implementation, the recommended approach is to use a third-party package like <strong>django-concurrency</strong>. This library provides an IntegerVersionField that you add to your model, which handles the version checking automatically and raises a RecordModifiedError on conflicts.</li></ul><h3>Beyond the Database: Architectural Patterns for Extreme Throughput</h3><p>What happens when even optimistic locking isn’t enough? Let’s bring back our original “flash sale” scenario. In an extreme case like this, the database itself can become the bottleneck. No matter how efficient our query is, a single relational database can only handle so many connections and transactions per second. When you need to scale beyond this limit, you must change the architecture.</p><p>The core idea is to move the most contentious part of the operation — the inventory check and decrement — out of the main database and into a system designed for high-speed, in-memory operations.</p><p><strong>Using an In-Memory Cache (like Redis)</strong></p><p>Redis is single-threaded and provides atomic operations, making it a perfect tool for managing inventory counts at incredible speeds.</p><p><strong>The Pattern</strong>: Before the sale, you load the inventory count into a Redis key (e.g., product:1:quantity). The purchase logic then becomes:</p><ol><li>Use the atomic DECR (decrement) command in Redis.</li><li>If the result is 0 or greater, the user has successfully reserved an item. Their request is added to a processing queue.</li><li>If the result is negative, the item is sold out, and you can immediately tell the user.</li></ol><p><strong>The Trade-off</strong>: This introduces complexity. You now have two sources of truth. A separate, slower background process must work through the queue, update the primary MySQL database, and handle the rest of the order fulfillment. You also need a plan to handle what happens if Redis fails.</p><p><strong>Request Queuing</strong>: Instead of processing every purchase request in real-time, you can accept them all instantly and place them into a message queue (like RabbitMQ or AWS SQS).</p><p><strong>The Pattern</strong>: The “Buy Now” button doesn’t trigger a database write; it simply publishes a “purchase request” event to a queue. A separate pool of consumer services reads from this queue at a controlled pace that your database can handle, processing the orders one by one using one of the locking strategies we’ve already discussed.</p><p><strong>The Trade-off</strong>: The user experience changes. You can’t give the user an immediate “Success!” message. Instead, you can only say, “Your order is being processed, we’ll email you a confirmation shortly.” This is often an acceptable trade-off for ensuring the system remains stable under extreme load.</p><p><strong>Load Shedding (Probabilistic Dropping)</strong>: When load is so extreme that even queuing requests is not enough, a valid strategy is to intentionally not serve every request. This is known as load shedding.</p><p><strong>The Pattern</strong>: At the application entry point (e.g., the web server or a load balancer), you can configure a rule to randomly drop a certain percentage of incoming requests. For example, you might decide to reject 10% of purchase requests with a “Server Busy, please try again” message. This prevents your entire system from collapsing under the weight of traffic it cannot handle.</p><p><strong>The Trade-off</strong>: The user experience for those who are rejected is obviously poor. However, this strategy prioritizes the stability of the system as a whole, ensuring that the majority of users have a functional experience rather than everyone having a failed one. It’s a pragmatic choice when system survival is the primary goal.</p><p>These architectural patterns move the problem from “how to handle concurrent writes” to “how to manage and eventually process a high volume of requests.” This list is not exhaustive, and other advanced strategies like read replicas, circuit breakers, and database sharding also play a crucial role in building highly scalable systems.</p><h3>Conclusion: Which One Should You Choose?</h3><p>There is no single “best” answer. The choice between pessimistic locking, optimistic locking, and more advanced architectural patterns is a classic engineering trade-off that depends entirely on your use case. It’s a journey of escalating scale.</p><p>By starting with a real-world problem, we’ve seen how these powerful strategies are not just abstract database features, but practical tools for building robust, scalable applications. The next time you face a concurrency challenge, you’ll be equipped not just to find <em>an</em> answer, but to choose the <em>right</em> one for the job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51cbc2f6fab2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Uncertainty: The Right Mindset for Using Cursor and LLMs]]></title>
            <link>https://kuangbyte.medium.com/working-with-uncertainty-the-right-mindset-for-using-cursor-and-llms-a279dc5186f5?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/a279dc5186f5</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 19:32:27 GMT</pubDate>
            <atom:updated>2025-07-31T19:43:12.073Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“You’re not going to lose your job to an AI, but you’re going to lose your job to someone who uses AI.”<br> — </em><strong><em>Jensen Huang</em></strong><em>, </em>CEO of NVIDIA</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*Jf-UgOONVGxXd48HeGD2vQ.png" /></figure><h3>👋 Introduction</h3><ul><li>Cursor and LLMs are powerful, but often feel <em>unpredictable</em></li><li>Ever asked a question and got a weird or wrong result?</li><li>It’s not about using the tool <em>harder</em>, it’s about thinking <em>differently</em></li></ul><p>🧠 <strong>Today’s goal:</strong><br>Learn the mindset that makes Cursor more reliable and useful — whether you’re junior or experienced</p><h3>😥 The Productivity Paradox: Maker vs. Reviewer</h3><p>The promise of 10x productivity often hides a stressful reality: your role subtly shifts from a <strong>maker</strong> to a constant <strong>reviewer</strong>, which introduces new dangers.</p><ul><li><strong>The Illusion of Skill:</strong> AI lets you generate code for tasks you don’t deeply understand (e.g., a backend developer suddenly writing complex CSS). This creates a fragile competence that shatters under pressure, as you lack the expertise to debug or extend the AI’s output.</li><li><strong>Accumulating “Cognitive Debt”:</strong> Every time you accept code you don’t fully understand, you incur cognitive debt. You pay the high interest on this debt later, with hours of confusion when you must fix or change that very same code.</li><li><strong>The Lie of “Free” Code:</strong> Tools like Gemini CLI or other agents can generate entire features, hiding the code. But this is not “free.” It’s often a loan taken out against future maintainability, paid back when the un-reviewed, “garbage” code inevitably fails.</li></ul><p>This paradox — the promise of speed vs. the reality of new burdens — is why a new mindset is essential. Simply using the tool isn’t enough. You must learn to <em>direct</em> it effectively to avoid drowning in cognitive debt.</p><h3>✨ Amplify, Don’t Replace: The True Leverage of AI</h3><p>If raw speed is a myth, what is the real goal? The answer is <strong>leverage</strong>. The goal is not to replace your thinking, but to amplify your own intelligence and creativity.</p><p>Here’s the leverage you should be seeking from your AI assistant:</p><ol><li><strong>Leverage on Implementation:</strong> Let the AI handle the <em>knowns</em> so you can focus on the <em>unknowns</em>. The AI can write the boilerplate for a solved problem (a CRUD endpoint), freeing your mind to design the novel, high-value parts of your system.</li><li><strong>Leverage on Design:</strong> Use the AI to de-risk your architectural decisions. By having it instantly generate and critique multiple approaches (“What are the pros and cons of these three patterns?”), you explore the design space more thoroughly and build more resilient systems.</li><li><strong>Leverage on Learning:</strong> Use the AI to conquer complexity. Instantly get a foothold in a massive legacy codebase or a complex new library. The AI acts as your personal cartographer, drawing you a map of the territory so you can navigate it with confidence.</li></ol><p>The goal isn’t to replace your thinking, but to augment it. By leveraging the AI to handle the repetitive and the exploratory, you free up your most valuable asset: your own creative, architectural judgment.</p><h3>😵 Why LLMs Feel Unpredictable</h3><ul><li><strong>They are probabilistic, not deterministic:</strong> At their core, LLMs generate responses based on statistical likelihood, not fixed rules. This inherent randomness is why the same prompt can yield different results.</li><li>The underlying models are constantly evolving. A prompt that works today might behave differently next month.</li><li>They are often missing project context or hallucinating details.</li></ul><p>🚨 <strong>Misconception:</strong> “I just need to find the perfect prompt.”</p><p>✅ <strong>Reality:</strong> “I need a durable <em>process</em> to guide the AI.”</p><p>This is why your ability to break down problems is the most critical skill. Your <em>process</em> will adapt to any model, but a specific “magic prompt” is fragile.</p><h3>💼 Mindset Shift #1</h3><h3>You’re the Lead: Provide Context and Direction</h3><ul><li>You own the quality and direction. The AI is your brilliant but context-less junior dev.</li><li>Your primary job is to provide context. Create a prd.md or instructions.md file in your project root explaining goals, tech stack, and conventions. Tell the AI to read it.</li><li>Give it: Clear goals, Specific constraints, Feedback when it misses the mark</li></ul><p>✅ <strong>An example of providing context:</strong></p><blockquote><em>“Based on the database schema and coding conventions defined in our </em><em>instructions.md, create a new repository class for our </em><em>Products table that includes methods for </em><em>get_product_by_id and </em><em>list_all_products.&quot;</em></blockquote><p>🧠 “Cursor gives you speed. You give it judgment.”</p><h3>🧭 Mindset Shift #2</h3><h3>Deconstruct and Iterate: Go Slow to Go Fast</h3><p>Think of it like drawing a sketch. You don’t expect a perfect masterpiece in one stroke. You start with a rough outline and incrementally add detail. This feels slower upfront, but it’s the classic “measure twice, cut once.” This careful, iterative process prevents the frustrating cycle of vague prompts and bad results.</p><p>AI works best with <strong>focus and structure</strong>. Don’t give it open-ended tasks. Break big problems into smaller, well-defined “Lego” pieces. This constrains the AI and leaves less room for error.</p><p>❌ <strong>Delegating the whole painting:</strong></p><blockquote><em>“Build an API endpoint for user profiles.”</em></blockquote><p>✅ <strong>Iterating on the sketch:</strong></p><ul><li>“Define a Pydantic model for a UserProfile with fields user_id, username, bio.&quot;</li><li>“Now, write a FastAPI endpoint GET /users/{user_id} that returns this model.&quot;</li><li>“Finally, add error handling for when the user is not found.”</li><li><strong>Summarize:</strong> “Perfect. Now summarize the endpoint we just created in a markdown block, including the model, path, and error handling.”</li></ul><p>🌀 Use it like a feedback loop: Prompt → Output → Review → Refine. You guide the AI to the final result, you don’t just hand over the task.</p><h3>🗣️ Mindset Shift #3</h3><h3>Master Clear and Simple Language</h3><p>The clarity of your prompt is the single biggest factor in the quality of the result. This makes LLMs an incredibly friendly and powerful tool for non-native English speakers.</p><ul><li><strong>Clarity over Fluency:</strong> The AI doesn’t care about perfect grammar or sounding “natural”; it only cares about clarity. This is an advantage, as it allows you to focus on simple, direct instructions — the best way to prompt — without the pressure of complex language.</li><li><strong>Simple and Direct is Best:</strong> Use short, clear sentences. Avoid slang, regional idioms, or ambiguous jargon.</li><li><strong>Be Explicit:</strong> State exactly what you want. The AI is very literal.</li></ul><p>❌ <strong>Ambiguous / Colloquial Prompt:</strong></p><blockquote><em>“Hey, can you whip up some code for me? I need to pull the user info from the database. Just the usual stuff.”</em></blockquote><p>✅ <strong>Clear and Simple Prompt:</strong></p><blockquote><em>“Write a Python function named </em><em>get_user_by_id. It must take one integer argument: </em><em>user_id. It should query the &#39;users&#39; database table and return the </em><em>id, </em><em>username, and </em><em>email for the matching user.&quot;</em></blockquote><p>🧠 The AI doesn’t need fancy prose. It needs precise instructions.</p><h3>🧐 Mindset Shift #4</h3><h3>Ask and Learn Before You Execute</h3><p>You are the final gatekeeper of quality. Your judgment is essential.</p><p>It’s tempting to let the AI “just fix it.” But without understanding the change, how can you be sure the fix is correct or sufficient?</p><p>Before applying any change, use the AI as a learning tool to deepen your own understanding.</p><ul><li>Ask it to explain the root cause of the bug.</li><li>Ask about the trade-offs of its proposed solution.</li><li>Ask it to walk you through the logic of the fix, step-by-step.</li></ul><p>This process ensures you are making an informed decision, not just blindly trusting a black box. You can’t be a good gatekeeper for a change you don’t understand.</p><p>🧠 Use AI to make yourself smarter before you let it change your code.</p><h3>🧪 Mindset Shift #5</h3><h3>Your Unit Tests Are Your Source of Truth</h3><p>Human review is slow and fallible. In an AI world, robust tests are your most reliable tool for verifying correctness.</p><ul><li><strong>Write tests first, or have the AI do it:</strong> Giving the AI a test file provides a concrete definition of “done.” It creates a clear contract for the AI to follow.</li><li><strong>AI makes testing cheap and fast:</strong> The friction to write tests is now incredibly low. Ask the AI to generate unit tests, integration tests, and edge cases for any piece of code.</li><li><strong>Tests are your contract:</strong> A comprehensive test suite acts as an executable specification. If the tests pass, the code is likely correct, regardless of whether it was written by a human or an AI.</li></ul><p>The ultimate workflow (Test-Driven Development with AI):</p><ol><li><strong>Enumerate Test Scenarios:</strong> Before writing any implementation code, you define the contract. Think critically about the happy path, edge cases, and potential error conditions. This is where your expertise is crucial.</li><li><strong>Generate the Test Scaffolding:</strong></li><li><strong>Implement to Pass:</strong> Now, instruct the AI to write the implementation code with the explicit goal of making all the tests pass.</li><li><strong>Verify and Refine:</strong> Run the full test suite. For any failing tests, feed the errors back to the AI and ask it to fix the implementation.</li><li><strong>Check Coverage for Gaps:</strong> Once all tests pass, check your test coverage report. If you find untested code paths, ask the AI to write tests for those specific branches.</li><li><strong>Final Sanity Check:</strong> As a last step, ask the AI to perform a final review: “Are there any potential bugs, race conditions, or security vulnerabilities in this final code?”</li></ol><p>🧠 Don’t just trust the code, trust the tests. If you don’t have tests, ask the AI to write them first.</p><h3>💬 Final Thought</h3><p>The core lesson is that working effectively with AI isn’t about learning a magic trick. It’s about applying timeless engineering discipline to a new, powerful tool. The best developers in the AI era won’t be the ones who type the fastest — they’ll be the ones who think the clearest</p><p>After reading through these points, you may realize they are not new rules. They are the same principles that define a great engineer: <strong>clarity</strong>, <strong>discipline</strong>, <strong>breaking down problems</strong>, and <strong>taking ownership of quality.</strong></p><p>AI doesn’t change these principles; it just makes them more important than ever.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a279dc5186f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Data Extraction: Partitioning and Pagination Strategies]]></title>
            <link>https://kuangbyte.medium.com/snowflake-data-extraction-partitioning-and-pagination-strategies-29400889628d?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/29400889628d</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 00:46:25 GMT</pubDate>
            <atom:updated>2025-07-03T00:59:21.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slgDGfrCsAWX15lJvzhzQw.jpeg" /></figure><p>This article outlines various strategies for efficiently extracting large datasets from Snowflake, focusing on the combination of partitioning and pagination. The goal is to achieve high-throughput, parallel, and resumable data pipelines.</p><h3>Core Concepts</h3><p>Effective large-scale data extraction from Snowflake relies on two key techniques:</p><ol><li><strong>Partitioning</strong>: Dividing the total dataset into smaller, independent chunks. This allows multiple concurrent workers to query a subset of the data without interfering with each other.</li><li><strong>Pagination</strong>: Fetching the data within each partition in manageable batches (pages). This avoids loading massive amounts of data into memory at once and makes the process resumable.</li></ol><h3>Partitioning Strategies</h3><p>Partitioning is about answering the question: “How do we assign each row to a specific worker?”</p><h3>Strategy 1: Modulo Hashing</h3><p>This is a robust, general-purpose strategy that works well for most use cases.</p><ul><li><strong>Concept</strong>: Use the built-in HASH() function on a designated partition_key_column. The MOD() operator is then used to assign each row to one of N virtual buckets, where N is the total number of parallel sources.</li><li><strong>SQL Snippet</strong>:</li></ul><pre>WHERE MOD(ABS(HASH(partition_key_column)), %(num_sources)s) = %(partition_id)s</pre><p><strong>Pros</strong>:</p><ul><li><strong>Good Data Distribution</strong>: Generally ensures a uniform distribution of data across workers, even if the key’s values are skewed or have gaps.</li><li><strong>No Setup Required</strong>: Does not require any pre-analysis of the table.</li></ul><p><strong>Cons</strong>:</p><ul><li><strong>Computational Overhead</strong>: The HASH() function is computed on-the-fly by Snowflake for every row, which can add a performance cost on very large tables.</li></ul><h3>Strategy 2: Range Partitioning</h3><p>This strategy is effective when the partition key is numeric and reasonably well-distributed.</p><ul><li><strong>Concept</strong>: Divide the data based on ranges of the partition_key_column.</li><li><strong>Implementation</strong>:</li></ul><ol><li>Run an initial query to find the MIN() and MAX() values of the key.</li><li>Divide the total range (MAX - MIN) into N equal-sized chunks.</li><li>Each worker queries its assigned range using a BETWEEN clause.</li></ol><ul><li><strong>SQL Snippet</strong>:</li></ul><pre>WHERE partition_key_column BETWEEN %(range_start)s AND %(range_end)s</pre><p><strong>Pros</strong>:</p><ul><li><strong>High Performance</strong>: Avoids the HASH() computation and can leverage a standard index on the partition key very effectively.</li></ul><p><strong>Cons</strong>:</p><ul><li><strong>Sensitive to Skew</strong>: If data is not uniformly distributed (e.g., many records have low IDs, few have high IDs), some workers will have much more work than others.</li><li><strong>Requires Setup</strong>: Needs an initial MIN/MAX query to define the ranges.</li></ul><h3>Strategy 3: Pre-computed Hash Column</h3><p>This is an advanced optimization for performance-critical pipelines.</p><ul><li><strong>Concept</strong>: Offload the hash computation by storing the partition assignment directly in a column.</li><li><strong>Implementation</strong>:</li></ul><ol><li>Add a new column to the source table (e.g., PARTITION_HASH).</li><li>Pre-populate it with the result of MOD(ABS(HASH(...)), N).</li><li>The pipeline’s WHERE clause becomes a simple, fast filter.</li></ol><ul><li><strong>SQL Snippet</strong>:</li></ul><pre>WHERE PARTITION_HASH = %(partition_id)sWHERE PARTITION_HASH = %(partition_id)s</pre><p><strong>Pros</strong>:</p><ul><li><strong>Fastest at Query Time</strong>: The expensive computation is done upfront. The query is extremely simple and fast.</li></ul><p><strong>Cons</strong>:</p><ul><li><strong>Requires Schema Changes</strong>: Often it is not possible to modify the source table.</li><li><strong>Maintenance</strong>: The hash value must be maintained as new data is added or updated.</li></ul><h3>Pagination Strategies</h3><p>Pagination is about answering the question: “How does a worker fetch its data chunk-by-chunk?”</p><h3>Strategy 1: Keyset Pagination (Seek Method)</h3><p>This is the most efficient and scalable method for paginating over large, ordered datasets.</p><ul><li><strong>Concept</strong>: Use a WHERE clause that seeks directly to the start of the next page of data, based on the values from the last row of the current page. This requires one or more cursor_columns that create a stable sort order.</li><li><strong>Implementation (Tuple Comparison)</strong>: Snowflake’s SQL dialect supports tuple comparison, which simplifies the logic significantly.</li><li><strong>SQL Snippet</strong>:</li></ul><pre>-- For cursor columns (c1, c2) and last values (v1, v2)<br>WHERE (c1, c2) &gt; (%(v1)s, %(v2)s)<br>ORDER BY c1, c2<br>LIMIT %(batch_size)s</pre><p><strong>Pros</strong>:</p><ul><li><strong>Highly Performant</strong>: With an index on the cursor columns, the database can jump directly to the next page without scanning previous data.</li><li><strong>Stateless and Resumable</strong>: Each request is self-contained.</li><li><strong>Simple Logic</strong>: Tuple syntax is clean and easy to maintain.</li></ul><p><strong>Cons</strong>:</p><ul><li>None. This is the preferred method for modern pagination.</li></ul><h3>3. Combined Implementation Example</h3><h3>Modulo Hash Partitioning + Keyset Pagination</h3><p>This combination provides a robust solution for parallel data extraction from large tables.</p><ul><li><strong>Concept</strong>: Each worker queries its hash-assigned partition using keyset pagination to fetch data in batches.</li><li><strong>SQL Snippet</strong>:</li></ul><pre>-- Worker 2 of 10, fetching next batch after cursor position<br>SELECT *<br>FROM your_table<br>WHERE <br>    MOD(ABS(HASH(partition_key)), 10) = 2<br>    AND (id, created_at) &gt; (%(last_id)s, %(last_created_at)s)<br>ORDER BY id, created_at<br>LIMIT 1000</pre><p><strong>Key Considerations</strong>:</p><ul><li>Choose cursor columns that form a unique, indexed combination</li><li>Save cursor position after each batch for resumability</li><li>Typical batch sizes range from 1,000 to 10,000 rows</li><li>Each worker maintains its own pagination state independently</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29400889628d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Peeking Behind the Curtain: Decoding YouTube’s API Design Through Network Traffic]]></title>
            <link>https://kuangbyte.medium.com/peeking-behind-the-curtain-decoding-youtubes-api-design-through-network-traffic-e3a68463df05?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a68463df05</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[youtube]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Tue, 06 May 2025 03:25:51 GMT</pubDate>
            <atom:updated>2025-07-03T01:00:00.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvP5OTeRKY32EU8paYGOfw.jpeg" /></figure><h3>Ever Wonder How YouTube Works Under the Hood?</h3><p>Let’s face it, understanding massive systems like YouTube can feel like trying to solve a giant puzzle. But what if we could get some clues by just watching how it talks to itself? That’s exactly what we did. We took a peek at the network traffic — the conversation between your browser and YouTube’s servers — when loading the homepage and a video page. Think of it like eavesdropping on the system to understand its API design choices.</p><p><strong>How We Did It:</strong> We used the Google Chrome Developer Console’s Network tab to capture all the nitty-gritty details of the HTTP requests and responses while browsing YouTube.</p><p><strong>What We’re Looking For:</strong> This isn’t about <strong><em>every</em></strong> single request. We’re focusing on the <strong><em>patterns</em></strong> in the API calls Google uses for <strong>www.youtube.com</strong>. What can we learn about their design choices, the trade-offs they might have made, and how things like experiments or loading new content work, just by looking at the traffic from a simple, logged-out visit?</p><h3>The API Calls We Captured (And What They Seem to Do)</h3><p>When loading the YouTube homepage and a video, a few key API players showed up. Interestingly, most of the main action happens through one central hub: /youtubei/v1/. Let&#39;s break down the main ones we saw:</p><blockquote><strong>POST /youtubei/v1/guide</strong></blockquote><p><strong>Its Job:</strong> Grabs the data for that left-hand navigation menu you see (Subscriptions, History, Playlists, etc.), especially on the homepage.</p><p><strong>What it Sends:</strong> Like most /youtubei calls, it sends a standard context object stuffed with info about your browser, language, location, and more.</p><p><strong>What it Returns:</strong> Structured data that tells the browser exactly how to build that navigation menu. It uses bits called guideSectionRenderer and guideEntryRenderer – basically, the server dictates the layout.</p><pre>// A taste of the /youtubei/v1/guide response<br>&quot;items&quot;: [<br>    {<br>        &quot;guideSectionRenderer&quot;: {<br>            &quot;items&quot;: [<br>                { &quot;guideEntryRenderer&quot;: { /* ... Home link data ... */ } },<br>                { &quot;guideEntryRenderer&quot;: { /* ... Shorts link data ... */ } },<br>                { &quot;guideEntryRenderer&quot;: { /* ... Subscriptions link data ... */ } }<br>            ],<br>            &quot;trackingParams&quot;: &quot;...&quot; // For analytics<br>        }<br>    },<br>    {<br>        &quot;guideSectionRenderer&quot;: { /* ... More sections like &#39;You&#39;, History ... */ }<br>    }<br>]</pre><blockquote><strong>POST /youtubei/v1/player</strong></blockquote><p><strong>Its Job:</strong> This is the big one for watching videos. It fetches all the initial info needed to get the player working when you click on a video.</p><p><strong>What it Sends:</strong> The context object (with all your browser/user info) and, crucially, the videoId.</p><p><strong>What it Returns:</strong> A big blob of JSON containing goodies like:</p><ul><li><strong><em>playabilityStatus</em></strong>: Can you actually watch this video? This is the gatekeeper, checking for things like age restrictions, region locks, private video status, or if a Premium account is needed. If the status isn&#39;t &quot;OK&quot;, you won&#39;t get the video data.</li><li><strong><em>videoDetails</em></strong>: All the basic info you see around the player – the title, shortDescription, channelId, author, viewCount, thumbnail URLs (thumbnail.thumbnails), video length (lengthSeconds), and keywords. Essentially, the metadata describing the video.</li><li><strong><em>streamingData</em></strong>: This is the technical core for playback. It tells the browser <em>how</em> to get the actual video and audio. It includes:</li><li><strong><em>formats</em></strong>: Sometimes includes pre-combined video and audio streams (e.g., a single 360p MP4 file). These are simpler but less flexible.</li><li><strong><em>adaptiveFormats</em></strong>: The modern way! This provides a list of separate video-only streams (in codecs like H.264, VP9, or AV1, across different resolutions like 480p, 720p, 1080p) and separate audio-only streams (in codecs like AAC or Opus, at different quality levels).</li><li><strong><em>Signed URLs</em></strong>: Crucially, each format listed in streamingData comes with a url. This isn&#39;t a direct link to a simple file. It&#39;s a special, temporary, signed URL pointing to Google&#39;s video delivery servers (.googlevideo.com). These signatures guarantee that only authorized users can access the video content for a limited duration, safeguarding the content and separating the video delivery process from the main API.</li><li><strong><em>playbackTracking</em></strong>: URLs the player uses to send back analytics about your viewing experience (buffering events, quality changes, watch time) to endpoints like /api/stats/playback and /api/stats/qoe.</li><li><strong><em>captions</em></strong>: Information on available subtitles or auto-generated captions, including language options and URLs to fetch the timed text.</li><li><strong><em>storyboards</em></strong>: Data that lets the player show those thumbnail previews when you hover over or scrub the timeline.</li></ul><blockquote><strong>POST /youtubei/v1/next</strong></blockquote><p><strong>Its Job:</strong> This endpoint is the workhorse for loading more stuff <em>after</em> the initial page load, especially on the video page. Think loading more comments, more related videos, or messages in a live chat replay. It’s what powers infinite scrolling.</p><p><strong>What it Sends:</strong> The context object and a special continuation token it got from a <em>previous</em> API response (like from /player or an earlier /next call).</p><pre>// Sending a continuation token to /youtubei/v1/next<br>{<br>    &quot;context&quot;: { /* ... client context ... */ },<br>    // This token tells the server &quot;get me the next batch of comments&quot;<br>    &quot;continuation&quot;: &quot;Eg0SC1Q5TDJxdHdwZXhNGAYyJSIRIgtUOUwycXR3cGV4TTAAeAJCEGNvbW1lbnRzLXNlY3Rpb24%3D&quot;<br>}</pre><p><strong>What it Returns:</strong> Data structured to build the UI for whatever it fetched (e.g., a batch of comments). And critically, it often includes a <em>new</em> continuation token so the client can ask for <em>even more</em> data if you keep scrolling.</p><pre>// A snippet from the /youtubei/v1/next response (loading comments)<br>  &quot;onResponseReceivedEndpoints&quot;: [<br>      {<br>          &quot;reloadContinuationItemsCommand&quot;: {<br>              &quot;targetId&quot;: &quot;comments-section&quot;, // Tells the client where to put this data<br>              &quot;continuationItems&quot;: [<br>                  { &quot;commentsHeaderRenderer&quot;: { /* ... Comment count, sort options ... */ } },<br>                  { &quot;commentThreadRenderer&quot;: { /* ... Data for the first comment thread ... */ } },<br>                  { &quot;commentThreadRenderer&quot;: { /* ... Data for the second comment thread ... */ } },<br>                  {<br>                      // This holds the key to loading *more* comments<br>                      &quot;continuationItemRenderer&quot;: {<br>                          &quot;continuationEndpoint&quot;: {<br>                              &quot;continuationCommand&quot;: {<br>                                  // The *next* token for the *next* batch of comments<br>                                  &quot;token&quot;: &quot;...&quot;<br>                              }<br>                          }<br>                      }<br>                  }<br>              ]<br>          }<br>      }<br>  ]</pre><p><strong>Logging Endpoints</strong></p><p><strong>Their Job:</strong> YouTube sends back various bits of operational data using different endpoints. We saw a few:</p><blockquote><strong>POST /youtubei/v1/log_event</strong></blockquote><p>Probably logs specific things you do in the browser (clicks, interactions) within the main YouTube app context.</p><blockquote><strong><em>POST play.google.com/log</em></strong></blockquote><p>This one received super-compact, hard-to-read data. It looks like a shared Google endpoint designed to handle huge amounts of general telemetry (performance stats, errors, basic usage) from many different Google products efficiently.</p><pre>// A highly simplified look at the compact log data structure<br>&quot;[[1,null,...,[[[&quot;ClientInfo&quot;,&quot;Version&quot;]...]],...],&lt;timestamp&gt;,[[&quot;&lt;request_id&gt;&quot;,null,...&quot;[[[/client_streamz/...]]]&quot;...]]]&quot;</pre><blockquote><strong><em>POST </em></strong><a href="http://www.youtube.com/api/stats/qoe"><strong><em>www.youtube.com/api/stats/qoe</em></strong></a></blockquote><p>This popped up on the video page. &quot;QoE&quot; likely means Quality of Experience – sending data specific to how well the video is streaming (buffering, quality changes, etc.).</p><blockquote><strong><em>POST www.youtube.com/videoplayback</em></strong></blockquote><p><strong>Their Job:</strong> These aren’t part of the /youtubei API. They&#39;re the actual Content Delivery Network (CDN) servers that dish out the video and audio bits.</p><p><strong>How they’re Accessed:</strong> The /youtubei/v1/player response gives the browser special, signed URLs pointing to these servers. The browser then uses these URLs to stream the media directly.</p><h3>Key Patterns We Noticed (And Why They Matter)</h3><p>Looking across these different API calls, some clear design patterns emerge, shaped by the need to operate at a mind-boggling scale and evolve constantly:</p><p><strong>One Gateway to Rule Them All (</strong><strong>/youtubei/v1/...): </strong>Nearly all the core requests go through this single, versioned entry point. It feels very much like an API Gateway or a Backend-for-Frontend (BFF).</p><ul><li><strong>Why?</strong> This gives the web app a single, consistent place to talk to, simplifying frontend logic.</li></ul><p><strong>POST All the Things!:<em> </em></strong>Even when just fetching data (like the guide or player info), YouTube uses POST requests.</p><ul><li><strong>Why?</strong> It’s almost certainly because of that big context object they need to send every time. Stuffing that into a POST body is easier and avoids ridiculously long URLs you might get with GET. Practicality wins over strict REST rules here; it prioritizes convenience and data richness over strictly following the HTTP rulebook.</li></ul><p><strong>The All-Knowing </strong><strong>context Object:</strong> This JSON object sent with every /youtubei call is packed with info: client version, OS, browser, language (hl), location (gl), a persistent visitorData ID (even if you&#39;re not logged in), and crucially, experiment flags.</p><ul><li><strong>Why?</strong> Sending so much client info might seem heavy, but it’s key to how YouTube works. It powers personalization, A/B testing, feature flags, and helps diagnose issues specific to certain environments. The backend doesn’t need to remember who you are between requests (it’s stateless); you tell it everything it needs each time.</li></ul><pre>&quot;context&quot;: {<br>    &quot;client&quot;: {<br>        &quot;hl&quot;: &quot;en-GB&quot;, // Language<br>        &quot;gl&quot;: &quot;CA&quot;,    // Geographic Location<br>        &quot;visitorData&quot;: &quot;Cgs1dmJjbzN4TXVoQSjr8bvABjIKCgJDQRIEGgAgTQ%3D%3D&quot;, // Unique ID for this browser session<br>        &quot;clientName&quot;: &quot;WEB&quot;,<br>        &quot;clientVersion&quot;: &quot;2.20250425.01.00&quot;,<br>        // ... screen size, OS, browser details ...<br>        &quot;configInfo&quot;: { /* ... data related to experiments ... */ },<br>        &quot;rolloutToken&quot;: &quot;...&quot;, // More experiment stuff<br>        &quot;deviceExperimentId&quot;: &quot;...&quot; // And more!<br>    },<br>    &quot;user&quot;: { /* ... empty if not logged in ... */ },<br>    &quot;request&quot;: { /* ... request specifics ... */ },<br>    &quot;adSignalsInfo&quot;: { /* ... info for ads ... */ }<br>}</pre><p><strong>Experiments Baked In:</strong> YouTube is clearly built for A/B testing. Experiment IDs (configInfo, rolloutToken, deviceExperimentId in the request context; numerical IDs under the &quot;e&quot; key in responseContext.serviceTrackingParams) are passed back and forth constantly.</p><ul><li><strong>Why?</strong> It’s clear A/B testing isn’t just <em>a</em> feature, it’s <em>core</em> to YouTube’s development process. Attaching the full context (with experiment flags) to <em>every</em> request allows the backend to make immediate, tailored decisions <em>for that specific interaction</em> without needing to maintain complex user state, crucial for real-time personalization at scale. While this increases payload size compared to fetching experiment configs separately upfront (a common pattern in other frameworks), YouTube likely prioritizes the benefits of a stateless backend and making decisions based on the absolute latest context for <em>every</em> request, accepting the overhead as a necessary trade-off for its dynamic nature and scale.</li></ul><pre>// Example of experiment IDs returned in a response context<br>&quot;responseContext&quot;: {<br>    &quot;serviceTrackingParams&quot;: [<br>        {<br>            &quot;service&quot;: &quot;GFEEDBACK&quot;, // Just an example service name<br>            &quot;params&quot;: [<br>                // The &#39;e&#39; key often holds a comma-separated list of active experiment IDs<br>                { &quot;key&quot;: &quot;e&quot;, &quot;value&quot;: &quot;51010235,51020570,51089474, ...&quot; }<br>            ]<br>        }<br>        // ... might be other tracking parameters ...<br>    ]<br>    // ...<br>}</pre><p><strong>Server-Driven UI (SDUI): T</strong>he API doesn’t just send raw data; it sends instructions on how to build the UI. Responses for the guide, feeds (/browse), and dynamic content (/next) contain chunks like guideSectionRenderer, commentThreadRenderer, or videoRenderer.</p><ul><li><strong>Why? Agility.</strong> YouTube changes <em>all the time</em>. SDUI lets them change layouts, test features, and personalize content just by altering the API response, often without needing app updates. The backend sends structured data (like JSON) describing <em>what</em> UI components to show (buttons, lists, video renderers) and <em>how</em> they should look and behave. The client app then simply interprets this data and renders the appropriate native components. (Unlike a WebView approach, which renders server-sent web content directly, SDUI uses server descriptions to build the UI from the client’s own native building blocks.) While powerful, testing SDUI requires care, often involving API contract tests (did the server send valid components?) and visual checks to catch rendering bugs. Although specific open-source SDUI frameworks are rare due to tight coupling with specific stacks, the pattern relies on this backend definition/client interpretation model, often built custom using standard technologies.</li></ul><p><strong>Continuation Tokens: </strong>For infinite scrolling feeds like comments or related videos, tokens are superior to page numbers.</p><ul><li><strong>Why? Reliability.</strong> Page numbers become unreliable when content changes frequently (causing missed or duplicate items). Tokens act as stable cursors, ensuring the server can always fetch the correct <em>next</em> batch of items relative to the last one seen, providing a seamless user experience despite underlying data changes. The cost is losing random access (can’t jump to page 10), but for dynamically updating feeds, smoothness and accuracy win.</li></ul><p><strong>Logging: </strong>YouTube doesn’t use a one-size-fits-all approach for logging. High-volume, general stuff goes to that optimized play.google.com/log endpoint. Specific things like video streaming quality (/api/stats/qoe) get their own dedicated path.</p><ul><li><strong>Why? Optimization and Organization.</strong> The super-compact format for play.google.com/log screams &quot;optimization for massive volume,&quot; likely leveraging shared Google infrastructure. Keeping specific logs (like QoE) separate keeps things organized – different data needs different handling.</li></ul><p><strong>Separating Data from Video:</strong> The /youtubei APIs handle the metadata (titles, descriptions, comments, URLs) and UI structure. The <em>actual</em> video and audio streaming uses completely separate .googlevideo.com domains.</p><ul><li><strong>Why? Performance and Scale.</strong> This is a standard CDN pattern and absolutely essential. It keeps the heavy lifting of high-bandwidth video delivery separate from the API calls, crucial for making YouTube perform well globally. Imagine the /youtubei API trying to handle video streaming too!</li></ul><h3>So, What Did We Learn?</h3><p>Peeking under the hood of a giant like YouTube, even just by watching its network chatter, reveals a lot about how modern web applications are built at scale. We didn’t need secret blueprints; the clues were right there in the API calls.</p><p>We saw how a central API gateway (/youtubei/v1/) brings order to the chaos, how practical choices (like using POST for nearly everything) win out, and how a rich context object fuels everything from A/B testing to personalization. The clever use of server-driven UI gives YouTube its flexibility, while continuation tokens ensure smooth scrolling, and separating video delivery keeps things speedy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a68463df05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Examples and tips for making your feedback cycles more collaborative and productive]]></title>
            <link>https://kuangbyte.medium.com/effective-code-review-comments-asking-and-replying-e37adde7ec6a?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/e37adde7ec6a</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 02:43:08 GMT</pubDate>
            <atom:updated>2025-04-28T02:53:01.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Code reviews are a cornerstone of healthy software development. They catch bugs, improve design, share knowledge, and maintain standards. But let’s be honest, they can also be a source of friction if not handled well.</p><p>The difference often lies in <em>how</em> we communicate. A poorly phrased comment can feel like an attack, while a vague reply leaves the reviewer guessing. Conversely, thoughtful questions and constructive responses turn reviews into collaborative problem-solving sessions.</p><p>This guide explores common code review scenarios, offering concrete examples of effective (and ineffective) ways to phrase comments as a reviewer and respond as the author. Let’s make our code reviews better, together!</p><h3>Key Principles for Better Reviews</h3><p>Before diving into scenarios, keep these general principles in mind:</p><ul><li><strong>Assume Good Intent:</strong> Start from the position that both the reviewer and the author want the best outcome for the code and the team.</li><li><strong>Be Specific and Constructive:</strong> Vague comments like “Fix this” aren’t helpful. Explain <em>why</em> something needs changing and, if possible, suggest <em>how</em>.</li><li><strong>Phrase as Questions or Suggestions:</strong> Instead of demanding changes (“Use Algorithm X”), try asking questions (“Have you considered Algorithm X? What are the trade-offs?”).</li><li><strong>Use a Conversational Tone:</strong> Adapt your phrasing based on context and relationship. Natural language and contractions (it’s, don’t) often work well.</li><li><strong>Acknowledge and Follow Up:</strong> If a comment raises a valid point that’s out of scope, acknowledge it! Suggest creating a ticket or follow-up task (e.g., “Good point! That’s a great idea for a follow-up. I’ve created ticket #XYZ to track this.”).</li></ul><h3>Common Code Review Scenarios</h3><p>Here are breakdowns of common situations, showing both sides of the conversation:</p><h3>Scenario: Code lacks clarity or seems overly complex</h3><ul><li><strong>Goal:</strong> Improve readability and maintainability.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “This is hacky.” / “Confusing.” <em>(Vague, accusatory)</em></li><li><em>Try These:</em></li><li>“I’m having trouble following the logic here. Could we perhaps simplify it or add a comment explaining the approach? I’m concerned about long-term maintainability.” <em>(Focuses on goal, collaborative)</em></li><li>“Could you walk me through this part? Maybe we can find a way to make it clearer for future maintainers.” <em>(Invites discussion)</em></li><li>“Perhaps renaming variable_foo to user_input_buffer could improve clarity here?&quot; <em>(Specific suggestion)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “I’m having trouble following the logic…”)</em></li><li><em>Avoid This:</em> “It’s not complex, it works fine.” / “It’s obvious.” <em>(Dismissive)</em></li><li><em>Try These:</em></li><li>“[Thanks!] You’re right, it was a bit dense. I’ve added comments/refactored this section/renamed variable_foo to user_input_buffer. Let me know if it&#39;s clearer now. Updated.&quot;</li><li>“[Thanks for looking closely.] I chose this approach due to [specific reason]. I’ve added comments explaining the trade-offs. Does that help clarify?” <em>(Explains rationale)</em></li></ul><h3>Scenario: Logic seems duplicated or could be reused</h3><ul><li><strong>Goal:</strong> Promote code reuse and reduce redundancy.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Why didn’t you abstract this?” <em>(Demanding)</em></li><li><em>Try These:</em></li><li>“This logic looks potentially reusable. Do you think it makes sense to abstract it now, or is it premature?” <em>(Opens discussion)</em></li><li>“I noticed similar logic in [other location]. Could we potentially create a shared helper?” <em>(Specific, constructive)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “This logic looks potentially reusable…”)</em></li><li><em>Avoid This:</em> “No.” / “It’s fine like this.” <em>(Uncooperative)</em></li><li><em>Try These:</em></li><li>“[Good suggestion.] I’ve extracted it into new_helper_function(). Fixed.&quot;</li><li>“[Makes sense.] Abstracted.”</li><li>“I considered that, but since it’s only used here, I worried an abstraction might be overkill (YAGNI). Happy to abstract it if you feel strongly, though.” <em>(Explains reasoning, still collaborative)</em></li></ul><h3>Scenario: A different approach might be better</h3><ul><li><strong>Goal:</strong> Suggest an alternative constructively and understand the author’s choices.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Use Algorithm X.” <em>(Prescriptive)</em></li><li><em>Try These:</em></li><li>“Have you considered Algorithm X here? I wonder if it might offer [specific benefit]. What were the reasons for choosing the current algorithm?” <em>(Invites discussion, asks for rationale)</em></li><li>“Another way we could approach this is [describe alternative]. What do you think about the trade-offs?” <em>(Offers alternative for consideration)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Have you considered Algorithm X?”)</em></li><li><em>Avoid This:</em> “This way is better.” / “Algorithm X is bad.” <em>(Dismissive, lacks justification)</em></li><li><em>Try These:</em></li><li>“[Great point!] I looked into Algorithm X, and you’re right, it seems like a better fit. I’ll make the change. Updated.”</li><li>“[Thanks for the suggestion.] I evaluated Algorithm X, but went with the current one because [concise reasoning…]. Let me know if you think that reasoning is sound.” <em>(Justifies choice, invites further discussion)</em></li></ul><h3>Scenario: Potential bug or edge case identified</h3><ul><li><strong>Goal:</strong> Highlight a potential issue and ensure it’s handled correctly.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “This will crash if input is null.” <em>(Accusatory, assumes certainty)</em></li><li><em>Try These:</em></li><li>“What’s the expected behavior if input is null here? Should we add a check?&quot; <em>(Focuses on behavior)</em></li><li>“I’m wondering about the edge case where [describe scenario]. How is that handled?” <em>(Inquires politely)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “What’s the expected behavior if </em><em>input is null?&quot;)</em></li><li><em>Avoid This:</em> “That won’t happen.” / “It should be obvious.” <em>(Dismissive, potentially incorrect)</em></li><li><em>Try These:</em></li><li>“[Good catch!] That was an oversight. Added a null check and a test. Fixed.”</li><li>“[Ah, right.] Added a check. Thanks!”</li><li>“[Thanks for asking.] In this flow, input is guaranteed by [upstream validation] not to be null. Should I add an assert to make this explicit?&quot; <em>(Explains guarantee, suggests clarification)</em></li></ul><h3>Scenario: Minor stylistic or naming issue (Nitpick)</h3><ul><li><strong>Goal:</strong> Suggest small improvements for consistency or clarity without overstating their importance.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Fix this naming.” <em>(Blunt)</em></li><li><em>Try These:</em></li><li>“Nit: Could we rename temp to user_profile_data for clarity?&quot; <em>(Labels as minor)</em></li><li>“Small suggestion: Maybe align these params vertically?” <em>(Clearly optional)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Nit: Could we rename </em><em>temp?&quot;)</em></li><li><em>Avoid This:</em> “Who cares?” / “This name is fine.” <em>(Dismissive)</em></li><li><em>Try These:</em></li><li>“Done. Renamed.”</li><li>“[Good suggestion.] Renamed. Fixed.”</li><li>“Hmm, temp is used consistently here for this. Kept it for consistency, but happy to change if you feel strongly.&quot; <em>(Polite disagreement with rationale)</em></li></ul><h3>Scenario: Tests seem missing or insufficient</h3><ul><li><strong>Goal:</strong> Ensure adequate test coverage.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Needs tests.” <em>(Vague)</em></li><li><em>Try These:</em></li><li>“Could you add a test case for the empty list scenario?” <em>(Specific request)</em></li><li>“How is this logic tested? I couldn’t find a test for the error handling path.” <em>(Asks about coverage)</em></li></ul><p><strong>Replying (Responding to the Comment)</strong></p><ul><li><em>(Example Reviewer Comment: “Could you add a test case for the empty list?”)</em></li><li><em>Avoid This:</em> “It doesn’t need a test.” <em>(Undermines quality)</em></li><li><em>Try These:</em></li><li>“[Good point.] Added a test for the empty list scenario. Updated.”</li><li>“[Makes sense.] Added test_empty_input. Fixed.&quot;</li><li>“This is covered by the integration test in test_integration.py. Should I add a specific unit test here too for clarity?&quot; <em>(Points to existing test, asks for preference)</em></li></ul><h3>Scenario: Potential performance issue</h3><ul><li><strong>Goal:</strong> Raise performance concerns constructively.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “This is slow.” <em>(Assertion without evidence)</em></li><li><em>Try These:</em></li><li>“I’m slightly concerned about performance here if this list gets large. Have you benchmarked this or considered [alternative]?” <em>(Expresses concern, asks for data/alternatives)</em></li><li>“Is there a potential performance implication if this is called frequently in a loop?” <em>(Asks about context)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “I’m concerned about performance…”)</em></li><li><em>Avoid This:</em> “It’s fast enough.” / “Don’t worry about it.” <em>(Dismissive, lacks evidence)</em></li><li><em>Try These:</em></li><li>“[Thanks!] Ran a benchmark for N=10k, completed in X ms, which seems acceptable. Let me know if you foresee larger inputs.”</li><li>“[You’re right,] performance could be an issue. Switched to [alternative approach]. Updated and added a benchmark.”</li><li>“[Good point.] Haven’t benchmarked formally, but based on [reasoning], didn’t anticipate issues. Can add a benchmark if needed.” <em>(Provides reasoning, offers to benchmark)</em></li></ul><h3>Scenario: Reason for a change or approach is unclear</h3><ul><li><strong>Goal:</strong> Politely ask for context or explanation.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Why?” <em>(Abrupt)</em></li><li><em>Try These:</em></li><li>“Could you add a quick comment explaining the reasoning here?” <em>(Polite request)</em></li><li>“What was the motivation for this change? Understanding the background helps.” <em>(Explains why you’re asking)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Could you add a comment explaining the reasoning?”)</em></li><li><em>Avoid This:</em> “Because.” / “Legacy code.” <em>(Unhelpful)</em></li><li><em>Try These:</em></li><li>“[Good question.] Chose this because [brief reason…]. Added a comment. Updated.”</li><li>“[Makes sense.] Added comments explaining the rationale. Fixed.”</li></ul><h3>Scenario: Potential security concern</h3><ul><li><strong>Goal:</strong> Raise potential security vulnerabilities constructively.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “This is insecure.” <em>(Needs specifics)</em></li><li><em>Try These:</em></li><li>“Is there a risk of [XSS] here? Should we sanitize this input?” <em>(Specific concern, suggests action)</em></li><li>“Could this expose sensitive data if an exception occurs here?” <em>(Highlights risk)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Is there a risk of XSS here?”)</em></li><li><em>Avoid This:</em> “That’s handled elsewhere.” / “Not a risk.” <em>(Dismissive unless explained)</em></li><li><em>Try These:</em></li><li>“[Excellent catch!] Input wasn’t sanitized. Added validation. Updated.”</li><li>“[Thanks.] This data comes from [trusted source], not user input. Added an assertion just to be safe. Updated.”</li><li>“[Good question.] Reviewed the risk and implemented [mitigation]. Fixed.”</li></ul><h3>Scenario: Documentation seems missing or insufficient</h3><ul><li><strong>Goal:</strong> Request necessary documentation (code comments, README updates, etc.).</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Needs docs.” <em>(Vague)</em></li><li><em>Try These:</em></li><li>“Could we add a docstring/comment explaining this function/class?” <em>(Specific request)</em></li><li>“Does the README need an update for these API changes?” <em>(Considers broader impact)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Could we add a docstring?”)</em></li><li><em>Avoid This:</em> “Code is self-documenting.” <em>(Rarely true)</em></li><li><em>Try These:</em></li><li>“[Good point.] Added docstring/comments. Updated.”</li><li>“[Right.] Updated the README. Fixed.”</li></ul><h3>Scenario: Deviation from established patterns or architecture</h3><ul><li><strong>Goal:</strong> Understand adherence to project standards.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “This is wrong.” / “Why not do it the standard way?” <em>(Accusatory)</em></li><li><em>Try These:</em></li><li>“Our usual pattern here is [describe pattern]. Was there a reason to deviate?” <em>(Highlights standard, asks politely)</em></li><li>“How does this fit into the overall [XYZ] architecture?” <em>(Seeks clarification)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Our usual pattern is X…”)</em></li><li><em>Avoid This:</em> “Because I like this way better.” <em>(Ignores standards)</em></li><li><em>Try These:</em></li><li>“[Ah, missed that.] Refactored to follow the pattern. Updated.”</li><li>“[Good question.] Deviated because [technical reason…]. Added a comment explaining. Let me know if that makes sense.” <em>(Provides rationale)</em></li></ul><h3>Scenario: Potential API design issue</h3><ul><li><strong>Goal:</strong> Suggest improvements to API contracts for clarity or usability.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “This API sucks.” <em>(Unprofessional)</em></li><li><em>Try These:</em></li><li>“For this API, would user_id be clearer than uid for consumers?&quot; <em>(Specific suggestion)</em></li><li>“Should this return ItemNotFoundError instead of a generic Exception for better error handling?&quot; <em>(Focuses on usability)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Would renaming this parameter improve clarity?”)</em></li><li><em>Avoid This:</em> “The name is fine.” <em>(Dismissive)</em></li><li><em>Try These:</em></li><li>“[Good suggestion.] Renamed parameter/Updated return type. Fixed.”</li><li>“Hmm, kept uid for consistency with [related APIs]. Is deviating worth the inconsistency here?&quot; <em>(Opens discussion on trade-offs)</em></li></ul><h3>Scenario: Questioning a new dependency</h3><ul><li><strong>Goal:</strong> Understand the need for a new dependency.</li></ul><p><strong>Asking</strong></p><ul><li><em>Avoid This:</em> “Why add this library?” <em>(Can sound challenging)</em></li><li><em>Try These:</em></li><li>“Could we achieve this using existing dependencies (like [existing_library]) instead of adding [new_library]?&quot; <em>(Asks about alternatives)</em></li><li>“What’s the main benefit of adding [new_library]? Just want to understand the trade-offs.&quot; <em>(Seeks justification)</em></li></ul><p><strong>Replying</strong></p><ul><li><em>(Example Reviewer Comment: “Could we achieve this without adding </em><em>[new_library]?&quot;)</em></li><li><em>Avoid This:</em> “No.” <em>(Uncooperative)</em></li><li><em>Try These:</em></li><li>“[Good question.] Tried [existing_library] but hit [limitation]. [new_library] handles this much better. Happy to elaborate.&quot;</li><li>“[You’re right.] Re-evaluated and managed with [existing_library]. Removed the dependency. Updated.&quot;</li><li>“[Thanks.] The benefit is [cleaner code/better performance]. Felt the trade-off was worthwhile.”</li></ul><h3>Final Thoughts</h3><p>Effective code review communication is a skill that improves with practice. By focusing on clarity, collaboration, and constructive feedback, we can make the review process smoother, more educational, and ultimately lead to better software.</p><p>Remember to adapt these examples to your team’s culture and the specific context of the review. Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e37adde7ec6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake in Your Critical Path: Hear Me Out, It Might Not Be Terrible]]></title>
            <link>https://kuangbyte.medium.com/snowflake-in-your-critical-path-hear-me-out-it-might-not-be-terrible-957cdbf0c683?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/957cdbf0c683</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 04:03:17 GMT</pubDate>
            <atom:updated>2025-05-07T02:22:38.210Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Why the “right tool for the job” isn’t always the full story when your critical service hits a snag.</blockquote><p>We’ve all heard the mantra: “Use the right tool for the job.”</p><p>In the world of data, this usually translates to a clear division of labor. Use databases like PostgreSQL for the fast, small requests needed by live user applications (think processing an order, fetching a profile). For complex analysis across massive datasets, such as determining quarterly sales trends, utilize powerful data warehouses like Snowflake.</p><p>One is a speedboat, the other a cargo ship. Simple, right?</p><p>So, when a critical online service — let’s call it PumpkinService — suddenly slows to a crawl, frustrating users trying to check out, the culprit is often traced back to an unexpected place. Imagine finding out it’s because a long-running, complex query hitting your Snowflake data warehouse is hogging all the resources.</p><blockquote>The immediate reaction? “Well, obviously! We shouldn’t use a data warehouse for live service requests!”</blockquote><p>And honestly? Often, that gut reaction is correct. A traditional database like PostgreSQL is usually purpose-built for the kind of quick, transactional workload PumpkinService needs.</p><h3>But Hold On — Is It Always That Simple?</h3><p>Let’s consider the messy reality, especially for a growing startup. Maybe your team is small, deeply invested in Snowflake for analytics, and lacks the resources or expertise to stand up, manage, secure, <em>and</em> synchronize data with a completely separate PostgreSQL cluster. AWS Aurora resource is not free, right?</p><p>Does the “right tool” mantra still hold if adopting it means significant operational overhead, potential data consistency headaches, and delays to critical features?</p><p>This forces us to ask a different, perhaps more pragmatic question:</p><p><strong><em>If constraints push us toward using a tool like Snowflake outside its primary comfort zone, how can we make it work as safely and effectively as possible?</em></strong></p><p>Looking back at our PumpkinService incident, the core issue wasn’t merely <em>that</em> Snowflake was involved. It was a specific, unbounded query — a request without proper limits — that ran wild. This suggests the problem might be less about the inherent nature of Snowflake and more about the lack of engineering rigor and guardrails around how it was being queried in a critical path.</p><h3>Making Snowflake Work (Carefully!) for Live(ish) Requests</h3><p>Using Snowflake for faster, user-facing tasks demands meticulous planning, especially around compute performance. If constraints push you this way, Snowflake provides detailed documentation on optimizing warehouse performance, covering key strategies. Focus on these core areas, leveraging Snowflake’s capabilities:</p><ol><li><strong>Optimize Queries &amp; Data Layout (Prerequisite)</strong></li><li><strong>Actively Manage Warehouse Queues &amp; Concurrency</strong></li><li><strong>Ensure Adequate Warehouse Resources (Size &amp; Memory)</strong></li><li><strong>Consider Advanced Acceleration (Where Applicable)</strong></li><li><strong>Set Strict Timeouts</strong></li></ol><p>By focusing on these optimizations, guided by Snowflake’s own recommendations (check their docs for details!) and utilizing its features alongside essential practices like external caching, you can build more resilient systems when pushing Snowflake toward latency-sensitive use cases.</p><p>Just remember, though: <strong>none of this Snowflake magic is free.</strong> Running bigger warehouses, auto-scaling them with MCW, maybe adding QAS, plus building and managing that external cache — it all costs Snowflake credits and adds complexity for your team. <strong>Definitely do the math!</strong> You might just find that after layering on all the necessary workarounds, the total cost and headache start looking suspiciously like… maybe just running a managed PostgreSQL instance (like AWS RDS) would have been simpler and cheaper all along. Funny how that happens, right?</p><h3>Looking Deeper: It’s Often About the Engineering Details</h3><p>When issues arise with PumpkinService, it&#39;s easy to place the blame solely on Snowflake. But often, that masks a simpler, more fundamental truth: maybe we didn’t sweat the details of how we were using it. The real issue frequently lies in engineering discipline.</p><blockquote>Thinking Through Edge Cases</blockquote><p>Did the team designing PumpkinService take into account the possibility of a Snowflake query being unexpectedly slow under load? Were backup plans, sensible defaults, or graceful degradation paths considered?</p><blockquote>Building Robust Safety Nets</blockquote><p>Why could a potentially long-running query execute in a critical user path without strict limits? Basic safety measures like timeouts (<strong>STATEMENT_TIMEOUT_IN_SECONDS</strong> is right there!) and resource isolation (dedicated warehouses) are essential, regardless of the database.</p><blockquote>Honest Trade-offs vs. Convenience</blockquote><p>Was Snowflake chosen after carefully weighing the risks and implementing necessary safeguards? Or was it picked simply because “it’s what we have,” without fully committing to the extra engineering rigor required to use it outside its primary analytical comfort zone?</p><p>Sometimes, despite the theoretical advantages of another tool, Snowflake is the only practical choice. Perhaps your team lives and breathes Snowflake, the data is already there, and spinning up and maintaining a separate database service isn’t feasible right now. That’s a valid constraint. But choosing Snowflake under constraint doesn’t absolve engineers of responsibility; it heightens it. If Snowflake must be used for a latency-sensitive task, then applying those safeguards—aggressive timeouts, isolated compute, smart caching, and rigorous testing—isn’t just recommended; it’s absolutely critical to avoid impacting users and businesses.</p><p>It’s also interesting how often we overlook the flexibility of tools we do have. Many engineers might be surprised to learn PostgreSQL can handle some pretty hefty analytical tasks with the right extensions and tuning, just as Snowflake can serve faster queries if engineered with extreme care. Deeply understanding the capabilities and limits of your chosen tools is key.</p><h3>Wrapping Up: Beyond the “Right Tool”</h3><p>So, should you use Snowflake in your critical, user-facing, low-latency path?</p><p>The standard, and often correct, advice is probably not your first choice. Databases like PostgreSQL are generally faster, cheaper per-query, and simpler for that specific job.</p><p>However, the PumpkinService story serves as a crucial reminder: when things break, the failure often lies deeper than just the name of the database. It’s frequently rooted in the engineering practices (or lack thereof) surrounding its use.</p><p>If practical constraints lead you down the path of using Snowflake for faster queries:</p><ul><li>Know its limits and strengths intimately.</li><li>Design defensively with timeouts, isolation, and aggressive caching.</li><li>Build (or buy) the necessary abstraction layers.</li><li>Test, test, and test again under realistic conditions.</li></ul><p>Using a tool outside its primary comfort zone demands <em>more</em> careful planning and rigorous execution, not less. Instead of just asking “Which tool?”, let’s also consistently ask, “How robustly did we build this?”</p><p>That’s often where the most important answers lie.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=957cdbf0c683" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices vs. Monolith: Are You Solving the Right Problem?]]></title>
            <link>https://kuangbyte.medium.com/we-may-not-need-microservice-right-now-9043a42f618d?source=rss-18fe091d97fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9043a42f618d</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[monolithic]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Hao Kuang]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 15:08:20 GMT</pubDate>
            <atom:updated>2025-04-28T03:13:30.066Z</atom:updated>
            <content:encoded><![CDATA[<p>I often see teams rushing towards microservices, drawn by the hype. But let’s pause and think: while microservices have their place, are we underestimating the baggage they bring compared to a good old monolith?</p><p>Part of this trend might stem from how we practice system design, especially in interviews. We often reach for the microservice pattern as a way to demonstrate handling scale and complexity. While useful in that context, it can inadvertently create the impression that it’s the <em>only</em> or <em>always</em> the right answer — a silver bullet it rarely is in practice.</p><h3>The Allure vs. The Reality</h3><p>Microservices promise modularity, letting teams work independently and potentially faster. That sounds great, right? But this path is paved with new complexities: service coordination, tricky inter-service communication, ensuring data stays consistent across services, and a significant bump in operational overhead. Don’t forget robust monitoring, logging, and security across <em>every single service</em>.</p><p>On the flip side, a monolith keeps everything in one place. Initially, this simplifies development, testing, and deployment. Sure, it can get bulky and slow things down if not managed well, mainly due to tight coupling making changes ripple unexpectedly.</p><h3>Is Scalability the Real Bottleneck?</h3><p>Insights from major players like DoorDash suggest scaling isn’t always the monolith’s fatal flaw. Often, the real drag is <strong>developer productivity</strong>. When the codebase becomes a tangled web, developers slow down, regardless of how well the application <em>technically</em> scales.</p><p>Successfully switching to microservices isn’t just a technical change; it demands shifts in infrastructure, team structure, and how developers work. That’s a steep learning curve with inherent risks.</p><h3>Questioning the Microservice Mandate</h3><p>Before jumping on the bandwagon, we need to ask some tough questions, driven by actual data, not just gut feelings:</p><ul><li><strong>Is Business Growth Hindered?</strong> Are we genuinely unable to meet business needs with our current setup?</li><li><strong>Is Development Speed Suffering?</strong> Can we <em>prove</em> with metrics that the monolith is slowing developers down, or could improvements in CI/CD or code structure help?</li><li><strong>Strategic Service Planning?</strong> Do we have a clear, strategic plan for <em>why</em> a new service is needed, or are we just carving things off arbitrarily?</li><li><strong>What Are the True Costs?</strong> Have we realistically estimated the operational overhead, infrastructure changes, and potential team retraining involved?</li><li><strong>Data Integration Challenges?</strong> If each service owns its database, how will we handle queries or processes needing data from multiple services? This is often non-trivial.</li><li><strong>Debugging Distributed Systems?</strong> Do we have the tooling for effective distributed tracing and debugging? Pinpointing issues across service calls can be incredibly difficult without it.</li></ul><p>Google’s research paper ‘Towards Modern Development of Cloud Applications’ even critiques how microservices often conflate logical design boundaries with physical deployment boundaries, hinting that there might be better ways to structure modern applications. For many companies lacking Google’s resources, deep analysis like this isn’t feasible, making careful upfront consideration even more critical.</p><h3>A More Measured Approach</h3><p>Instead of a default “microservices!” answer, let’s reconsider. Maybe the goal isn’t a full rewrite but enhancing developer productivity within the monolith. Often, we underestimate what existing tools, patterns, or focused refactoring within the current system can achieve; creating a new service can seem like an easier path initially, but might sidestep necessary improvements. Or perhaps a hybrid approach makes sense, strategically introducing <em>a few</em> well-defined services for specific, high-impact areas.</p><p>The key takeaway? <strong>It’s easy to draw boundaries, but incredibly hard (and expensive) to redraw them later.</strong> Make decisions based on clear needs and data, not just the architectural trend of the day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9043a42f618d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>