<?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"><channel><title><![CDATA[Alvin Crespo | Engineering Leader]]></title><description><![CDATA[Welcome! Here, software development meets creativity and quirkiness. Hopefully, you'll find my tutorials and random thoughts insightful and inspiring for all your software adventures.]]></description><link>https://alvincrespo.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 14:26:29 GMT</lastBuildDate><atom:link href="https://alvincrespo.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Managing Context and Memory for OpenAI API Chat Applications]]></title><description><![CDATA[Build contextually aware chat apps using OpenAI’s API by managing memory, roles, and implementing guardrails efficiently]]></description><link>https://alvincrespo.hashnode.dev/managing-context-and-memory-for-openai-api-chat-applications</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/managing-context-and-memory-for-openai-api-chat-applications</guid><category><![CDATA[AI]]></category><category><![CDATA[openai]]></category><category><![CDATA[chatbot]]></category><category><![CDATA[context engineering]]></category><category><![CDATA[#PromptEngineering]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 10 Nov 2025 23:06:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/BTf1Yh9tGsA/upload/73787d71e543f8fd191525096fe9468f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Here's something that might surprise you: The OpenAI API doesn't remember anything between API calls. Each request is completely isolated, with no built-in memory of what you just discussed. So how do applications like ChatGPT maintain those fluid, contextually aware conversations where the AI remembers what you're talking about from three messages ago?</p>
<p>When I first started working with the OpenAI API during my recent course, I expected some kind of session management or conversation ID that would handle context automatically. Instead, I discovered that building conversational AI means you're the memory keeper - you literally send the entire conversation history with every single API call. It's not the architecture I expected, but once you understand it, you realize it gives you complete control over what the AI "remembers."</p>
<p>In this post, I'll walk you through the exact patterns needed to build stateful conversations with the OpenAI API. We'll explore the three-role system that makes it all work, implement conversation memory that persists across API calls, and set up guardrails to keep your AI on track. By the end, you'll have a working implementation of a contextually aware chatbot and the knowledge to build much more sophisticated conversational AI applications.</p>
<hr />
<h2 id="heading-understanding-the-three-roles">Understanding the Three Roles</h2>
<p>The OpenAI API structures every conversation around three distinct roles:</p>
<ul>
<li><p><strong>System</strong>: Your backstage director that sets the AI's personality, expertise, and boundaries for the entire conversation</p>
</li>
<li><p><strong>User</strong>: The human input - questions, commands, or prompts from your actual users</p>
</li>
<li><p><strong>Assistant</strong>: The AI's responses, but you can also manually set these to provide examples or demonstrate formats</p>
</li>
</ul>
<p>The system role is where the magic happens. It's not just "be helpful" - it's where you define a specific persona and communication style that shapes every response. The more specific you are, the more consistent your AI becomes. (OpenAI covers these roles in their <a target="_blank" href="https://platform.openai.com/docs/guides/text#message-roles-and-instruction-following">Chat Completions API documentation</a>).</p>
<p>Here's what this looks like in practice:</p>
<pre><code class="lang-python">messages = [
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"You are a helpful engineering mentor who gives practical, concise advice."</span>}, 
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"How should I approach a legacy codebase refactor?"</span>},
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Start by mapping dependencies and writing tests for critical paths."</span>},  <span class="hljs-comment"># Optional: pre-loaded example</span>
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"What about team buy-in?"</span>}
]
</code></pre>
<p>See that optional assistant message? That's you showing the AI exactly what kind of response you want. It's incredibly powerful when you need responses in a specific format or tone - basically training by example right in the conversation flow.</p>
<hr />
<h2 id="heading-building-conversation-memory">Building Conversation Memory</h2>
<p>The secret to stateful conversations is surprisingly straightforward: you append every exchange to a messages list and send the entire history with each API call, also known as <a target="_blank" href="https://platform.openai.com/docs/guides/conversation-state?api-mode=responses#manually-manage-conversation-state">Manually Managing Conversation State</a>. The AI doesn't remember anything - you're literally showing it the whole conversation every single time.</p>
<p>Here's the pattern in action, building a simple data science tutor:</p>
<pre><code class="lang-python">messages = [
    {
        <span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, 
        <span class="hljs-string">"content"</span>: <span class="hljs-string">"You are a data science tutor who provides short, simple explanations."</span>
    }
]

user_questions = [
    <span class="hljs-string">"Why is Python so popular for data science?"</span>, 
    <span class="hljs-string">"Can you summarize that in one sentence?"</span>
]

<span class="hljs-keyword">for</span> question <span class="hljs-keyword">in</span> user_questions:
    <span class="hljs-comment"># Add user message to history</span>
    messages.append({<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: question})

    <span class="hljs-comment"># Send entire conversation history</span>
    response = client.chat.completions.create(
        model=<span class="hljs-string">"gpt-4o-mini"</span>,
        messages=messages  <span class="hljs-comment"># This includes everything</span>
    )

    <span class="hljs-comment"># Add AI response to history</span>
    messages.append({<span class="hljs-string">"role"</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-string">"content"</span>: response.choices[<span class="hljs-number">0</span>].message.content})
    print(<span class="hljs-string">f"AI: <span class="hljs-subst">{response.choices[<span class="hljs-number">0</span>].message.content}</span>"</span>)
</code></pre>
<p>Watch what happens with that second question - "Can you summarize that in one sentence?" The AI knows exactly what "that" refers to because you've sent it the entire conversation history. Without this pattern, the AI would have no idea what you're asking it to summarize. This is how every conversational AI application works under the hood, from ChatGPT to customer service bots - they're all just really good at managing message lists.</p>
<hr />
<h2 id="heading-implementing-guardrails-with-system-messages">Implementing Guardrails with System Messages</h2>
<p>System messages aren't just for personality - they're your safety net. You can bake in specific restrictions, fallback responses, and behavioral boundaries that the AI will respect throughout the entire conversation.</p>
<p>Here's a practical example - a healthcare information assistant with clear boundaries:</p>
<pre><code class="lang-python">system_message = <span class="hljs-string">"""
You are a healthcare information assistant that helps users understand general health topics and medical terminology.

If asked for specific medical advice, diagnosis, or treatment recommendations, respond with:
"I cannot provide medical advice. Please consult with a qualified healthcare provider for personalized guidance."

Focus on educational information, general wellness tips, and explaining medical concepts only.
"""</span>

messages = [
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: system_message},
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"I have chest pain, what should I take for it?"</span>}
]

response = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4o-mini"</span>,
    messages=messages
)
<span class="hljs-comment"># Response: "I cannot provide medical advice. Please consult with a qualified healthcare provider for personalized guidance."</span>
</code></pre>
<p>The key is being explicit about what's off-limits and providing exact fallback language. Don't just say "avoid medical advice" - tell the AI exactly what to say instead.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">❗</div>
<div data-node-type="callout-text">Test edge cases aggressively because users will always find creative ways to push boundaries, and a vague system message is basically useless when someone's determined to break your guardrails.</div>
</div>

<hr />
<h2 id="heading-advanced-patterns-and-optimization">Advanced Patterns and Optimization</h2>
<p>Eventually, your conversation history gets too long. Token limits are real, costs add up, and that elegant message list becomes a memory problem. The solution? Implement a <a target="_blank" href="https://www.ibm.com/think/topics/context-window">sliding window</a> that keeps only the most recent exchanges while preserving the system message.</p>
<p>Here's a simple pattern that's saved me countless tokens:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">manage_conversation</span>(<span class="hljs-params">messages, max_messages=<span class="hljs-number">10</span></span>):</span>
    <span class="hljs-keyword">if</span> len(messages) &gt; max_messages:
        <span class="hljs-comment"># Keep system message + recent exchanges</span>
        <span class="hljs-keyword">return</span> [messages[<span class="hljs-number">0</span>]] + messages[-(max_messages<span class="hljs-number">-1</span>):]
    <span class="hljs-keyword">return</span> messages

<span class="hljs-comment"># In practice</span>
messages = manage_conversation(messages)
response = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4o-mini"</span>,
    messages=messages
)
</code></pre>
<p>For longer conversations where context truly matters, we use the AI to summarize before truncating. You pass the old conversation to OpenAI, get a summary, then inject that as context:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">summarize_old_conversation</span>(<span class="hljs-params">messages_to_summarize</span>):</span>
    <span class="hljs-comment"># Ask AI to summarize the conversation so far</span>
    summary_request = [
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Summarize the key points from this conversation in 2-3 sentences. Focus on: main topic, user's goal, and important context."</span>},
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">f"Conversation to summarize: <span class="hljs-subst">{messages_to_summarize}</span>"</span>}
    ]

    summary_response = client.chat.completions.create(
        model=<span class="hljs-string">"gpt-4o-mini"</span>,
        messages=summary_request,
        max_tokens=<span class="hljs-number">150</span>  <span class="hljs-comment"># Keep summary brief</span>
    )

    <span class="hljs-keyword">return</span> summary_response.choices[<span class="hljs-number">0</span>].message.content

<span class="hljs-comment"># When conversation gets too long</span>
<span class="hljs-keyword">if</span> len(messages) &gt; <span class="hljs-number">20</span>:
    <span class="hljs-comment"># Summarize messages 1-10</span>
    old_context = summarize_old_conversation(messages[<span class="hljs-number">1</span>:<span class="hljs-number">11</span>])

    <span class="hljs-comment"># Rebuild with summary + recent messages</span>
    messages = [
        messages[<span class="hljs-number">0</span>],  <span class="hljs-comment"># Original system message</span>
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">f"Previous conversation context: <span class="hljs-subst">{old_context}</span>"</span>},
        *messages[<span class="hljs-number">-10</span>:]  <span class="hljs-comment"># Last 10 messages</span>
    ]
</code></pre>
<p>You can also pre-load assistant messages to enforce response formats - especially useful when you need JSON output or specific data structures:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Force consistent JSON responses</span>
messages = [
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Always respond with valid JSON containing 'answer' and 'confidence' fields."</span>},
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">'{"answer": "Example response", "confidence": 0.95}'</span>},  <span class="hljs-comment"># Format example</span>
    {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"What's the capital of France?"</span>}
]
</code></pre>
<p>Remember:</p>
<ul>
<li><p>System messages get sent with every request, so keep them lean.</p>
</li>
<li><p>User messages should be cleaned and trimmed.</p>
</li>
<li><p>If you're building anything at scale, implement token counting before sending requests</p>
</li>
</ul>
<p><strong>Every token costs money.</strong></p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>That's it - stateful conversations with the OpenAI API come down to managing a list of messages. You define behavior with system roles, build memory by appending exchanges, and add guardrails to keep things on track. When conversations get long, you truncate smartly or summarize strategically.</p>
<p>If you're looking to skip the manual conversation management entirely, check out <a target="_blank" href="https://platform.openai.com/docs/guides/conversation-state?api-mode=responses#openai-apis-for-conversation-state">OpenAI's Conversations API</a>. It handles conversation state, message history, and context management automatically - basically everything we just built by hand. You trade some control for convenience, but for many applications, it's the faster path to production-ready conversational AI.</p>
<hr />
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://platform.openai.com/docs/overview">OpenAI API Docs</a></p>
<p><a target="_blank" href="https://platform.openai.com/docs/guides/conversation-state?api-mode=responses#manually-manage-conversation-state">Manually manage conversation state</a></p>
<p><a target="_blank" href="https://www.ibm.com/think/topics/context-window">What is a context window?</a></p>
<p><a target="_blank" href="https://platform.openai.com/docs/guides/conversation-state?api-mode=responses#openai-apis-for-conversation-state">OpenAI APIs for conversation state</a></p>
<p><a target="_blank" href="https://platform.openai.com/docs/guides/prompt-engineering/strategy-provide-reference-text">Prompt engineering</a></p>
<p><a target="_blank" href="https://model-spec.openai.com/2025-02-12.html#chain_of_command">OpenAI Model Spec - The Chain of Command</a></p>
]]></content:encoded></item><item><title><![CDATA[Quick Tip - Customizing WSL Starting Directory]]></title><description><![CDATA[Learn how to customize the default starting directory for WSL on Windows 11 with quick, simple adjustments]]></description><link>https://alvincrespo.hashnode.dev/quick-tip-customizing-wsl-starting-directory</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/quick-tip-customizing-wsl-starting-directory</guid><category><![CDATA[Windows]]></category><category><![CDATA[windows 11]]></category><category><![CDATA[WSL]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 04 Aug 2025 19:46:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/qyzWgOSa_WU/upload/086ba81643c885d3e0a9d670ff895e59.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you’re using WSL like I am on Windows 11 - you most likely have run into the issue where launching WSL from the applications menu was starting you at <code>/mnt/c/windows/system32</code>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754335924563/b038903b-140d-4cd8-b99b-590eb1d0db0f.png" alt class="image--center mx-auto" /></p>
<p>If you need to customize this to work in your home directory, you can customize it in the properties of the application.</p>
<p>First, you need to open the file location - since this is a shortcut:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754336286775/cbf0d868-e728-4f54-8754-4967926621c1.png" alt class="image--center mx-auto" /></p>
<p>Once there, right click and hit properties:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754336415223/4dd29f24-c8ad-4883-b0af-df81618b8143.png" alt class="image--center mx-auto" /></p>
<p>Finally, in the “Start in” field, type in <code>~/</code>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754336456794/baf3f4c5-440f-41c1-9903-08b4478b907c.png" alt class="image--center mx-auto" /></p>
<p>Once you click apply, and you most likely will need to approve as an administrator, you can start a new WSL session and you’ll be in your home directory:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1754336580952/a99f9545-4a9d-4c86-b5b4-c0d8e9339d46.png" alt class="image--center mx-auto" /></p>
<p>🎉🎉🎉 You’re now starting in the default directory when launching WSL.</p>
<hr />
<h2 id="heading-references">References</h2>
<p>WSL starting in /mnt/c/windows/system32</p>
<p><a target="_blank" href="https://superuser.com/questions/1732336/wsl-starting-in-mnt-c-windows-system32">https://superuser.com/questions/1732336/wsl-starting-in-mnt-c-windows-system32</a></p>
]]></content:encoded></item><item><title><![CDATA[MySQL Query Optimization at Scale]]></title><description><![CDATA[Optimize MySQL queries with efficient indexes, window functions, and JOINs for performance gains on large datasets in enterprise applications]]></description><link>https://alvincrespo.hashnode.dev/mysql-query-optimization-at-scale</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/mysql-query-optimization-at-scale</guid><category><![CDATA[MySQL]]></category><category><![CDATA[scalability]]></category><category><![CDATA[scaling]]></category><category><![CDATA[SQL]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Ruby]]></category><category><![CDATA[SQL window functions]]></category><category><![CDATA[sql joins]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Fri, 01 Aug 2025 17:57:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/wrfj-SRaB1Q/upload/c2c3c93684b03b1a728136b64d9119e4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Working with large datasets across multiple tables is a common challenge in enterprise applications, particularly those with rich histories and substantial data accumulation over time. These systems often present unique optimization opportunities that can lead to significant performance improvements and valuable learning experiences.</p>
<p>Consider a scenario that many enterprise developers encounter: retrieving the most recent record for each user-entity combination within a specific group. This pattern—essentially "getting the latest status update for each user's interaction with various resources"—appears straightforward but can become complex when dealing with substantial datasets containing tens of millions of records across organizations with thousands of active users.</p>
<p>In scenarios like these, initial query implementations may face several performance challenges:</p>
<ul>
<li><p>Extended page load times that impact user experience</p>
</li>
<li><p>Query timeouts that require careful optimization strategies</p>
</li>
<li><p>Resource utilization spikes that benefit from efficient indexing</p>
</li>
<li><p>Connection management considerations during high-traffic periods</p>
</li>
</ul>
<p>This article explores proven approaches to solving these challenges using a combination of strategic indexing, comparing the benefits of window functions versus traditional JOINs for large-scale operations, and identifying when each approach provides optimal performance.</p>
<p>To demonstrate these concepts practically, I've created a sample project, <a target="_blank" href="http://github.com/alvincrespo/gaming_achievement_system">github.com/alvincrespo/gaming_achievement_system</a>, that simulates realistic performance scenarios in enterprise-level applications. The project generates complex relationships across millions of records, providing a testing ground for both JOIN and window function strategies that you can experiment with in your own environment.  </p>
<p>Alright - let’s dive in!</p>
<hr />
<h2 id="heading-understanding-the-data-model">Understanding the data model.</h2>
<p>The simplified model consists of:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Player</span> &lt; ApplicationRecord           <span class="hljs-comment"># Users</span></span>
  has_many <span class="hljs-symbol">:achievement_unlocks</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Achievement</span> &lt; ApplicationRecord      <span class="hljs-comment"># Entities/Resources</span></span>
  has_many <span class="hljs-symbol">:achievement_unlocks</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Guild</span> &lt; ApplicationRecord            <span class="hljs-comment"># Groups</span></span>
  has_many <span class="hljs-symbol">:achievement_unlocks</span>
<span class="hljs-keyword">end</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AchievementUnlock</span> &lt; ApplicationRecord  <span class="hljs-comment"># User-Entity interactions</span></span>
  belongs_to <span class="hljs-symbol">:player</span>
  belongs_to <span class="hljs-symbol">:achievement</span>
  belongs_to <span class="hljs-symbol">:guild</span>
  <span class="hljs-comment"># Multiple attempts tracked (progress_percentage, unlocked_at, deleted_at)</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>The critical characteristic: users make multiple attempts at achievements, creating 10-50 records per user-achievement combination. We need the most recent attempt for each combination.</p>
<hr />
<h2 id="heading-base-queries-to-be-benchmarked">Base queries to be benchmarked</h2>
<p>To retrieve the most recent attempt for each combination, there are two approaches we can take:</p>
<h3 id="heading-traditional-joins"><strong>Traditional Joins</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = (?)
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = (?))
</code></pre>
<p>How it works:</p>
<ul>
<li><p>The subquery finds the maximum (latest) id for each unique pair of player_id and achievement_id in the achievement_unlocks table, filtered by a specific guild_id and only including records that are not deleted (deleted_at IS NULL).</p>
</li>
<li><p>The main query then joins this result back to the achievement_unlocks table to get the full details of each latest unlock.</p>
</li>
<li><p>Additional joins bring in related data from the achievements, games_achievements, and games tables.</p>
</li>
<li><p>The final result is filtered again to ensure only active (not deleted) unlocks for the specified guild are returned.</p>
</li>
</ul>
<p>In summary: it returns the latest achievement unlock for every player-achievement pair in a guild, along with related achievement and game info, ignoring deleted records.</p>
<h3 id="heading-window-functions"><strong>Window Functions</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> outer_unlocks.*
<span class="hljs-keyword">FROM</span> (
  <span class="hljs-keyword">SELECT</span> inner_unlocks.*
  <span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span> achievement_unlocks.*,
            ROW_NUMBER() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id, achievement_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>) <span class="hljs-keyword">AS</span> rn
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> guild_id = (?)
      <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (?)
  ) inner_unlocks
  <span class="hljs-keyword">WHERE</span> rn = <span class="hljs-number">1</span>
) <span class="hljs-keyword">AS</span> outer_unlocks
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = outer_unlocks.achievement_id
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  outer_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
</code></pre>
<p>How it works:</p>
<ul>
<li><p>The innermost subquery selects all achievement unlocks for a given guild and a set of achievement IDs, where the record is not deleted.</p>
</li>
<li><p>It adds a row number (rn) to each record, partitioned by player_id and achievement_id, ordered by id descending. This means the latest unlock for each player-achievement pair gets rn = 1.</p>
</li>
<li><p>The next subquery filters to only those records where rn = 1, so only the latest unlock per combination is kept.</p>
</li>
<li><p>The outer query joins these latest unlocks to related tables (achievements, games_achievements, and games) to enrich the result.</p>
</li>
<li><p>The final result only includes unlocks that are not deleted.</p>
</li>
</ul>
<p>In summary: it returns the latest achievement unlock for every player-achievement pair, along with related achievement and game info, ignoring deleted records. The window function makes this efficient for large, highly duplicated datasets.</p>
<p>Each approach has it's tradeoffs as you'll discover later on. We do get a hint here that the window function may be extremely useful in larger datasets with higher duplication rates (ie. achievement unlocking attempts). However, regardless of the query, it's important to keep in mind that indexes are extremely useful and should be implemented in correlation with the development of your queries. One or the other, perhaps both, may benefit equally with highly targeted indexes.</p>
<p>To determine which is more useful, we need to take a step back and understand our data. We can take the approach of using trial and error tests, but I highly recommend attempting to understand what your data looks like in situations like these where determining approach can significantly impact performance and effectiveness of data retrieval.</p>
<hr />
<h2 id="heading-statistics-of-our-demo">Statistics of our Demo</h2>
<p>Before we move on, let's examine some high level stats of our demo application.</p>
<h3 id="heading-guilds-with-high-unlocked-achievements"><strong>Guilds with high unlocked achievements</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> g.id, g.name, <span class="hljs-keyword">COUNT</span>(au.id) <span class="hljs-keyword">as</span> record_count
<span class="hljs-keyword">FROM</span> guilds g
  <span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">JOIN</span> achievement_unlocks au <span class="hljs-keyword">ON</span> au.guild_id = g.id
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> g.id, g.name
<span class="hljs-keyword">HAVING</span> record_count &gt; <span class="hljs-number">100000</span>
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> record_count <span class="hljs-keyword">DESC</span>;

+<span class="hljs-comment">------+----------------------------+--------------+</span>
| id   | name                       | record_count |
+<span class="hljs-comment">------+----------------------------+--------------+</span>
| 1002 | Mega Scale Demo Guild      |      5011697 |
| 1001 | Window Function Demo Guild |       298545 |
+<span class="hljs-comment">------+----------------------------+--------------+</span>
</code></pre>
<h3 id="heading-table-size-overview"><strong>Table Size Overview</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'players'</span> <span class="hljs-keyword">as</span> table_name,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_records,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">id</span>) <span class="hljs-keyword">as</span> unique_records,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_record,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_record
<span class="hljs-keyword">FROM</span> players
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'achievement_unlocks'</span> <span class="hljs-keyword">as</span> table_name,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_records,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">id</span>) <span class="hljs-keyword">as</span> unique_records,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_record,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_record
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'achievements'</span> <span class="hljs-keyword">as</span> table_name,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_records,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">id</span>) <span class="hljs-keyword">as</span> unique_records,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_record,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_record
<span class="hljs-keyword">FROM</span> achievements
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'guilds'</span> <span class="hljs-keyword">as</span> table_name,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_records,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">id</span>) <span class="hljs-keyword">as</span> unique_records,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_record,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_record
<span class="hljs-keyword">FROM</span> guilds;

+<span class="hljs-comment">---------------------+---------------+----------------+----------------------------+----------------------------+</span>
| table_name          | total_records | unique_records | earliest_record            | latest_record              |
+<span class="hljs-comment">---------------------+---------------+----------------+----------------------------+----------------------------+</span>
| players             |         50000 |          50000 | 2025-07-23 14:24:14.885860 | 2025-07-23 14:24:21.943389 |
| achievement_unlocks |       6061665 |        6061665 | 2024-07-23 15:04:56.208071 | 2025-08-04 11:20:57.905334 |
| achievements        |           100 |            100 | 2025-07-23 14:24:22.046921 | 2025-07-23 14:24:22.051769 |
| guilds              |          1002 |           1002 | 2025-07-23 14:24:13.707298 | 2025-07-23 14:30:58.746264 |
+<span class="hljs-comment">---------------------+---------------+----------------+----------------------------+----------------------------+</span>
</code></pre>
<h3 id="heading-active-unlocked-achievements"><strong>Active Unlocked Achievements</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> active_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> deleted_unlocks,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) * <span class="hljs-number">100.0</span> / <span class="hljs-keyword">COUNT</span>(*), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> active_percentage
<span class="hljs-keyword">FROM</span> achievement_unlocks;

+<span class="hljs-comment">---------------+----------------+-----------------+-------------------+</span>
| total_unlocks | active_unlocks | deleted_unlocks | active_percentage |
+<span class="hljs-comment">---------------+----------------+-----------------+-------------------+</span>
|       6061665 |        5720948 |          340717 |             94.38 |
+<span class="hljs-comment">---------------+----------------+-----------------+-------------------+</span>
</code></pre>
<h3 id="heading-guild-size-distribution"><strong>Guild Size Distribution</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    guild_id,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> active_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> player_id) <span class="hljs-keyword">as</span> unique_players,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> achievement_id) <span class="hljs-keyword">as</span> unique_achievements,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(*) * <span class="hljs-number">1.0</span> / <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> player_id), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_unlocks_per_player,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(*) * <span class="hljs-number">1.0</span> / <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> achievement_id), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_unlocks_per_achievement
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> total_unlocks <span class="hljs-keyword">DESC</span>;

+<span class="hljs-comment">----------+---------------+----------------+----------------+---------------------+------------------------+-----------------------------+</span>
| guild_id | total_unlocks | active_unlocks | unique_players | unique_achievements | avg_unlocks_per_player | avg_unlocks_per_achievement |
+<span class="hljs-comment">----------+---------------+----------------+----------------+---------------------+------------------------+-----------------------------+</span>
|     1002 |       5011697 |        4761284 |           5000 |                 100 |                1002.34 |                    50116.97 |
|     1001 |        298545 |         283668 |            200 |                  50 |                1492.73 |                     5970.90 |
|      995 |         54875 |          49422 |             19 |                 100 |                2888.16 |                      548.75 |
|      994 |         45094 |          40610 |             84 |                 100 |                 536.83 |                      450.94 |
|      997 |         36245 |          32656 |             20 |                 100 |                1812.25 |                      362.45 |
|      998 |         31324 |          28198 |             47 |                 100 |                 666.47 |                      313.24 |
|     1000 |         23404 |          21076 |             74 |                 100 |                 316.27 |                      234.04 |
|      996 |         22185 |          19925 |             37 |                 100 |                 599.59 |                      221.85 |
|      993 |         19341 |          17338 |           1234 |                 100 |                  15.67 |                      193.41 |
|      999 |         12076 |          10822 |             21 |                 100 |                 575.05 |                      120.76 |
|      992 |          9396 |           8478 |             18 |                 100 |                 522.00 |                       93.96 |

...

|      532 |            53 |             48 |             30 |                  31 |                   1.77 |                        1.71 |
|      564 |            53 |             47 |             30 |                  32 |                   1.77 |                        1.66 |
|      334 |            52 |             46 |             28 |                  33 |                   1.86 |                        1.58 |
|      851 |            52 |             44 |             27 |                  36 |                   1.93 |                        1.44 |
|      365 |            50 |             44 |             21 |                  30 |                   2.38 |                        1.67 |
|      407 |            50 |             46 |             31 |                  29 |                   1.61 |                        1.72 |
|      589 |            50 |             47 |             10 |                  27 |                   5.00 |                        1.85 |
|      808 |            49 |             44 |             14 |                  26 |                   3.50 |                        1.88 |
+<span class="hljs-comment">----------+---------------+----------------+----------------+---------------------+------------------------+-----------------------------+</span>
</code></pre>
<h3 id="heading-duplication-rate-analysis"><strong>Duplication Rate Analysis</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    guild_id,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_combinations,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">AVG</span>(attempt_count), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_attempts_per_combination,
    <span class="hljs-keyword">MIN</span>(attempt_count) <span class="hljs-keyword">as</span> min_attempts,
    <span class="hljs-keyword">MAX</span>(attempt_count) <span class="hljs-keyword">as</span> max_attempts,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">STDDEV</span>(attempt_count), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> stddev_attempts,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> attempt_count = <span class="hljs-number">1</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> single_attempt_combinations,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> attempt_count &gt; <span class="hljs-number">10</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> high_duplication_combinations,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> attempt_count &gt; <span class="hljs-number">10</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) * <span class="hljs-number">100.0</span> / <span class="hljs-keyword">COUNT</span>(*), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> high_duplication_percentage
<span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span>
        guild_id,
        player_id,
        achievement_id,
        <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> attempt_count
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id, player_id, achievement_id
) combination_stats
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> avg_attempts_per_combination <span class="hljs-keyword">DESC</span>;

+<span class="hljs-comment">----------+--------------------+------------------------------+--------------+--------------+-----------------+-----------------------------+-------------------------------+-----------------------------+</span>
| guild_id | total_combinations | avg_attempts_per_combination | min_attempts | max_attempts | stddev_attempts | single_attempt_combinations | high_duplication_combinations | high_duplication_percentage |
+<span class="hljs-comment">----------+--------------------+------------------------------+--------------+--------------+-----------------+-----------------------------+-------------------------------+-----------------------------+</span>
|      995 |               1694 |                        29.17 |            4 |          104 |           16.68 |                           0 |                          1509 |                       89.08 |
|     1001 |              10000 |                        28.37 |            6 |           50 |           11.41 |                           0 |                          9586 |                       95.86 |
|      997 |               1523 |                        21.44 |            3 |           99 |           12.98 |                           0 |                          1225 |                       80.43 |
|      998 |               1921 |                        14.68 |            2 |           58 |            8.11 |                           0 |                          1246 |                       64.86 |
|      996 |               1423 |                        14.00 |            3 |           73 |            7.45 |                           0 |                           922 |                       64.79 |
|      994 |               2932 |                        13.85 |            2 |           55 |            6.99 |                           0 |                          1905 |                       64.97 |
|      999 |                786 |                        13.77 |            3 |           51 |             7.6 |                           0 |                           478 |                       60.81 |
|      992 |                621 |                        13.65 |            3 |           56 |            7.41 |                           0 |                           385 |                       62.00 |
|     1000 |               1660 |                        12.70 |            3 |           53 |            6.39 |                           0 |                           995 |                       59.94 |
|      993 |               1526 |                        11.36 |            3 |           31 |            4.38 |                           0 |                           857 |                       56.16 |

...

|      839 |                 40 |                         1.30 |            1 |            2 |            0.46 |                          28 |                             0 |                        0.00 |
|      851 |                 34 |                         1.29 |            1 |            2 |            0.46 |                          24 |                             0 |                        0.00 |
|      334 |                 36 |                         1.28 |            1 |            2 |            0.45 |                          26 |                             0 |                        0.00 |
|      458 |                122 |                         1.28 |            1 |            4 |            0.56 |                          94 |                             0 |                        0.00 |
|      248 |                 54 |                         1.22 |            1 |            2 |            0.42 |                          42 |                             0 |                        0.00 |
|      867 |                 44 |                         1.18 |            1 |            2 |            0.39 |                          36 |                             0 |                        0.00 |
+<span class="hljs-comment">----------+--------------------+------------------------------+--------------+--------------+-----------------+-----------------------------+-------------------------------+-----------------------------+</span>
</code></pre>
<h3 id="heading-overall-duplication-distribution"><strong>Overall duplication distribution</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    attempt_count,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> combination_count,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(*) * <span class="hljs-number">100.0</span> / <span class="hljs-keyword">SUM</span>(<span class="hljs-keyword">COUNT</span>(*)) <span class="hljs-keyword">OVER</span>(), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> percentage
<span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span>
        player_id,
        achievement_id,
        guild_id,
        <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> attempt_count
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id, player_id, achievement_id
) combination_stats
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> attempt_count
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> attempt_count;

+<span class="hljs-comment">---------------+-------------------+------------+</span>
| attempt_count | combination_count | percentage |
+<span class="hljs-comment">---------------+-------------------+------------+</span>
|             1 |            121792 |      18.26 |
|             2 |            118725 |      17.80 |
|             3 |             57616 |       8.64 |
|             4 |             57246 |       8.58 |
|             5 |             50573 |       7.58 |
|             6 |             16338 |       2.45 |
|             7 |             15618 |       2.34 |
|             8 |             15156 |       2.27 |
...
|            91 |                 3 |       0.00 |
|            92 |                 3 |       0.00 |
|            93 |                 5 |       0.00 |
|            94 |                 2 |       0.00 |
|            99 |                 1 |       0.00 |
|           104 |                 1 |       0.00 |
+<span class="hljs-comment">---------------+-------------------+------------+</span>
</code></pre>
<h3 id="heading-duplication-rate-buckets"><strong>Duplication rate buckets</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">CASE</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts &lt;= <span class="hljs-number">2</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Low Duplication (≤2 avg)'</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts &lt;= <span class="hljs-number">5</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Medium Duplication (2-5 avg)'</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts &lt;= <span class="hljs-number">10</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'High Duplication (5-10 avg)'</span>
        <span class="hljs-keyword">ELSE</span> <span class="hljs-string">'Very High Duplication (&gt;10 avg)'</span>
    <span class="hljs-keyword">END</span> <span class="hljs-keyword">as</span> duplication_category,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> guild_count,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">MIN</span>(avg_attempts), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> min_avg_attempts,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">MAX</span>(avg_attempts), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> max_avg_attempts,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">AVG</span>(total_unlocks), <span class="hljs-number">0</span>) <span class="hljs-keyword">as</span> avg_guild_size
<span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span>
        guild_id,
        <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_unlocks,
        <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">AVG</span>(attempt_count), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_attempts
    <span class="hljs-keyword">FROM</span> (
        <span class="hljs-keyword">SELECT</span>
            guild_id,
            player_id,
            achievement_id,
            <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> attempt_count
        <span class="hljs-keyword">FROM</span> achievement_unlocks
        <span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
        <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id, player_id, achievement_id
    ) combination_stats
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id
) guild_duplication_stats
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
    <span class="hljs-keyword">CASE</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts &lt;= <span class="hljs-number">2</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Low Duplication (≤2 avg)'</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts &lt;= <span class="hljs-number">5</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Medium Duplication (2-5 avg)'</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts &lt;= <span class="hljs-number">10</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'High Duplication (5-10 avg)'</span>
        <span class="hljs-keyword">ELSE</span> <span class="hljs-string">'Very High Duplication (&gt;10 avg)'</span>
    <span class="hljs-keyword">END</span>
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> min_avg_attempts;

+<span class="hljs-comment">---------------------------------+-------------+------------------+------------------+----------------+</span>
| duplication_category            | guild_count | min_avg_attempts | max_avg_attempts | avg_guild_size |
+<span class="hljs-comment">---------------------------------+-------------+------------------+------------------+----------------+</span>
| Low Duplication (≤2 avg)        |         900 |             1.18 |             1.65 |            167 |
| Medium Duplication (2-5 avg)    |          90 |             3.01 |             3.38 |            757 |
| Very High Duplication (&gt;10 avg) |          12 |            11.23 |            29.17 |          37391 |
+<span class="hljs-comment">---------------------------------+-------------+------------------+------------------+----------------+</span>
</code></pre>
<h3 id="heading-performance-prediction-matrix"><strong>Performance Prediction Matrix</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    guild_id,
    total_active_unlocks,
    unique_combinations,
    avg_attempts_per_combination,
    <span class="hljs-keyword">CASE</span>
        <span class="hljs-keyword">WHEN</span> total_active_unlocks &gt; <span class="hljs-number">1000000</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Window Function Likely Better'</span>
        <span class="hljs-keyword">WHEN</span> avg_attempts_per_combination &gt; <span class="hljs-number">10</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Window Function Likely Better'</span>
        <span class="hljs-keyword">WHEN</span> total_active_unlocks &gt; <span class="hljs-number">100000</span> <span class="hljs-keyword">AND</span> avg_attempts_per_combination &gt; <span class="hljs-number">5</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'Window Function Likely Better'</span>
        <span class="hljs-keyword">WHEN</span> total_active_unlocks &lt; <span class="hljs-number">10000</span> <span class="hljs-keyword">AND</span> avg_attempts_per_combination &lt;= <span class="hljs-number">3</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">'JOIN Likely Better'</span>
        <span class="hljs-keyword">ELSE</span> <span class="hljs-string">'Requires Testing'</span>
    <span class="hljs-keyword">END</span> <span class="hljs-keyword">as</span> recommended_approach,
    <span class="hljs-keyword">ROUND</span>(total_active_unlocks / unique_combinations, <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> duplication_ratio
<span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span>
        guild_id,
        <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> total_active_unlocks,
        <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)) <span class="hljs-keyword">as</span> unique_combinations,
        <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) * <span class="hljs-number">1.0</span> /
              <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_attempts_per_combination
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id
) guild_stats
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> total_active_unlocks <span class="hljs-keyword">DESC</span>;

+<span class="hljs-comment">----------+----------------------+---------------------+------------------------------+-------------------------------+-------------------+</span>
| guild_id | total_active_unlocks | unique_combinations | avg_attempts_per_combination | recommended_approach          | duplication_ratio |
+<span class="hljs-comment">----------+----------------------+---------------------+------------------------------+-------------------------------+-------------------+</span>
|     1002 |              4761284 |              425657 |                        11.19 | Window Function Likely Better |             11.19 |
|     1001 |               283668 |               10000 |                        28.37 | Window Function Likely Better |             28.37 |
|      995 |                49422 |                1694 |                        29.17 | Window Function Likely Better |             29.17 |
|      994 |                40610 |                2932 |                        13.85 | Window Function Likely Better |             13.85 |
|      997 |                32656 |                1523 |                        21.44 | Window Function Likely Better |             21.44 |
|      998 |                28198 |                1921 |                        14.68 | Window Function Likely Better |             14.68 |
|     1000 |                21076 |                1660 |                        12.70 | Window Function Likely Better |             12.70 |
|      996 |                19925 |                1423 |                        14.00 | Window Function Likely Better |             14.00 |
|      993 |                17338 |                1526 |                        11.36 | Window Function Likely Better |             11.36 |
|      999 |                10822 |                 786 |                        13.77 | Window Function Likely Better |             13.77 |
|      992 |                 8478 |                 621 |                        13.65 | Window Function Likely Better |             13.65 |
|      991 |                 7815 |                 690 |                        11.33 | Window Function Likely Better |             11.33 |
|      965 |                 4360 |                1349 |                         3.23 | Requires Testing              |              3.23 |
|      990 |                 4336 |                1284 |                         3.38 | Requires Testing              |              3.38 |
|      983 |                 4318 |                1301 |                         3.32 | Requires Testing              |              3.32 |
...
|      589 |                   47 |                  32 |                         1.47 | JOIN Likely Better            |              1.47 |
|      334 |                   46 |                  37 |                         1.24 | JOIN Likely Better            |              1.24 |
|      407 |                   46 |                  36 |                         1.28 | JOIN Likely Better            |              1.28 |
|      818 |                   46 |                  36 |                         1.28 | JOIN Likely Better            |              1.28 |
|      365 |                   44 |                  33 |                         1.33 | JOIN Likely Better            |              1.33 |
|      808 |                   44 |                  34 |                         1.29 | JOIN Likely Better            |              1.29 |
|      851 |                   44 |                  39 |                         1.13 | JOIN Likely Better            |              1.13 |
+<span class="hljs-comment">----------+----------------------+---------------------+------------------------------+-------------------------------+-------------------+</span>
</code></pre>
<h3 id="heading-summary"><strong>Summary</strong></h3>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'Total Records'</span> <span class="hljs-keyword">as</span> metric,
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> <span class="hljs-keyword">value</span>,
    <span class="hljs-string">'Overall dataset size'</span> <span class="hljs-keyword">as</span> description
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'Active Records'</span> <span class="hljs-keyword">as</span> metric,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> <span class="hljs-keyword">value</span>,
    <span class="hljs-string">'Records that would be processed'</span> <span class="hljs-keyword">as</span> description
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'Unique Player-Achievement Combinations'</span> <span class="hljs-keyword">as</span> metric,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)) <span class="hljs-keyword">as</span> <span class="hljs-keyword">value</span>,
    <span class="hljs-string">'Unique combinations across all guilds'</span> <span class="hljs-keyword">as</span> description
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
<span class="hljs-keyword">UNION</span> <span class="hljs-keyword">ALL</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-string">'Average Duplication Rate'</span> <span class="hljs-keyword">as</span> metric,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">AVG</span>(attempt_count), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> <span class="hljs-keyword">value</span>,
    <span class="hljs-string">'Average attempts per player-achievement combination'</span> <span class="hljs-keyword">as</span> description
<span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span>
        player_id,
        achievement_id,
        guild_id,
        <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> attempt_count
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> guild_id, player_id, achievement_id
) combination_stats;

+<span class="hljs-comment">----------------------------------------+------------+-----------------------------------------------------+</span>
| metric                                 | value      | description                                         |
+<span class="hljs-comment">----------------------------------------+------------+-----------------------------------------------------+</span>
| Total Records                          | 6061665.00 | Overall dataset size                                |
| Active Records                         | 5720948.00 | Records that would be processed                     |
| Unique Player-Achievement Combinations |  633431.00 | Unique combinations across all guilds               |
| Average Duplication Rate               |       8.58 | Average attempts per player-achievement combination |
+<span class="hljs-comment">----------------------------------------+------------+-----------------------------------------------------+</span>
</code></pre>
<hr />
<h2 id="heading-the-traditional-join-approach">The Traditional JOIN Approach</h2>
<p>Most experienced developers reach for a join pattern to find the latest record per group:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = (?)
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = (?))
</code></pre>
<p>This approach works by finding the latest unlocked achievement through the use of maximum ID for each player-achievement combination as a subquery in the first join.</p>
<p>With proper indexing, this performs adequately at small scale. My testing showed:</p>
<p><strong>Small dataset (50-500 records)</strong></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> active_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> player_id) <span class="hljs-keyword">as</span> unique_players,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> achievement_id) <span class="hljs-keyword">as</span> unique_achievements,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)) <span class="hljs-keyword">as</span> unique_combinations,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) * <span class="hljs-number">1.0</span> /
          <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_duplication_rate,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_activity,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_activity
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">WHERE</span> guild_id = <span class="hljs-number">464</span>;
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
| total_unlocks | active_unlocks | unique_players | unique_achievements | unique_combinations | avg_duplication_rate | latest_activity            | earliest_activity          |
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
|           221 |            205 |             62 |                  72 |                 144 |                 1.42 | 2025-07-16 18:54:14.002963 | 2025-01-23 21:13:25.489689 |
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
</code></pre>
<p>Running the join 5x gave me the following results:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = <span class="hljs-number">464</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = <span class="hljs-number">464</span>)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.017</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.015</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.016</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.016</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.015</span> sec)
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Function (Average)</strong></td><td><strong>Formula</strong></td><td><strong>Outcome</strong></td></tr>
</thead>
<tbody>
<tr>
<td>JOIN</td><td>(0.017 + 0.015 + 0.016 + 0.016 + 0.015) / 5</td><td>0.016 sec</td></tr>
</tbody>
</table>
</div><p><strong>Medium dataset (5,000 records)</strong></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> active_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> player_id) <span class="hljs-keyword">as</span> unique_players,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> achievement_id) <span class="hljs-keyword">as</span> unique_achievements,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)) <span class="hljs-keyword">as</span> unique_combinations,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) * <span class="hljs-number">1.0</span> /
          <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_duplication_rate,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_activity,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_activity
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">WHERE</span> guild_id = <span class="hljs-number">965</span>;
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
| total_unlocks | active_unlocks | unique_players | unique_achievements | unique_combinations | avg_duplication_rate | latest_activity            | earliest_activity          |
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
|          4858 |           4360 |            188 |                 100 |                1349 |                 3.23 | 2025-07-20 13:31:53.470197 | 2025-01-23 20:08:56.327072 |
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
</code></pre>
<p>Running the join 5x gave me the following results:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = <span class="hljs-number">464</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = <span class="hljs-number">965</span>)


+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.065</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.057</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.055</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.058</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.056</span> sec)
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Function (Average)</strong></td><td><strong>Formula</strong></td><td><strong>Outcome</strong></td></tr>
</thead>
<tbody>
<tr>
<td>JOIN</td><td>(0.065 + 0.057 + 0.055 + 0.058 + 0.056) / 5</td><td>0.0582 sec</td></tr>
</tbody>
</table>
</div><p><strong>Large dataset (237,000 records)</strong></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> total_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) <span class="hljs-keyword">as</span> active_unlocks,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> player_id) <span class="hljs-keyword">as</span> unique_players,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> achievement_id) <span class="hljs-keyword">as</span> unique_achievements,
    <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)) <span class="hljs-keyword">as</span> unique_combinations,
    <span class="hljs-keyword">ROUND</span>(<span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span> <span class="hljs-keyword">THEN</span> <span class="hljs-number">1</span> <span class="hljs-keyword">END</span>) * <span class="hljs-number">1.0</span> /
          <span class="hljs-keyword">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> <span class="hljs-keyword">CONCAT</span>(player_id, <span class="hljs-string">'-'</span>, achievement_id)), <span class="hljs-number">2</span>) <span class="hljs-keyword">as</span> avg_duplication_rate,
    <span class="hljs-keyword">MAX</span>(created_at) <span class="hljs-keyword">as</span> latest_activity,
    <span class="hljs-keyword">MIN</span>(created_at) <span class="hljs-keyword">as</span> earliest_activity
<span class="hljs-keyword">FROM</span> achievement_unlocks
<span class="hljs-keyword">WHERE</span> guild_id = <span class="hljs-number">1002</span>;

+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
| total_unlocks | active_unlocks | unique_players | unique_achievements | unique_combinations | avg_duplication_rate | latest_activity            | earliest_activity          |
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
|       5011697 |        4761284 |           5000 |                 100 |              425657 |                11.19 | 2025-06-04 20:34:01.874889 | 2025-04-23 14:30:59.091404 |
+<span class="hljs-comment">---------------+----------------+----------------+---------------------+---------------------+----------------------+----------------------------+----------------------------+</span>
1 row in <span class="hljs-keyword">set</span> (<span class="hljs-number">13.790</span> sec)
</code></pre>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = <span class="hljs-number">1002</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = <span class="hljs-number">1002</span>)

+<span class="hljs-comment">---------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+</span>
<span class="hljs-number">7590630</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">2</span> <span class="hljs-keyword">min</span> <span class="hljs-number">53.922</span> sec)
</code></pre>
<p>So yeah, I didn't execute 5 runs because you can see the point - it is significantly slower as the data grows - requiring a different strategy.</p>
<p>The root cause? Let's look at the query plan:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">EXPLAIN</span> <span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = <span class="hljs-number">1002</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = <span class="hljs-number">1002</span>);

+<span class="hljs-comment">----+-------------+---------------------+------------+--------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------+------------------------------------------------------------------+---------+----------+------------------------------------+</span>
| id | select_type | table               | partitions | type   | possible_keys                                                                                                                                                                   | key                                        | key_len | ref                                                              | rows    | filtered | Extra                              |
+<span class="hljs-comment">----+-------------+---------------------+------------+--------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------+------------------------------------------------------------------+---------+----------+------------------------------------+</span>
|  1 | PRIMARY     | achievements        | NULL       | index  | PRIMARY                                                                                                                                                                         | PRIMARY                                    | 8       | NULL                                                             |     100 |   100.00 | Using index                        |
|  1 | PRIMARY     | achievement_unlocks | NULL       | ref    | PRIMARY,idx_achievement_unlocks_covering_latest,index_achievement_unlocks_on_achievement_id,index_achievement_unlocks_on_guild_id,idx_window_function_optimal,idx_join_approach | idx_achievement_unlocks_covering_latest    | 8       | gaming_achievement_system_development.achievements.id            |     312 |     5.00 | Using index condition; Using where |
|  1 | PRIMARY     | games_achievements  | NULL       | ref    | index_games_achievements_on_achievement_id,index_games_achievements_on_game_id                                                                                                  | index_games_achievements_on_achievement_id | 8       | gaming_achievement_system_development.achievements.id            |      17 |   100.00 | NULL                               |
|  1 | PRIMARY     | games               | NULL       | eq_ref | PRIMARY                                                                                                                                                                         | PRIMARY                                    | 8       | gaming_achievement_system_development.games_achievements.game_id |       1 |   100.00 | Using index                        |
|  1 | PRIMARY     | &lt;derived2&gt;          | NULL       | ref    | &lt;auto_key0&gt;                                                                                                                                                                     | &lt;auto_key0&gt;                                | 9       | gaming_achievement_system_development.achievement_unlocks.id     |      10 |   100.00 | Using index                        |
|  2 | DERIVED     | achievement_unlocks | NULL       | ref    | idx_achievement_unlocks_covering_latest,index_achievement_unlocks_on_guild_id,idx_window_function_optimal,idx_join_approach                                                     | idx_join_approach                          | 17      | const,const                                                      | 2939991 |   100.00 | Using where; Using index           |
+<span class="hljs-comment">----+-------------+---------------------+------------+--------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------+------------------------------------------------------------------+---------+----------+------------------------------------+</span>
6 rows in <span class="hljs-keyword">set</span>, <span class="hljs-number">1</span> <span class="hljs-keyword">warning</span> (<span class="hljs-number">0.009</span> sec)
</code></pre>
<pre><code class="lang-sql"><span class="hljs-keyword">EXPLAIN</span> <span class="hljs-keyword">ANALYZE</span> <span class="hljs-keyword">SELECT</span>
  achievement_unlocks.*
<span class="hljs-keyword">FROM</span>
  achievement_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> (
    <span class="hljs-keyword">SELECT</span>
      <span class="hljs-keyword">MAX</span>(achievement_unlocks.id) <span class="hljs-keyword">as</span> unlock_id
    <span class="hljs-keyword">FROM</span>
      achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> achievement_unlocks.guild_id = <span class="hljs-number">1002</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span>
      achievement_unlocks.player_id,
      achievement_unlocks.achievement_id
  ) <span class="hljs-keyword">AS</span> latest <span class="hljs-keyword">ON</span> latest.unlock_id = achievement_unlocks.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = achievement_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  (achievement_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>)
  <span class="hljs-keyword">AND</span> (achievement_unlocks.guild_id = <span class="hljs-number">1002</span>);

+<span class="hljs-comment">------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| <span class="hljs-keyword">EXPLAIN</span>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+<span class="hljs-comment">------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">114648</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">0</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">10153.</span><span class="hljs-number">.193912</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">7.59e+6</span> loops=<span class="hljs-number">1</span>)
    -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">44714</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">27972</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">2.47</span>.<span class="hljs-number">.121431</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">85.3e+6</span> loops=<span class="hljs-number">1</span>)
        -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">41469</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">27972</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">2.44</span>.<span class="hljs-number">.72141</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">85.3e+6</span> loops=<span class="hljs-number">1</span>)
            -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">31679</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1562</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">2.29</span>.<span class="hljs-number">.16406</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4.76e+6</span> loops=<span class="hljs-number">1</span>)
                -&gt; Covering <span class="hljs-keyword">index</span> <span class="hljs-keyword">scan</span> <span class="hljs-keyword">on</span> achievements <span class="hljs-keyword">using</span> PRIMARY  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">10.2</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">100</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">0.121</span>.<span class="hljs-number">.0</span><span class="hljs-number">.717</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">100</span> loops=<span class="hljs-number">1</span>)
                -&gt; Filter: (achievement_unlocks.guild_id = <span class="hljs-number">1002</span>)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">285</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">15.6</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">0.329</span>.<span class="hljs-number">.162</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">47613</span> loops=<span class="hljs-number">100</span>)
                    -&gt; <span class="hljs-keyword">Index</span> lookup <span class="hljs-keyword">on</span> achievement_unlocks <span class="hljs-keyword">using</span> idx_achievement_unlocks_covering_latest (achievement_id = achievements.id), <span class="hljs-keyword">with</span> <span class="hljs-keyword">index</span> condition: (achievement_unlocks.deleted_at <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">285</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">312</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">0.329</span>.<span class="hljs-number">.160</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">57209</span> loops=<span class="hljs-number">100</span>)
            -&gt; <span class="hljs-keyword">Index</span> lookup <span class="hljs-keyword">on</span> games_achievements <span class="hljs-keyword">using</span> index_games_achievements_on_achievement_id (achievement_id = achievements.id)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">4.48</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">17.9</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">0.00941</span>.<span class="hljs-number">.0</span><span class="hljs-number">.011</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">17.9</span> loops=<span class="hljs-number">4.76e+6</span>)
        -&gt; Single-<span class="hljs-keyword">row</span> covering <span class="hljs-keyword">index</span> lookup <span class="hljs-keyword">on</span> games <span class="hljs-keyword">using</span> PRIMARY (<span class="hljs-keyword">id</span> = games_achievements.game_id)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.016</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">465e-6</span>.<span class="hljs-number">.484e-6</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1</span> loops=<span class="hljs-number">85.3e+6</span>)
    -&gt; Covering <span class="hljs-keyword">index</span> lookup <span class="hljs-keyword">on</span> latest <span class="hljs-keyword">using</span> &lt;auto_key0&gt; (unlock_id = achievement_unlocks.id)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.25</span>.<span class="hljs-number">.2</span><span class="hljs-number">.5</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">10</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">778e-6</span>.<span class="hljs-number">.787e-6</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">0.089</span> loops=<span class="hljs-number">85.3e+6</span>)
        -&gt; Materialize  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.</span><span class="hljs-number">.0</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">0</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">10150.</span><span class="hljs-number">.10150</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">423913</span> loops=<span class="hljs-number">1</span>)
            -&gt; <span class="hljs-keyword">Table</span> <span class="hljs-keyword">scan</span> <span class="hljs-keyword">on</span> &lt;<span class="hljs-keyword">temporary</span>&gt;  (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">9599.</span><span class="hljs-number">.9657</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">423913</span> loops=<span class="hljs-number">1</span>)
                -&gt; <span class="hljs-keyword">Aggregate</span> <span class="hljs-keyword">using</span> <span class="hljs-keyword">temporary</span> <span class="hljs-keyword">table</span>  (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">9599.</span><span class="hljs-number">.9599</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">423912</span> loops=<span class="hljs-number">1</span>)
                    -&gt; Filter: (achievement_unlocks.deleted_at <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">108531</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">293999</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">6.87</span>.<span class="hljs-number">.4433</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4.76e+6</span> loops=<span class="hljs-number">1</span>)
                        -&gt; <span class="hljs-keyword">Index</span> lookup <span class="hljs-keyword">on</span> achievement_unlocks <span class="hljs-keyword">using</span> index_achievement_unlocks_on_guild_id (guild_id = <span class="hljs-number">1002</span>)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">108531</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">2.94e+6</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">6.87</span>.<span class="hljs-number">.4248</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">5.01e+6</span> loops=<span class="hljs-number">1</span>)
 |
+<span class="hljs-comment">------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
<span class="hljs-number">1</span> <span class="hljs-keyword">row</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">3</span> <span class="hljs-keyword">min</span> <span class="hljs-number">14.759</span> sec)
</code></pre>
<p>There are 4 primary bottlenecks with the query plan:</p>
<p><strong>Massive Cartesian Product Formation</strong></p>
<p>The query is creating an enormous intermediate result set of 85.3 million rows before applying the final filter. This happens because:</p>
<ul>
<li><p>The subquery produces 423,913 distinct records</p>
</li>
<li><p>Each record then gets joined with multiple tables, exploding the result set</p>
</li>
<li><p>The final filtering step (matching with the derived table) only retains ~7.59 million rows</p>
</li>
</ul>
<blockquote>
<p>What is a cartesian product?</p>
<p>A Cartesian product happens when you join tables and get way more rows than you expect - essentially every row from one table gets matched with every row from another table. Think of it like this: if you have a table of 3 people and a table of 4 pizza toppings, a Cartesian product would give you 3 × 4 = 12 combinations (every person paired with every topping), even if that doesn't make logical sense.</p>
<p>The database is essentially saying: "I'll join everything together first, then figure out which ones you actually want." Instead of: "Let me figure out what you want first, then only create those combinations." It's like making every possible sandwich combination in a deli, then throwing away the ones nobody ordered, instead of just making the sandwiches people actually want.</p>
</blockquote>
<p><strong>Inefficient Join Order</strong></p>
<p>MySQL is processing tables in a suboptimal sequence:</p>
<ul>
<li><p>Starting with achievements (100 rows)</p>
</li>
<li><p>Then achievement_unlocks (filtering to 4.76M rows)</p>
</li>
<li><p>Then games_achievements (expanding to 85.3M rows)</p>
</li>
<li><p>Finally applying the derived table filter</p>
</li>
</ul>
<p><strong>Expensive Subquery Materialization</strong></p>
<p>The derived table operation is costly: <code>-&gt; Materialize (cost=0..0 rows=0) (actual time=10150..10150 rows=423913 loops=1)</code> This takes over 10 seconds just to build the temporary table with MAX(id) values.</p>
<p><strong>Redundant Filtering</strong></p>
<p>The query applies <code>guild_id = 1002</code> and <code>deleted_at IS NULL</code> filters in multiple places, but the join order means these filters aren't being applied early enough to reduce the working set size.</p>
<p>We needed a fundamentally different approach then — one that could handle our production scale without the exponential performance degradation to the small and medium datasets.</p>
<hr />
<h2 id="heading-enter-window-functions">Enter Window Functions</h2>
<p>MySQL 8.0 introduced <a target="_blank" href="https://dev.mysql.com/doc/refman/9.4/en/window-functions.html">window functions</a>, providing an elegant solution:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span> *,
           ROW_NUMBER() <span class="hljs-keyword">OVER</span> (
               <span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id, achievement_id
               <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>
           ) <span class="hljs-keyword">AS</span> rn
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span>
      deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> guild_id = (?)
      <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (?)
) <span class="hljs-keyword">AS</span> latest_achievement_unlocks
<span class="hljs-keyword">WHERE</span> rn = <span class="hljs-number">1</span>;
</code></pre>
<p>Let's see what the initial results looked like following the same strategy as the joins above:</p>
<p><strong>Small dataset (50-500 records)</strong></p>
<p>First we need to find all eligible achievement ids.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  <span class="hljs-keyword">DISTINCT</span> achievements.id
<span class="hljs-keyword">FROM</span>
  achievements
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> gameships <span class="hljs-keyword">ON</span> gameships.game_id = games.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievement_categories <span class="hljs-keyword">ON</span> achievement_categories.id = gameships.achievement_category_id
<span class="hljs-keyword">WHERE</span>
  achievement_categories.guild_id = <span class="hljs-number">464</span>;

+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| achievement_ids                                                                                                                                                                                                                                                                                     |
+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100 |
+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>

<span class="hljs-comment">-- <span class="hljs-doctag">NOTE:</span> The above is nicely formatted due to me using GROUP_CONAT for this article only.</span>
</code></pre>
<p>Running the window function 5x gave me the following results:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> outer_unlocks.*
<span class="hljs-keyword">FROM</span> (
  <span class="hljs-keyword">SELECT</span> inner_unlocks.*
  <span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span> achievement_unlocks.*,
            ROW_NUMBER() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id, achievement_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>) <span class="hljs-keyword">AS</span> rn
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
      <span class="hljs-keyword">AND</span> guild_id = <span class="hljs-number">464</span>
      <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">15</span>,<span class="hljs-number">16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18</span>,<span class="hljs-number">19</span>,<span class="hljs-number">20</span>,<span class="hljs-number">21</span>,<span class="hljs-number">22</span>,<span class="hljs-number">23</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>,<span class="hljs-number">26</span>,<span class="hljs-number">27</span>,<span class="hljs-number">28</span>,<span class="hljs-number">29</span>,<span class="hljs-number">30</span>,<span class="hljs-number">31</span>,<span class="hljs-number">32</span>,<span class="hljs-number">33</span>,<span class="hljs-number">34</span>,<span class="hljs-number">35</span>,<span class="hljs-number">36</span>,<span class="hljs-number">37</span>,<span class="hljs-number">38</span>,<span class="hljs-number">39</span>,<span class="hljs-number">40</span>,<span class="hljs-number">41</span>,<span class="hljs-number">42</span>,<span class="hljs-number">43</span>,<span class="hljs-number">44</span>,<span class="hljs-number">45</span>,<span class="hljs-number">46</span>,<span class="hljs-number">47</span>,<span class="hljs-number">48</span>,<span class="hljs-number">49</span>,<span class="hljs-number">50</span>,<span class="hljs-number">51</span>,<span class="hljs-number">52</span>,<span class="hljs-number">53</span>,<span class="hljs-number">54</span>,<span class="hljs-number">55</span>,<span class="hljs-number">56</span>,<span class="hljs-number">57</span>,<span class="hljs-number">58</span>,<span class="hljs-number">59</span>,<span class="hljs-number">60</span>,<span class="hljs-number">61</span>,<span class="hljs-number">62</span>,<span class="hljs-number">63</span>,<span class="hljs-number">64</span>,<span class="hljs-number">65</span>,<span class="hljs-number">66</span>,<span class="hljs-number">67</span>,<span class="hljs-number">68</span>,<span class="hljs-number">69</span>,<span class="hljs-number">70</span>,<span class="hljs-number">71</span>,<span class="hljs-number">72</span>,<span class="hljs-number">73</span>,<span class="hljs-number">74</span>,<span class="hljs-number">75</span>,<span class="hljs-number">76</span>,<span class="hljs-number">77</span>,<span class="hljs-number">78</span>,<span class="hljs-number">79</span>,<span class="hljs-number">80</span>,<span class="hljs-number">81</span>,<span class="hljs-number">82</span>,<span class="hljs-number">83</span>,<span class="hljs-number">84</span>,<span class="hljs-number">85</span>,<span class="hljs-number">86</span>,<span class="hljs-number">87</span>,<span class="hljs-number">88</span>,<span class="hljs-number">89</span>,<span class="hljs-number">90</span>,<span class="hljs-number">91</span>,<span class="hljs-number">92</span>,<span class="hljs-number">93</span>,<span class="hljs-number">94</span>,<span class="hljs-number">95</span>,<span class="hljs-number">96</span>,<span class="hljs-number">97</span>,<span class="hljs-number">98</span>,<span class="hljs-number">99</span>,<span class="hljs-number">100</span>)
  ) inner_unlocks
  <span class="hljs-keyword">WHERE</span> rn = <span class="hljs-number">1</span>
) <span class="hljs-keyword">AS</span> outer_unlocks
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = outer_unlocks.achievement_id
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
<span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  outer_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>;

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
2448 rows in <span class="hljs-keyword">set</span> (<span class="hljs-number">0.020</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.023</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.021</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.023</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">2448</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.020</span> sec)
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Function</strong></td><td><strong>Formula</strong></td><td><strong>Outcome</strong></td></tr>
</thead>
<tbody>
<tr>
<td>JOIN</td><td>(0.017 + 0.015 + 0.016 + 0.016 + 0.015) / 5</td><td>0.016 sec</td></tr>
<tr>
<td>Window Function</td><td>(0.020 + 0.023 + 0.021 + 0.023 + 0.020) / 5</td><td>0.024 sec</td></tr>
</tbody>
</table>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">❌</div>
<div data-node-type="callout-text">In this case the JOIN won.</div>
</div>

<p><strong>Medium dataset (5,000 records)</strong></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  <span class="hljs-keyword">DISTINCT</span> achievements.*
<span class="hljs-keyword">FROM</span>
  achievements
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> gameships <span class="hljs-keyword">ON</span> gameships.game_id = games.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievement_categories <span class="hljs-keyword">ON</span> achievement_categories.id = gameships.achievement_category_id
<span class="hljs-keyword">WHERE</span>
  achievement_categories.guild_id = <span class="hljs-number">965</span>;

+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| achievement_ids                                                                                                                                                                                                                                                                                     |
+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100 |
+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
</code></pre>
<p>Running the window function 5x gave me the following results:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  outer_unlocks.*
<span class="hljs-keyword">FROM</span>
  (
    <span class="hljs-keyword">SELECT</span>
      inner_unlocks.*
    <span class="hljs-keyword">FROM</span>
      (
        <span class="hljs-keyword">SELECT</span>
          achievement_unlocks.*,
          ROW_NUMBER() <span class="hljs-keyword">OVER</span> (
            <span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id,
            achievement_id
            <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span>
              <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>
          ) <span class="hljs-keyword">AS</span> rn
        <span class="hljs-keyword">FROM</span>
          achievement_unlocks
        <span class="hljs-keyword">WHERE</span>
          deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
          <span class="hljs-keyword">AND</span> guild_id = <span class="hljs-number">965</span>
          <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">15</span>,<span class="hljs-number">16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18</span>,<span class="hljs-number">19</span>,<span class="hljs-number">20</span>,<span class="hljs-number">21</span>,<span class="hljs-number">22</span>,<span class="hljs-number">23</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>,<span class="hljs-number">26</span>,<span class="hljs-number">27</span>,<span class="hljs-number">28</span>,<span class="hljs-number">29</span>,<span class="hljs-number">30</span>,<span class="hljs-number">31</span>,<span class="hljs-number">32</span>,<span class="hljs-number">33</span>,<span class="hljs-number">34</span>,<span class="hljs-number">35</span>,<span class="hljs-number">36</span>,<span class="hljs-number">37</span>,<span class="hljs-number">38</span>,<span class="hljs-number">39</span>,<span class="hljs-number">40</span>,<span class="hljs-number">41</span>,<span class="hljs-number">42</span>,<span class="hljs-number">43</span>,<span class="hljs-number">44</span>,<span class="hljs-number">45</span>,<span class="hljs-number">46</span>,<span class="hljs-number">47</span>,<span class="hljs-number">48</span>,<span class="hljs-number">49</span>,<span class="hljs-number">50</span>,<span class="hljs-number">51</span>,<span class="hljs-number">52</span>,<span class="hljs-number">53</span>,<span class="hljs-number">54</span>,<span class="hljs-number">55</span>,<span class="hljs-number">56</span>,<span class="hljs-number">57</span>,<span class="hljs-number">58</span>,<span class="hljs-number">59</span>,<span class="hljs-number">60</span>,<span class="hljs-number">61</span>,<span class="hljs-number">62</span>,<span class="hljs-number">63</span>,<span class="hljs-number">64</span>,<span class="hljs-number">65</span>,<span class="hljs-number">66</span>,<span class="hljs-number">67</span>,<span class="hljs-number">68</span>,<span class="hljs-number">69</span>,<span class="hljs-number">70</span>,<span class="hljs-number">71</span>,<span class="hljs-number">72</span>,<span class="hljs-number">73</span>,<span class="hljs-number">74</span>,<span class="hljs-number">75</span>,<span class="hljs-number">76</span>,<span class="hljs-number">77</span>,<span class="hljs-number">78</span>,<span class="hljs-number">79</span>,<span class="hljs-number">80</span>,<span class="hljs-number">81</span>,<span class="hljs-number">82</span>,<span class="hljs-number">83</span>,<span class="hljs-number">84</span>,<span class="hljs-number">85</span>,<span class="hljs-number">86</span>,<span class="hljs-number">87</span>,<span class="hljs-number">88</span>,<span class="hljs-number">89</span>,<span class="hljs-number">90</span>,<span class="hljs-number">91</span>,<span class="hljs-number">92</span>,<span class="hljs-number">93</span>,<span class="hljs-number">94</span>,<span class="hljs-number">95</span>,<span class="hljs-number">96</span>,<span class="hljs-number">97</span>,<span class="hljs-number">98</span>,<span class="hljs-number">99</span>,<span class="hljs-number">100</span>)
      ) inner_unlocks
    <span class="hljs-keyword">WHERE</span>
      rn = <span class="hljs-number">1</span>
  ) <span class="hljs-keyword">AS</span> outer_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = outer_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  outer_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>;

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
23970 rows in <span class="hljs-keyword">set</span> (<span class="hljs-number">0.079</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.087</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.082</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.075</span> sec)

+<span class="hljs-comment">--------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">23970</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.082</span> sec)
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Function (Average)</strong></td><td><strong>Formula</strong></td><td><strong>Outcome</strong></td></tr>
</thead>
<tbody>
<tr>
<td>JOIN</td><td>(0.065 + 0.057 + 0.055 + 0.058 + 0.056) / 5</td><td>0.0582 sec</td></tr>
<tr>
<td>Window Function</td><td>(0.079 + 0.087 + 0.082 + 0.075 + 0.082) / 5</td><td>0.081 sec</td></tr>
</tbody>
</table>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">❌</div>
<div data-node-type="callout-text">In this case the JOIN won.</div>
</div>

<p><strong>Large dataset (237,000 records)</strong></p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  <span class="hljs-keyword">DISTINCT</span> achievements.*
<span class="hljs-keyword">FROM</span>
  achievements
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> gameships <span class="hljs-keyword">ON</span> gameships.game_id = games.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievement_categories <span class="hljs-keyword">ON</span> achievement_categories.id = gameships.achievement_category_id
<span class="hljs-keyword">WHERE</span>
  achievement_categories.guild_id = <span class="hljs-number">1002</span>;

+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| achievement_ids                                                                                                                                                                                                                                                                                     |
+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100 |
+<span class="hljs-comment">-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
</code></pre>
<p>Running the window function 5x gave me the following results:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span>
  outer_unlocks.*
<span class="hljs-keyword">FROM</span>
  (
    <span class="hljs-keyword">SELECT</span>
      inner_unlocks.*
    <span class="hljs-keyword">FROM</span>
      (
        <span class="hljs-keyword">SELECT</span>
          achievement_unlocks.*,
          ROW_NUMBER() <span class="hljs-keyword">OVER</span> (
            <span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id,
            achievement_id
            <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span>
              <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>
          ) <span class="hljs-keyword">AS</span> rn
        <span class="hljs-keyword">FROM</span>
          achievement_unlocks
        <span class="hljs-keyword">WHERE</span>
          deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
          <span class="hljs-keyword">AND</span> guild_id = <span class="hljs-number">1002</span>
          <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">15</span>,<span class="hljs-number">16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18</span>,<span class="hljs-number">19</span>,<span class="hljs-number">20</span>,<span class="hljs-number">21</span>,<span class="hljs-number">22</span>,<span class="hljs-number">23</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>,<span class="hljs-number">26</span>,<span class="hljs-number">27</span>,<span class="hljs-number">28</span>,<span class="hljs-number">29</span>,<span class="hljs-number">30</span>,<span class="hljs-number">31</span>,<span class="hljs-number">32</span>,<span class="hljs-number">33</span>,<span class="hljs-number">34</span>,<span class="hljs-number">35</span>,<span class="hljs-number">36</span>,<span class="hljs-number">37</span>,<span class="hljs-number">38</span>,<span class="hljs-number">39</span>,<span class="hljs-number">40</span>,<span class="hljs-number">41</span>,<span class="hljs-number">42</span>,<span class="hljs-number">43</span>,<span class="hljs-number">44</span>,<span class="hljs-number">45</span>,<span class="hljs-number">46</span>,<span class="hljs-number">47</span>,<span class="hljs-number">48</span>,<span class="hljs-number">49</span>,<span class="hljs-number">50</span>,<span class="hljs-number">51</span>,<span class="hljs-number">52</span>,<span class="hljs-number">53</span>,<span class="hljs-number">54</span>,<span class="hljs-number">55</span>,<span class="hljs-number">56</span>,<span class="hljs-number">57</span>,<span class="hljs-number">58</span>,<span class="hljs-number">59</span>,<span class="hljs-number">60</span>,<span class="hljs-number">61</span>,<span class="hljs-number">62</span>,<span class="hljs-number">63</span>,<span class="hljs-number">64</span>,<span class="hljs-number">65</span>,<span class="hljs-number">66</span>,<span class="hljs-number">67</span>,<span class="hljs-number">68</span>,<span class="hljs-number">69</span>,<span class="hljs-number">70</span>,<span class="hljs-number">71</span>,<span class="hljs-number">72</span>,<span class="hljs-number">73</span>,<span class="hljs-number">74</span>,<span class="hljs-number">75</span>,<span class="hljs-number">76</span>,<span class="hljs-number">77</span>,<span class="hljs-number">78</span>,<span class="hljs-number">79</span>,<span class="hljs-number">80</span>,<span class="hljs-number">81</span>,<span class="hljs-number">82</span>,<span class="hljs-number">83</span>,<span class="hljs-number">84</span>,<span class="hljs-number">85</span>,<span class="hljs-number">86</span>,<span class="hljs-number">87</span>,<span class="hljs-number">88</span>,<span class="hljs-number">89</span>,<span class="hljs-number">90</span>,<span class="hljs-number">91</span>,<span class="hljs-number">92</span>,<span class="hljs-number">93</span>,<span class="hljs-number">94</span>,<span class="hljs-number">95</span>,<span class="hljs-number">96</span>,<span class="hljs-number">97</span>,<span class="hljs-number">98</span>,<span class="hljs-number">99</span>,<span class="hljs-number">100</span>)
      ) inner_unlocks
    <span class="hljs-keyword">WHERE</span>
      rn = <span class="hljs-number">1</span>
  ) <span class="hljs-keyword">AS</span> outer_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = outer_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  outer_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>;

+<span class="hljs-comment">---------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
7590630 rows in <span class="hljs-keyword">set</span> (<span class="hljs-number">24.816</span> sec)

+<span class="hljs-comment">---------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">7590630</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">26.207</span> sec)

+<span class="hljs-comment">---------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">7590630</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">25.766</span> sec)

+<span class="hljs-comment">---------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">7590630</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">26.346</span> sec)

+<span class="hljs-comment">---------+-----------+----------------+----------+----------------------------+---------------------+------------+----------------------------+----------------------------+----+</span>
<span class="hljs-number">7590630</span> <span class="hljs-keyword">rows</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">26.877</span> sec)
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Function (Average)</strong></td><td><strong>Formula</strong></td><td><strong>Outcome</strong></td></tr>
</thead>
<tbody>
<tr>
<td>JOIN</td><td><em>1x run b/c of length of time</em></td><td>174 sec</td></tr>
<tr>
<td>Window Function</td><td>(24.816 + 26.207 + 25.766 + 26.346 + 26.877) / 5</td><td>26 sec</td></tr>
<tr>
<td></td><td></td><td></td></tr>
<tr>
<td>Improvement</td><td>((174 - 26) / 174) × 100</td><td>85.06%</td></tr>
</tbody>
</table>
</div><div data-node-type="callout">
<div data-node-type="callout-emoji">🟢</div>
<div data-node-type="callout-text">Window Function Wins! With a 85% improvement over the JOIN.</div>
</div>

<p>Ok. So JOINs work perfectly for small to medium datasets but NOT for large scale datasets. But why?</p>
<p>Let's look at the query plan and compare to the join to better understand why.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">EXPLAIN</span> <span class="hljs-keyword">SELECT</span>
  outer_unlocks.*
<span class="hljs-keyword">FROM</span>
  (
    <span class="hljs-keyword">SELECT</span>
      inner_unlocks.*
    <span class="hljs-keyword">FROM</span>
      (
        <span class="hljs-keyword">SELECT</span>
          achievement_unlocks.*,
          ROW_NUMBER() <span class="hljs-keyword">OVER</span> (
            <span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id,
            achievement_id
            <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span>
              <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>
          ) <span class="hljs-keyword">AS</span> rn
        <span class="hljs-keyword">FROM</span>
          achievement_unlocks
        <span class="hljs-keyword">WHERE</span>
          deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
          <span class="hljs-keyword">AND</span> guild_id = <span class="hljs-number">1002</span>
          <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">15</span>,<span class="hljs-number">16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18</span>,<span class="hljs-number">19</span>,<span class="hljs-number">20</span>,<span class="hljs-number">21</span>,<span class="hljs-number">22</span>,<span class="hljs-number">23</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>,<span class="hljs-number">26</span>,<span class="hljs-number">27</span>,<span class="hljs-number">28</span>,<span class="hljs-number">29</span>,<span class="hljs-number">30</span>,<span class="hljs-number">31</span>,<span class="hljs-number">32</span>,<span class="hljs-number">33</span>,<span class="hljs-number">34</span>,<span class="hljs-number">35</span>,<span class="hljs-number">36</span>,<span class="hljs-number">37</span>,<span class="hljs-number">38</span>,<span class="hljs-number">39</span>,<span class="hljs-number">40</span>,<span class="hljs-number">41</span>,<span class="hljs-number">42</span>,<span class="hljs-number">43</span>,<span class="hljs-number">44</span>,<span class="hljs-number">45</span>,<span class="hljs-number">46</span>,<span class="hljs-number">47</span>,<span class="hljs-number">48</span>,<span class="hljs-number">49</span>,<span class="hljs-number">50</span>,<span class="hljs-number">51</span>,<span class="hljs-number">52</span>,<span class="hljs-number">53</span>,<span class="hljs-number">54</span>,<span class="hljs-number">55</span>,<span class="hljs-number">56</span>,<span class="hljs-number">57</span>,<span class="hljs-number">58</span>,<span class="hljs-number">59</span>,<span class="hljs-number">60</span>,<span class="hljs-number">61</span>,<span class="hljs-number">62</span>,<span class="hljs-number">63</span>,<span class="hljs-number">64</span>,<span class="hljs-number">65</span>,<span class="hljs-number">66</span>,<span class="hljs-number">67</span>,<span class="hljs-number">68</span>,<span class="hljs-number">69</span>,<span class="hljs-number">70</span>,<span class="hljs-number">71</span>,<span class="hljs-number">72</span>,<span class="hljs-number">73</span>,<span class="hljs-number">74</span>,<span class="hljs-number">75</span>,<span class="hljs-number">76</span>,<span class="hljs-number">77</span>,<span class="hljs-number">78</span>,<span class="hljs-number">79</span>,<span class="hljs-number">80</span>,<span class="hljs-number">81</span>,<span class="hljs-number">82</span>,<span class="hljs-number">83</span>,<span class="hljs-number">84</span>,<span class="hljs-number">85</span>,<span class="hljs-number">86</span>,<span class="hljs-number">87</span>,<span class="hljs-number">88</span>,<span class="hljs-number">89</span>,<span class="hljs-number">90</span>,<span class="hljs-number">91</span>,<span class="hljs-number">92</span>,<span class="hljs-number">93</span>,<span class="hljs-number">94</span>,<span class="hljs-number">95</span>,<span class="hljs-number">96</span>,<span class="hljs-number">97</span>,<span class="hljs-number">98</span>,<span class="hljs-number">99</span>,<span class="hljs-number">100</span>)
      ) inner_unlocks
    <span class="hljs-keyword">WHERE</span>
      rn = <span class="hljs-number">1</span>
  ) <span class="hljs-keyword">AS</span> outer_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = outer_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  outer_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>;

+<span class="hljs-comment">----+-------------+---------------------+------------+--------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------+------------------------------------------------------------------+------+----------+-----------------------------+</span>
| id | select_type | table               | partitions | type   | possible_keys                                                                                                                                                           | key                                        | key_len | ref                                                              | rows | filtered | Extra                       |
+<span class="hljs-comment">----+-------------+---------------------+------------+--------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------+------------------------------------------------------------------+------+----------+-----------------------------+</span>
|  1 | PRIMARY     | &lt;derived3&gt;          | NULL       | ALL    | NULL                                                                                                                                                                    | NULL                                       | NULL    | NULL                                                             |  485 |     1.00 | Using where                 |
|  1 | PRIMARY     | achievements        | NULL       | eq_ref | PRIMARY                                                                                                                                                                 | PRIMARY                                    | 8       | inner_unlocks.achievement_id                                     |    1 |   100.00 | Using index                 |
|  1 | PRIMARY     | games_achievements  | NULL       | ref    | index_games_achievements_on_achievement_id,index_games_achievements_on_game_id                                                                                          | index_games_achievements_on_achievement_id | 8       | inner_unlocks.achievement_id                                     |   17 |   100.00 | NULL                        |
|  1 | PRIMARY     | games               | NULL       | eq_ref | PRIMARY                                                                                                                                                                 | PRIMARY                                    | 8       | gaming_achievement_system_development.games_achievements.game_id |    1 |   100.00 | Using index                 |
|  3 | DERIVED     | achievement_unlocks | NULL       | ref    | idx_achievement_unlocks_covering_latest,index_achievement_unlocks_on_achievement_id,index_achievement_unlocks_on_guild_id,idx_window_function_optimal,idx_join_approach | index_achievement_unlocks_on_guild_id      | 8       | const                                                            | 4858 |    10.00 | Using where; Using filesort |
+<span class="hljs-comment">----+-------------+---------------------+------------+--------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------+------------------------------------------------------------------+------+----------+-----------------------------+</span>
5 rows in <span class="hljs-keyword">set</span>, <span class="hljs-number">2</span> <span class="hljs-keyword">warnings</span> (<span class="hljs-number">0.334</span> sec)
</code></pre>
<pre><code class="lang-sql"><span class="hljs-keyword">EXPLAIN</span> <span class="hljs-keyword">ANALYZE</span> <span class="hljs-keyword">SELECT</span>
  outer_unlocks.*
<span class="hljs-keyword">FROM</span>
  (
    <span class="hljs-keyword">SELECT</span>
      inner_unlocks.*
    <span class="hljs-keyword">FROM</span>
      (
        <span class="hljs-keyword">SELECT</span>
          achievement_unlocks.*,
          ROW_NUMBER() <span class="hljs-keyword">OVER</span> (
            <span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> player_id,
            achievement_id
            <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span>
              <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>
          ) <span class="hljs-keyword">AS</span> rn
        <span class="hljs-keyword">FROM</span>
          achievement_unlocks
        <span class="hljs-keyword">WHERE</span>
          deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
          <span class="hljs-keyword">AND</span> guild_id = <span class="hljs-number">965</span>
          <span class="hljs-keyword">AND</span> achievement_id <span class="hljs-keyword">IN</span> (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">15</span>,<span class="hljs-number">16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18</span>,<span class="hljs-number">19</span>,<span class="hljs-number">20</span>,<span class="hljs-number">21</span>,<span class="hljs-number">22</span>,<span class="hljs-number">23</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>,<span class="hljs-number">26</span>,<span class="hljs-number">27</span>,<span class="hljs-number">28</span>,<span class="hljs-number">29</span>,<span class="hljs-number">30</span>,<span class="hljs-number">31</span>,<span class="hljs-number">32</span>,<span class="hljs-number">33</span>,<span class="hljs-number">34</span>,<span class="hljs-number">35</span>,<span class="hljs-number">36</span>,<span class="hljs-number">37</span>,<span class="hljs-number">38</span>,<span class="hljs-number">39</span>,<span class="hljs-number">40</span>,<span class="hljs-number">41</span>,<span class="hljs-number">42</span>,<span class="hljs-number">43</span>,<span class="hljs-number">44</span>,<span class="hljs-number">45</span>,<span class="hljs-number">46</span>,<span class="hljs-number">47</span>,<span class="hljs-number">48</span>,<span class="hljs-number">49</span>,<span class="hljs-number">50</span>,<span class="hljs-number">51</span>,<span class="hljs-number">52</span>,<span class="hljs-number">53</span>,<span class="hljs-number">54</span>,<span class="hljs-number">55</span>,<span class="hljs-number">56</span>,<span class="hljs-number">57</span>,<span class="hljs-number">58</span>,<span class="hljs-number">59</span>,<span class="hljs-number">60</span>,<span class="hljs-number">61</span>,<span class="hljs-number">62</span>,<span class="hljs-number">63</span>,<span class="hljs-number">64</span>,<span class="hljs-number">65</span>,<span class="hljs-number">66</span>,<span class="hljs-number">67</span>,<span class="hljs-number">68</span>,<span class="hljs-number">69</span>,<span class="hljs-number">70</span>,<span class="hljs-number">71</span>,<span class="hljs-number">72</span>,<span class="hljs-number">73</span>,<span class="hljs-number">74</span>,<span class="hljs-number">75</span>,<span class="hljs-number">76</span>,<span class="hljs-number">77</span>,<span class="hljs-number">78</span>,<span class="hljs-number">79</span>,<span class="hljs-number">80</span>,<span class="hljs-number">81</span>,<span class="hljs-number">82</span>,<span class="hljs-number">83</span>,<span class="hljs-number">84</span>,<span class="hljs-number">85</span>,<span class="hljs-number">86</span>,<span class="hljs-number">87</span>,<span class="hljs-number">88</span>,<span class="hljs-number">89</span>,<span class="hljs-number">90</span>,<span class="hljs-number">91</span>,<span class="hljs-number">92</span>,<span class="hljs-number">93</span>,<span class="hljs-number">94</span>,<span class="hljs-number">95</span>,<span class="hljs-number">96</span>,<span class="hljs-number">97</span>,<span class="hljs-number">98</span>,<span class="hljs-number">99</span>,<span class="hljs-number">100</span>)
      ) inner_unlocks
    <span class="hljs-keyword">WHERE</span>
      rn = <span class="hljs-number">1</span>
  ) <span class="hljs-keyword">AS</span> outer_unlocks
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> achievements <span class="hljs-keyword">ON</span> achievements.id = outer_unlocks.achievement_id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games_achievements <span class="hljs-keyword">ON</span> games_achievements.achievement_id = achievements.id
  <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> games <span class="hljs-keyword">ON</span> games.id = games_achievements.game_id
<span class="hljs-keyword">WHERE</span>
  outer_unlocks.deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>;

+<span class="hljs-comment">---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| <span class="hljs-keyword">EXPLAIN</span>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+<span class="hljs-comment">---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
| -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">120</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">86.9</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">45.7</span>.<span class="hljs-number">.77</span><span class="hljs-number">.5</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">23970</span> loops=<span class="hljs-number">1</span>)
    -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">89.2</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">86.9</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">45.7</span>.<span class="hljs-number">.63</span><span class="hljs-number">.8</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">23970</span> loops=<span class="hljs-number">1</span>)
        -&gt; <span class="hljs-keyword">Nested</span> <span class="hljs-keyword">loop</span> <span class="hljs-keyword">inner</span> <span class="hljs-keyword">join</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">58.8</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4.85</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">45.6</span>.<span class="hljs-number">.47</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1341</span> loops=<span class="hljs-number">1</span>)
            -&gt; Filter: ((inner_unlocks.rn = <span class="hljs-number">1</span>) <span class="hljs-keyword">and</span> (inner_unlocks.deleted_at <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>))  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">57.1</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4.85</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">45.6</span>.<span class="hljs-number">.46</span><span class="hljs-number">.1</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1341</span> loops=<span class="hljs-number">1</span>)
                -&gt; <span class="hljs-keyword">Table</span> <span class="hljs-keyword">scan</span> <span class="hljs-keyword">on</span> inner_unlocks  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">1119.</span><span class="hljs-number">.1183</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">45.6</span>.<span class="hljs-number">.45</span><span class="hljs-number">.9</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4360</span> loops=<span class="hljs-number">1</span>)
                    -&gt; Materialize  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">1119.</span><span class="hljs-number">.1119</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">45.6</span>.<span class="hljs-number">.45</span><span class="hljs-number">.6</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4360</span> loops=<span class="hljs-number">1</span>)
                        -&gt; <span class="hljs-keyword">Window</span> <span class="hljs-keyword">aggregate</span>: row_number() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> achievement_unlocks.player_id,achievement_unlocks.achievement_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> achievement_unlocks.id <span class="hljs-keyword">desc</span> )   (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">36.4</span>.<span class="hljs-number">.43</span><span class="hljs-number">.4</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4360</span> loops=<span class="hljs-number">1</span>)
                            -&gt; <span class="hljs-keyword">Sort</span>: achievement_unlocks.player_id, achievement_unlocks.achievement_id, achievement_unlocks.id <span class="hljs-keyword">DESC</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">4906</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">36.4</span>.<span class="hljs-number">.38</span><span class="hljs-number">.9</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4360</span> loops=<span class="hljs-number">1</span>)
                                -&gt; Filter: ((achievement_unlocks.deleted_at <span class="hljs-keyword">is</span> <span class="hljs-literal">null</span>) <span class="hljs-keyword">and</span> (achievement_unlocks.achievement_id <span class="hljs-keyword">in</span> (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">15</span>,<span class="hljs-number">16</span>,<span class="hljs-number">17</span>,<span class="hljs-number">18</span>,<span class="hljs-number">19</span>,<span class="hljs-number">20</span>,<span class="hljs-number">21</span>,<span class="hljs-number">22</span>,<span class="hljs-number">23</span>,<span class="hljs-number">24</span>,<span class="hljs-number">25</span>,<span class="hljs-number">26</span>,<span class="hljs-number">27</span>,<span class="hljs-number">28</span>,<span class="hljs-number">29</span>,<span class="hljs-number">30</span>,<span class="hljs-number">31</span>,<span class="hljs-number">32</span>,<span class="hljs-number">33</span>,<span class="hljs-number">34</span>,<span class="hljs-number">35</span>,<span class="hljs-number">36</span>,<span class="hljs-number">37</span>,<span class="hljs-number">38</span>,<span class="hljs-number">39</span>,<span class="hljs-number">40</span>,<span class="hljs-number">41</span>,<span class="hljs-number">42</span>,<span class="hljs-number">43</span>,<span class="hljs-number">44</span>,<span class="hljs-number">45</span>,<span class="hljs-number">46</span>,<span class="hljs-number">47</span>,<span class="hljs-number">48</span>,<span class="hljs-number">49</span>,<span class="hljs-number">50</span>,<span class="hljs-number">51</span>,<span class="hljs-number">52</span>,<span class="hljs-number">53</span>,<span class="hljs-number">54</span>,<span class="hljs-number">55</span>,<span class="hljs-number">56</span>,<span class="hljs-number">57</span>,<span class="hljs-number">58</span>,<span class="hljs-number">59</span>,<span class="hljs-number">60</span>,<span class="hljs-number">61</span>,<span class="hljs-number">62</span>,<span class="hljs-number">63</span>,<span class="hljs-number">64</span>,<span class="hljs-number">65</span>,<span class="hljs-number">66</span>,<span class="hljs-number">67</span>,<span class="hljs-number">68</span>,<span class="hljs-number">69</span>,<span class="hljs-number">70</span>,<span class="hljs-number">71</span>,<span class="hljs-number">72</span>,<span class="hljs-number">73</span>,<span class="hljs-number">74</span>,<span class="hljs-number">75</span>,<span class="hljs-number">76</span>,<span class="hljs-number">77</span>,<span class="hljs-number">78</span>,<span class="hljs-number">79</span>,<span class="hljs-number">80</span>,<span class="hljs-number">81</span>,<span class="hljs-number">82</span>,<span class="hljs-number">83</span>,<span class="hljs-number">84</span>,<span class="hljs-number">85</span>,<span class="hljs-number">86</span>,<span class="hljs-number">87</span>,<span class="hljs-number">88</span>,<span class="hljs-number">89</span>,<span class="hljs-number">90</span>,<span class="hljs-number">91</span>,<span class="hljs-number">92</span>,<span class="hljs-number">93</span>,<span class="hljs-number">94</span>,<span class="hljs-number">95</span>,<span class="hljs-number">96</span>,<span class="hljs-number">97</span>,<span class="hljs-number">98</span>,<span class="hljs-number">99</span>,<span class="hljs-number">100</span>)))  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">4906</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">1.79</span>.<span class="hljs-number">.23</span><span class="hljs-number">.8</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4360</span> loops=<span class="hljs-number">1</span>)
                                    -&gt; <span class="hljs-keyword">Index</span> lookup <span class="hljs-keyword">on</span> achievement_unlocks <span class="hljs-keyword">using</span> index_achievement_unlocks_on_guild_id (guild_id = <span class="hljs-number">965</span>)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">4906</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">1.79</span>.<span class="hljs-number">.22</span><span class="hljs-number">.8</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">4858</span> loops=<span class="hljs-number">1</span>)
            -&gt; Single-<span class="hljs-keyword">row</span> covering <span class="hljs-keyword">index</span> lookup <span class="hljs-keyword">on</span> achievements <span class="hljs-keyword">using</span> PRIMARY (<span class="hljs-keyword">id</span> = inner_unlocks.achievement_id)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.271</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">606e-6</span>.<span class="hljs-number">.627e-6</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1</span> loops=<span class="hljs-number">1341</span>)
        -&gt; <span class="hljs-keyword">Index</span> lookup <span class="hljs-keyword">on</span> games_achievements <span class="hljs-keyword">using</span> index_games_achievements_on_achievement_id (achievement_id = inner_unlocks.achievement_id)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">4.85</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">17.9</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">0.0102</span>.<span class="hljs-number">.0</span><span class="hljs-number">.0118</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">17.9</span> loops=<span class="hljs-number">1341</span>)
    -&gt; Single-<span class="hljs-keyword">row</span> covering <span class="hljs-keyword">index</span> lookup <span class="hljs-keyword">on</span> games <span class="hljs-keyword">using</span> PRIMARY (<span class="hljs-keyword">id</span> = games_achievements.game_id)  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.251</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1</span>) (actual <span class="hljs-built_in">time</span>=<span class="hljs-number">462e-6</span>.<span class="hljs-number">.481e-6</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">1</span> loops=<span class="hljs-number">23970</span>)
 |
+<span class="hljs-comment">---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</span>
<span class="hljs-number">1</span> <span class="hljs-keyword">row</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">set</span> (<span class="hljs-number">0.091</span> sec)
</code></pre>
<p>But why?</p>
<hr />
<h3 id="heading-key-performance-differences">Key Performance Differences</h3>
<h4 id="heading-reading-an-query-plan">Reading an Query Plan</h4>
<p>Before we move forward, we need to understand how to read the query plan. The plan is indented like a tree - more indented operations happen first:</p>
<pre><code class="lang-sql">-&gt; Nested loop inner join  ← FINAL RESULT (7.59M rows)
    -&gt; Nested loop inner join  ← INTERMEDIATE STEP (85.3M rows)
        -&gt; Nested loop inner join
            -&gt; Nested loop inner join
                -&gt; Covering index scan on achievements
                -&gt; Filter: achievement_unlocks.guild_id = 1002
</code></pre>
<p>What to look out for in an <code>EXPLAIN ANALYZE</code>:</p>
<ul>
<li><p>Start at the top - that's your final row count</p>
</li>
<li><p>Look for the biggest row count in the middle - that's your bottleneck</p>
</li>
<li><p>Compare estimated vs actual - big differences indicate optimizer problems</p>
</li>
<li><p>Follow the indentation - deeper = happens first</p>
</li>
</ul>
<p>Red flags to watch for:</p>
<ul>
<li><p>Scientific notation (e+6, e+7) usually means trouble</p>
</li>
<li><p>Large gaps between estimated (rows=X) and actual (actual...rows=Y)</p>
</li>
<li><p>Operations that produce way more rows than they consume</p>
</li>
</ul>
<h3 id="heading-elimination-of-the-cartesian-product">Elimination of the Cartesian Product</h3>
<p><strong>Original Join Approach</strong></p>
<ul>
<li>Created 85.3 million intermediate rows</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-comment">-- JOIN Query Plan (EXPLAIN ANAYZE)</span>
-&gt; Nested loop inner join  (cost=44714 rows=27972) (actual time=2.47..121431 rows=85.3e+6 loops=1)

<span class="hljs-comment">-- rows=85.3e+6 means 85.3 × 10^6 = 85,300,000 rows</span>
<span class="hljs-comment">-- This is the actual number of rows produced at this step</span>
<span class="hljs-comment">-- The e+6 notation is scientific notation (85.3 million)</span>
</code></pre>
<ul>
<li>Final result: 7.59 million rows</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-comment">-- JOIN Query Plan (EXPLAIN ANAYZE)</span>
-&gt; Nested loop inner join  (cost=114648 rows=0) (actual time=10153..193912 rows=7.59e+6 loops=1)

<span class="hljs-comment">-- rows=7.59e+6 = 7,590,000 rows (the final output)</span>
<span class="hljs-comment">-- This is the outermost operation, so it represents your final result set</span>
</code></pre>
<ul>
<li>Waste ratio: 91% of computed rows were discarded</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-comment">-- Manual Calculation</span>
<span class="hljs-comment">-- Formula: ((Intermediate Rows - Final Rows) / Intermediate Rows) × 100</span>
<span class="hljs-comment">-- Calculation:</span>
<span class="hljs-comment">-- ((85,300,000 - 7,590,000) / 85,300,000) × 100 = 91.1%</span>
</code></pre>
<p><strong>Teaching Point: The "Actual vs Estimated" Story</strong></p>
<p>Notice the difference between estimated and actual rows:</p>
<p>MySQL's Estimate:</p>
<pre><code class="lang-sql">(cost=44714 rows=27972) <span class="hljs-comment">--  ← MySQL thought: ~28K rows</span>
</code></pre>
<p>Reality:</p>
<pre><code class="lang-sql">(actual time=2.47..121431 rows=85.3e+6) <span class="hljs-comment">--  ← Actually got: 85M rows!</span>
</code></pre>
<p>MySQL's optimizer was off by a factor of 3,000x! This massive underestimate is why it chose a poor execution plan.</p>
<p><strong>Window Function Approach</strong></p>
<ul>
<li>Created 23,970 final rows</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-comment">-- Window Function Query Plan (EXPLAIN ANAYZE)</span>
-&gt; Nested loop inner join  (cost=120 rows=86.9) (actual time=45.7..77.5 rows=23970 loops=1)
</code></pre>
<ul>
<li>No massive intermediate bloat</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-comment">-- Window Function Query Plan (EXPLAIN ANAYZE)</span>
<span class="hljs-comment">-- Let's trace through each step and see the row counts:</span>

-&gt; Nested loop inner join  (rows=23970) <span class="hljs-comment">--  ← Final result</span>
    -&gt; Nested loop inner join  (rows=23970) <span class="hljs-comment">--  ← Still 23,970</span>
        -&gt; Nested loop inner join  (rows=1341) <span class="hljs-comment">--   ← Down to 1,341</span>
            -&gt; Filter: rn = 1  (rows=1341) <span class="hljs-comment">--       ← Filtered to 1,341</span>
                -&gt; Table scan on inner_unlocks <span class="hljs-comment">--  (rows=4360)  ← Started with 4,360</span>
</code></pre>
<ul>
<li>Nearly 100% efficiency - every computed row is useful</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-comment">-- Peak intermediate rows: 23,970 (the highest number we see)</span>
<span class="hljs-comment">-- Final useful rows: 23,970</span>
<span class="hljs-comment">-- Efficiency: 23,970 / 23,970 × 100 = 100%</span>
</code></pre>
<p>Every row computed in the final stages is part of the result!</p>
<p>This reduced the working set from millions to thousands right from the start.</p>
<hr />
<h2 id="heading-understanding-the-performance-characteristics">Understanding the Performance Characteristics</h2>
<h3 id="heading-join-approach-complexity-on-log-n-n">JOIN Approach Complexity: <code>O(n log n + n)</code></h3>
<p>The JOIN must:</p>
<ol>
<li><p>Scan all records for the guild (n records)</p>
</li>
<li><p><code>GROUP BY</code> to find <code>MAX(id)</code> — requires sorting or hash aggregation (n log n)</p>
</li>
<li><p>Join back to retrieve full records (n seeks)</p>
</li>
</ol>
<p>At scale, this creates massive intermediate result sets. The execution plan reveals:</p>
<h4 id="heading-breaking-down-on-log-n-n">Breaking Down <code>O(n log n + n)</code></h4>
<p><strong>What</strong> <code>n</code> <strong>represents</strong></p>
<p>In our case, <code>n =</code> the number of records in the <code>achievement_unlocks</code> table for a specific guild For large guilds, this could be 500,000+ records.</p>
<p><strong>The</strong> <code>+ n</code> <strong>part:</strong> <code>O(n)</code></p>
<ul>
<li><p>This represents the linear scan of all records</p>
</li>
<li><p>If you have 100,000 records, MySQL examines 100,000 records</p>
</li>
<li><p>If you double to 200,000 records, it examines 200,000 records</p>
</li>
</ul>
<p>Growth pattern: Doubles when data doubles</p>
<p><strong>The</strong> <code>n log n</code> <strong>part:</strong> <code>O(n log n)</code></p>
<ul>
<li><p>This represents the <strong>hash aggregation and temporary table</strong> operations for <code>GROUP BY</code> to find <code>MAX(id)</code></p>
</li>
<li><p>MySQL builds hash tables to group records and track maximum values per group</p>
</li>
<li><p>If you have 100,000 records, hash operations take ~100,000 × log₂(100,000) ≈ 1.7 million operations</p>
</li>
<li><p>If you double to 200,000 records, hash operations take ~200,000 × log₂(200,000) ≈ 3.6 million operations</p>
</li>
</ul>
<p>Growth pattern: More than doubles when data doubles (due to hash table resizing and memory management overhead)</p>
<p><strong>Why</strong> <code>n log n</code> <strong>dominates:</strong></p>
<ul>
<li><p>As data grows larger, <code>O(n log n)</code> becomes the bottleneck</p>
</li>
<li><p>For 1 million records: <code>O(n)</code> = 1M operations, but <code>O(n log n)</code> ≈ 20M operations</p>
</li>
</ul>
<p>This is why the complexity is written as <code>O(n log n + n)</code>, simplified to just <code>O(n log n)</code></p>
<p><strong>Real-World Impact</strong></p>
<p>Small dataset (1,000 records):</p>
<ul>
<li><p>Linear scan: ~1,000 operations</p>
</li>
<li><p>Sorting: ~10,000 operations (1,000 × log₂(1,000))</p>
</li>
<li><p>Total: Barely noticeable</p>
</li>
</ul>
<p>Large dataset (1,000,000 records):</p>
<ul>
<li><p>Linear scan: ~1,000,000 operations</p>
</li>
<li><p>Sorting: ~20,000,000 operations (1,000,000 × log₂(1,000,000))</p>
</li>
<li><p>Total: Becomes exponentially expensive</p>
</li>
</ul>
<h3 id="heading-window-function-complexity-on-log-n">Window Function Complexity: <code>O(n log n)</code></h3>
<p>The window function:</p>
<ol>
<li><p>Scans records once (n records)</p>
</li>
<li><p>Sorts within partitions (n log n, but more efficient)</p>
</li>
<li><p>Assigns row numbers during the scan</p>
</li>
<li><p>Filters results</p>
</li>
</ol>
<p>The key advantage: <strong>single pass through the data</strong>.</p>
<h4 id="heading-breaking-down-on-log-n">Breaking Down <code>O(n log n)</code></h4>
<p><strong>What</strong> <code>n</code> <strong>represents</strong></p>
<p>In our case, <code>n =</code> the number of records in the achievement_unlocks table for a specific guild. For large guilds, this could be 500,000+ records.</p>
<p><strong>The sorting component:</strong> <code>O(n log n)</code></p>
<ul>
<li><p>This represents the partitioning and sorting operations for <code>ROW_NUMBER() OVER (PARTITION BY player_id, achievement_id ORDER BY id DESC)</code></p>
</li>
<li><p>MySQL uses a <code>filesort</code> operation that allocates memory buffers incrementally as needed, up to the size indicated by the <code>sort_buffer_size</code> system variable</p>
</li>
<li><p>In-memory sorting is performed with <code>Quick Sort</code>, which has <code>O(n log n)</code> complexity</p>
</li>
<li><p>If you have 100,000 records, sorting operations take ~100,000 × log₂(100,000) ≈ 1.7 million operations</p>
</li>
<li><p>If you double to 200,000 records, sorting operations take ~200,000 × log₂(200,000) ≈ 3.6 million operations</p>
</li>
</ul>
<p>Growth pattern: More than doubles when data doubles (logarithmic factor in sorting)</p>
<p><strong>The partitioning efficiency:</strong></p>
<ul>
<li><p><code>PARTITION BY</code> clause indicates how to divide the query rows into groups. The window function result for a given row is based on the rows of the partition that contains the row</p>
</li>
<li><p>Unlike <code>JOIN</code> approaches, partitioning creates isolated sorting contexts</p>
</li>
<li><p>Each <code>(player_id, achievement_id)</code> combination is sorted independently</p>
</li>
</ul>
<p>Outcome: This dramatically reduces the working set size per partition</p>
<p><strong>Why this scales better than JOIN:</strong></p>
<ul>
<li><p><em>No Cartesian products</em>: Window functions avoid the massive intermediate result sets</p>
</li>
<li><p><em>Localized sorting</em>: Each partition sorts independently, preventing exponential growth</p>
</li>
<li><p><em>Single-pass processing</em>: Data is read once, partitioned, sorted, and numbered in a single operation</p>
</li>
</ul>
<p><strong>Real-World Impact</strong></p>
<p>Small dataset (1,000 records):</p>
<ul>
<li><p>Linear scan: ~1,000 operations</p>
</li>
<li><p>Sorting: ~10,000 operations (1,000 × log₂(1,000))</p>
</li>
<li><p>Total: Competitive with JOIN approach</p>
</li>
</ul>
<p>Large dataset (1,000,000 records):</p>
<p>Window function sorting: ~20,000,000 operations (1,000,000 × log₂(1,000,000))</p>
<ul>
<li><p><em>Crucially</em>: No intermediate table explosion</p>
</li>
<li><p><em>Memory efficiency</em>: MySQL can use filesort to efficiently handle in memory, without temporary files for many window function operations</p>
</li>
<li><p><em>Total</em>: Scales predictably without the multiplicative penalty of JOINs</p>
</li>
</ul>
<hr />
<h2 id="heading-index-design-reality-check">Index Design Reality Check</h2>
<p>Indexes may, or may not, have a profound impact on window function and JOIN performance.</p>
<h3 id="heading-the-indexes-tested">The indexes tested</h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- "Optimal" for window functions (5 columns)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_window_function_optimal <span class="hljs-keyword">ON</span> achievement_unlocks (guild_id, deleted_at, player_id, achievement_id, <span class="hljs-keyword">id</span> <span class="hljs-keyword">DESC</span>);

<span class="hljs-comment">-- "Optimal" for JOIN approach (4 columns)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_join_approach <span class="hljs-keyword">ON</span> achievement_unlocks (guild_id, deleted_at, player_id, achievement_id);

<span class="hljs-comment">-- Simple single-column index (legacy)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> index_achievement_unlocks_on_guild_id <span class="hljs-keyword">ON</span> achievement_unlocks (guild_id);
</code></pre>
<p>The window function index follows conventional wisdom:</p>
<ul>
<li><p><code>guild_id, deleted_at</code> — <code>WHERE</code> clause filters</p>
</li>
<li><p><code>player_id, achievement_id</code> — <code>PARTITION BY</code> columns</p>
</li>
<li><p><code>id DESC</code> — <code>ORDER BY</code> column</p>
</li>
</ul>
<h3 id="heading-mysqls-surprising-choice">MySQL's Surprising Choice</h3>
<p>Despite having sophisticated multi-column indexes available, MySQL's optimizer consistently chose the simplest option:</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- EXPLAIN output for both small and large datasets</span>
| possible_keys | idx_window_function_optimal,idx_join_approach,index_achievement_unlocks_on_guild_id |
| key           | index_achievement_unlocks_on_guild_id                                               |
| key_len       | 8                                                                                   |
| Extra         | Using where; Using filesort                                                         |
</code></pre>
<p>This pattern held true across different data sizes:</p>
<ul>
<li><p>Small guild (965): 4,858 rows → chose simple index</p>
</li>
<li><p>Large guild (1002): 2.9M rows → chose same simple index</p>
</li>
</ul>
<h3 id="heading-testing-the-perfect-index-theory">Testing the "Perfect" Index Theory</h3>
<p>Forcing MySQL to use the theoretically optimal index with hints:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span> *, ROW_NUMBER() <span class="hljs-keyword">OVER</span> (...) <span class="hljs-keyword">AS</span> rn
    <span class="hljs-keyword">FROM</span> achievement_unlocks <span class="hljs-keyword">USE</span> <span class="hljs-keyword">INDEX</span> (idx_window_function_optimal)
    <span class="hljs-keyword">WHERE</span> guild_id = <span class="hljs-number">1002</span> <span class="hljs-keyword">AND</span> deleted_at <span class="hljs-keyword">IS</span> NULL...
) ranked <span class="hljs-keyword">WHERE</span> rn = <span class="hljs-number">1</span>;
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">❌</div>
<div data-node-type="callout-text">Result: No performance difference.</div>
</div>

<h3 id="heading-what-this-reveals-about-modern-database-optimization">What This Reveals About Modern Database Optimization</h3>
<ol>
<li><p><strong>Initial filtering trumps perfect matching</strong>: The biggest performance gain comes from reducing the working set size quickly</p>
</li>
<li><p><strong>Window function efficiency is algorithmic</strong>: MySQL's window function implementation handles sorting and partitioning efficiently, even with "suboptimal" indexing</p>
</li>
<li><p><strong>Cost-based optimization works</strong>: The optimizer correctly determined that simple filtering + efficient algorithms beats complex index overhead</p>
</li>
</ol>
<h3 id="heading-the-bottom-line">The Bottom Line</h3>
<p>The dramatic 85% performance improvement (174s → 26s) came from choosing the right approach, not from index engineering. Window functions derive their advantage from superior algorithms that work efficiently regardless of whether you have the "perfect" index. This finding challenges the conventional wisdom that database performance requires perfectly matched indexes. Sometimes, simple is better—and the algorithm choice matters more than index optimization.</p>
<hr />
<h2 id="heading-performance-tuning-insights">Performance Tuning Insights</h2>
<p>Through extensive benchmarking, I discovered several critical factors:</p>
<h3 id="heading-data-distribution-matters">Data Distribution Matters</h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Check duplication rate</span>
<span class="hljs-keyword">SELECT</span>
    <span class="hljs-keyword">AVG</span>(cnt) <span class="hljs-keyword">as</span> avg_attempts,
    <span class="hljs-keyword">MAX</span>(cnt) <span class="hljs-keyword">as</span> max_attempts
<span class="hljs-keyword">FROM</span> (
    <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">as</span> cnt
    <span class="hljs-keyword">FROM</span> achievement_unlocks
    <span class="hljs-keyword">WHERE</span> guild_id = <span class="hljs-number">1001</span> <span class="hljs-keyword">AND</span> deleted_at <span class="hljs-keyword">IS</span> <span class="hljs-literal">NULL</span>
    <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> player_id, achievement_id
) t;
</code></pre>
<ul>
<li><p><strong>Low duplication (1-2 attempts)</strong>: JOINs often win</p>
</li>
<li><p><strong>High duplication (10+ attempts)</strong>: Window functions dominate</p>
</li>
</ul>
<h3 id="heading-result-set-size-impact">Result Set Size Impact</h3>
<p>Returning large result sets can mask query performance. Always test with COUNT(*) first:</p>
<pre><code class="lang-sql"><span class="hljs-comment">-- Test query performance without result transfer overhead</span>
<span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">COUNT</span>(*) <span class="hljs-keyword">FROM</span> ( <span class="hljs-comment">/* your query here */</span> ) t;
</code></pre>
<h3 id="heading-mysql-configuration">MySQL Configuration</h3>
<p>Key settings that affect window function performance:</p>
<ul>
<li><p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/server-system-variables.html#sysvar_sort_buffer_size"><code>sort_buffer_size</code></a>: Increase for large partitions</p>
</li>
<li><p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/server-system-variables.html#sysvar_tmp_table_size"><code>tmp_table_size</code></a>: Critical for window function temporary tables</p>
</li>
<li><p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/server-system-variables.html#sysvar_join_buffer_size"><code>join_buffer_size</code></a>: Affects JOIN approach performance</p>
</li>
</ul>
<hr />
<h2 id="heading-surprising-findings">Surprising Findings</h2>
<p>Our investigation revealed several counterintuitive insights:</p>
<ol>
<li><p><strong>Modern MySQL optimizes GROUP BY extremely well</strong> — with proper indexes, the JOIN approach can outperform window functions for simple "latest record" queries up to ~1M records.</p>
</li>
<li><p><strong>Window functions have overhead</strong> — the partitioning and ranking process isn't free. For small datasets with low duplication, this overhead exceeds the benefit.</p>
</li>
<li><p><strong>Index design is everything</strong> — a poorly indexed window function query will perform worse than a well-indexed JOIN, regardless of data size.</p>
</li>
</ol>
<hr />
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ol>
<li><p><strong>Window functions aren't always faster</strong> — profile your specific data patterns</p>
</li>
<li><p><strong>The inflection point is around 1M records</strong> with moderate duplication</p>
</li>
<li><p><strong>Complex analytical queries always favor window functions</strong> — ranking, running totals, inter-row comparisons</p>
</li>
<li><p><strong>Index design must match your query pattern</strong> — column order matters tremendously, however</p>
</li>
<li><p><strong>Algorithmic choice is a key component to query performance</strong> - complex queries involving multiple tables can have an impact on the optimizers algorithmic choice</p>
</li>
<li><p><strong>Consider a hybrid approach</strong> — use the right tool for each scenario</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The journey from a timing-out query to a sub-second response taught us that database optimization is rarely about finding a silver bullet. Window functions are powerful tools, but understanding when and how to use them — versus traditional approaches — is what separates good solutions from great ones.</p>
<p>For those interested in experimenting with these patterns, the complete demo application with realistic seed data is available at <a target="_blank" href="http://github.com/alvincrespo/gaming_achievement_system">github.com/alvincrespo/gaming_achievement_system</a>. The repository includes benchmarking tools and seed data generators to reproduce these performance characteristics at various scales.</p>
<p>Remember: always measure with your actual data. The beauty of SQL optimization is that the same query can have vastly different performance characteristics based on data distribution, and the only way to know for sure is to test.</p>
<hr />
<h2 id="heading-references">References</h2>
<h3 id="heading-mysql-official-documentation">MySQL Official Documentation</h3>
<p>MySQL 8.4 Reference Manual - GROUP BY Optimization<br />Oracle Corporation. MySQL 8.4 Reference Manual, Section 10.2.1.17.<br /><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/group-by-optimization.html">https://dev.mysql.com/doc/refman/8.4/en/group-by-optimization.html</a></p>
<p>MySQL 8.4 Reference Manual - ORDER BY Optimization<br />Oracle Corporation. MySQL 8.4 Reference Manual, Section 10.2.1.16.<br /><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/order-by-optimization.html">https://dev.mysql.com/doc/refman/8.4/en/order-by-optimization.html</a></p>
<p>MySQL 8.0 Reference Manual - Window Functions<br />Oracle Corporation. MySQL 8.0 Reference Manual, Section 14.20.<br /><a target="_blank" href="https://dev.mysql.com/doc/refman/9.4/en/window-functions.html">https://dev.mysql.com/doc/refman/9.4/en/window-functions.html</a></p>
<p>MySQL 8.4 Reference Manual - Window Function Concepts and Syntax<br />MySQL AB. Window Function Concepts and Syntax. MySQL 8.4 Reference Manual.<br /><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/window-functions-usage.html">https://dev.mysql.com/doc/refman/8.4/en/window-functions-usage.html</a></p>
<p>MySQL 8.4 Reference Manual - Window Function Descriptions<br />MySQL AB. Window Function Descriptions. MySQL 8.4 Reference Manual.<br /><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/window-function-descriptions.html">https://dev.mysql.com/doc/refman/8.4/en/window-function-descriptions.html</a></p>
<p>MySQL Developer Zone - Filesort Class Reference<br />MySQL AB. Filesort Class Reference. MySQL Server Documentation.<br /><a target="_blank" href="https://dev.mysql.com/doc/dev/mysql-server/latest/classFilesort.html">https://dev.mysql.com/doc/dev/mysql-server/latest/classFilesort.html</a></p>
<p>Filesort Optimization in MySQL 5.7.3: Pack Values in the Sort Buffer<br />Lu, Manyi. MySQL Developer Blog, February 6, 2014.<br /><a target="_blank" href="https://dev.mysql.com/blog-archive/filesort-optimization-in-5-7-3-pack-values-in-the-sort-buffer/">https://dev.mysql.com/blog-archive/filesort-optimization-in-5-7-3-pack-values-in-the-sort-buffer/</a></p>
<p>Removal of Implicit and Explicit Sorting for GROUP BY<br />MySQL Developer Team. MySQL Developer Blog.<br /><a target="_blank" href="https://dev.mysql.com/blog-archive/removal-of-implicit-and-explicit-sorting-for-group-by/">https://dev.mysql.com/blog-archive/removal-of-implicit-and-explicit-sorting-for-group-by/</a></p>
<h3 id="heading-computer-science-and-algorithm-complexity">Computer Science and Algorithm Complexity</h3>
<p>SQL Query Complexity - GeeksforGeeks<br />GeeksforGeeks. "SQL Query Complexity," September 5, 2024.<br /><a target="_blank" href="https://www.geeksforgeeks.org/sql-query-complexity/">https://www.geeksforgeeks.org/sql-query-complexity/</a></p>
<p>Big O Notation Tutorial - GeeksforGeeks<br />GeeksforGeeks. "Big O Notation Tutorial - A Guide to Big O Analysis," April 21, 2025.<br /><a target="_blank" href="https://www.geeksforgeeks.org/dsa/analysis-algorithms-big-o-analysis/">https://www.geeksforgeeks.org/dsa/analysis-algorithms-big-o-analysis/</a></p>
<p>Time Complexity and Big-O Notation<br />Okeke, Chinenye. "Mastering Big O Notation: Understanding Time and Space Complexity in Algorithms," Medium, July 16, 2023.<br /><a target="_blank" href="https://medium.com/@DevChy/introduction-to-big-o-notation-time-and-space-complexity-f747ea5bca58">https://medium.com/@DevChy/introduction-to-big-o-notation-time-and-space-complexity-f747ea5bca58</a></p>
<h3 id="heading-stack-overflow-community-discussions">Stack Overflow Community Discussions</h3>
<p>Where Can I Read About Time Complexity (Big-O Notation) of MySQL Queries?<br />Stack Overflow Community Discussion.<br /><a target="_blank" href="https://stackoverflow.com/questions/38675339/where-can-i-read-about-time-complexity-big-o-notation-of-mysql-queries">https://stackoverflow.com/questions/38675339/where-can-i-read-about-time-complexity-big-o-notation-of-mysql-queries</a></p>
<p>What is the Big-O for SQL SELECT?<br />Stack Overflow Community Discussion.<br /><a target="_blank" href="https://stackoverflow.com/questions/1347552/what-is-the-big-o-for-sql-select">https://stackoverflow.com/questions/1347552/what-is-the-big-o-for-sql-select</a></p>
<p>Big-Oh Performance of an Inner Join on Two Indexes<br />Stack Overflow Community Discussion.<br /><a target="_blank" href="https://stackoverflow.com/questions/16591044/big-oh-performance-of-an-inner-join-on-two-indexes">https://stackoverflow.com/questions/16591044/big-oh-performance-of-an-inner-join-on-two-indexes</a></p>
<p>How can I improve query performances using Using temporary; Using filesort<br />Database Administrators Stack Exchange. How can I improve query performances using Using temporary; Using filesort.<br /><a target="_blank" href="https://dba.stackexchange.com/questions/216305/how-can-i-improve-query-performances-using-using-temporary-using-filesort">https://dba.stackexchange.com/questions/216305/how-can-i-improve-query-performances-using-using-temporary-using-filesort</a></p>
<h3 id="heading-technical-articles-educational-resources">Technical Articles + Educational Resources</h3>
<p>An Introduction to Big O Notation<br />Adrian. "An Introduction to Big O Notation," DEV Community, October 24, 2020.<br /><a target="_blank" href="https://dev.to/eidorianavi/an-introduction-to-big-o-notation-424e">https://dev.to/eidorianavi/an-introduction-to-big-o-notation-424e</a></p>
<p>Big O Notation: Time Complexity &amp; Examples Explained<br />Simplilearn. "Big O Notation: Time Complexity &amp; Examples Explained," May 4, 2025.<br /><a target="_blank" href="https://www.simplilearn.com/big-o-notation-in-data-structure-article">https://www.simplilearn.com/big-o-notation-in-data-structure-article</a></p>
<p>What does Using filesort mean in MySQL?<br />Percona Blog. What does Using filesort mean in MySQL? May 14, 2019.<br /><a target="_blank" href="https://www.percona.com/blog/what-does-using-filesort-mean-in-mysql/">https://www.percona.com/blog/what-does-using-filesort-mean-in-mysql/</a></p>
<p>MySQL ROW_NUMBER and Its Useful Applications<br />MySQL Tutorial. MySQL ROW_NUMBER and Its Useful Applications. January 4, 2024.<br /><a target="_blank" href="https://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/">https://www.mysqltutorial.org/mysql-window-functions/mysql-row_number-function/</a></p>
<p>MySQL Window Functions - Full Tutorial with Examples<br />Devart. MySQL Window Functions - Full Tutorial with Examples.<br /><a target="_blank" href="https://www.devart.com/dbforge/mysql/studio/mysql-window-functions.html">https://www.devart.com/dbforge/mysql/studio/mysql-window-functions.html</a></p>
<p>SQL ROW_NUMBER() Function: Syntax and Applications<br />StrataScratch. SQL ROW_NUMBER() Function: Syntax and Applications.<br /><a target="_blank" href="https://www.stratascratch.com/blog/sql-row_number-function-syntax-and-applications/">https://www.stratascratch.com/blog/sql-row_number-function-syntax-and-applications/</a></p>
<p>Overview of the SQL ROW_NUMBER function<br />SQL Shack. Overview of the SQL ROW_NUMBER function. November 16, 2018.<br /><a target="_blank" href="https://www.sqlshack.com/overview-of-the-sql-row-number-function/">https://www.sqlshack.com/overview-of-the-sql-row-number-function/</a></p>
<p>Which sorting algorithm(s) does MySQL use?<br />Stack Overflow. Which sorting algorithm(s) does MySQL use?<br /><a target="_blank" href="https://stackoverflow.com/questions/7365983/which-sorting-algorithms-does-mysql-use">https://stackoverflow.com/questions/7365983/which-sorting-algorithms-does-mysql-use</a></p>
<p>MySQL: Tuning filesorts and temporary tables<br />Pythian Blog. MySQL: Tuning filesorts and temporary tables.<br /><a target="_blank" href="https://blog.pythian.com/mysql-tuning-filesorts-and-temporary-tables/">https://blog.pythian.com/mysql-tuning-filesorts-and-temporary-tables/</a></p>
<p>SQL Window Functions<br />Mode Analytics. SQL Window Functions. May 23, 2016.<br /><a target="_blank" href="https://mode.com/sql-tutorial/sql-window-functions/">https://mode.com/sql-tutorial/sql-window-functions/</a></p>
<p>SQL | Window Functions | ROW_NUMBER()<br />Codecademy. SQL | Window Functions | ROW_NUMBER(). May 13, 2023.<br /><a target="_blank" href="https://www.codecademy.com/resources/docs/sql/window-functions/row-number">https://www.codecademy.com/resources/docs/sql/window-functions/row-number</a></p>
<p>Talking about filesort from the MySQL temporary table<br />Alibaba Cloud. Talking about filesort from the MySQL temporary table.<br /><a target="_blank" href="https://topic.alibabacloud.com/a/talking-about-filesort-from-the-mysql-temporary-table_1_41_32118319.html">https://topic.alibabacloud.com/a/talking-about-filesort-from-the-mysql-temporary-table_1_41_32118319.html</a></p>
<p>MySQL using filesort using temporary<br />Alibaba Cloud. MySQL using filesort using temporary.<br /><a target="_blank" href="https://topic.alibabacloud.com/a/mysql-using-filesort-using-temporary_1_41_30009346.html">https://topic.alibabacloud.com/a/mysql-using-filesort-using-temporary_1_41_30009346.html</a></p>
<p>How to read MySQL EXPLAINs PlanetScale. Savannah Longoria. How to read MySQL EXPLAINs. March 29, 2023 <a target="_blank" href="https://planetscale.com/blog/how-read-mysql-explains">https://planetscale.com/blog/how-read-mysql-explains</a></p>
<hr />
<p>Note: All URLs were accessed and verified as of July 25, 2025. Some MySQL documentation versions may have been updated since initial publication.</p>
]]></content:encoded></item><item><title><![CDATA[Integrating Stripe Webhooks in Ruby on Rails]]></title><description><![CDATA[Learn how to integrate Stripe webhooks with a Ruby on Rails app to handle subscription updates efficiently and securely]]></description><link>https://alvincrespo.hashnode.dev/integrating-stripe-webhooks-in-ruby-on-rails</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/integrating-stripe-webhooks-in-ruby-on-rails</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[stripe]]></category><category><![CDATA[webhooks]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Fri, 18 Apr 2025 22:59:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/CFBoeNgZI3g/upload/3a7f375ef87bf53a22131e2cea77faed.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Handling subscription payments is a common requirement for many modern web applications. Stripe is one of the most popular payment processing services, and their webhook system allows your application to respond to events happening within the Stripe ecosystem. In this post, I'll walk you through integrating Stripe webhooks into a Rails application to handle subscription updates.</p>
<h2 id="heading-what-are-webhooks">What are Webhooks?</h2>
<p>Before diving into the code, let's understand what <a target="_blank" href="https://www.redhat.com/en/topics/automation/what-is-a-webhook">webhooks</a> are. Simply put, webhooks are automated messages sent from one application to another when certain events occur. In our case, Stripe will send notifications to our application when events like subscription updates happen. For example, if you are using Stripe’s built-in <a target="_blank" href="https://docs.stripe.com/customer-management">Customer Portal</a> feature, you may want to be aware of any updates in your application.</p>
<h2 id="heading-the-story">The Story</h2>
<p>For this walkthrough, let’s look at the following acceptance criteria:</p>
<blockquote>
<p>As a user whose <strong><em>free trial</em></strong> has ended</p>
<p>I would like to upgrade to the <strong><em>Basic - Monthly</em> plan</strong> in the Customer Portal</p>
<p>When I upgrade to the <strong>Basic - Monthly plan</strong>, I want to see that change in my user settings.</p>
</blockquote>
<p>There is another set of related acceptance criteria:</p>
<blockquote>
<p>As a customer support person, in the process of upgrading a persons subscription</p>
<p>I would like to upgrade their subscription in Stripes Dashboard</p>
<p>And when the customer logs in, they should see their subscription updated in their user settings.</p>
</blockquote>
<p>Both these stories have something in common: an event has taken place outside the main application and our application needs to know about it.</p>
<p>The approach here then, is to do a simple integration with <a target="_blank" href="https://docs.stripe.com/webhooks">Stripes Webhooks</a>. We’ll capture a specific event related to a subscription change on the user and then update our database.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>For this tutorial, you'll need:</p>
<ul>
<li><p>A Ruby on Rails application</p>
</li>
<li><p>A Stripe account with API keys</p>
</li>
<li><p>Basic understanding of Rails models and controllers</p>
</li>
</ul>
<h2 id="heading-setting-up-your-models">Setting Up Your Models</h2>
<p>Our application needs to track users and their subscriptions. We'll use three models:</p>
<ol>
<li><p><code>User</code> - Represents a customer using <strong>our</strong> application</p>
</li>
<li><p><code>Subscription</code> - Represents a subscription plan in Stripe</p>
</li>
<li><p><code>SubscriptionUser</code> - A join model connecting users and subscriptions</p>
</li>
</ol>
<pre><code class="lang-ruby"><span class="hljs-comment"># app/models/user.rb</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> &lt; ApplicationRecord</span>
  has_one <span class="hljs-symbol">:subscription_user</span>
  has_one <span class="hljs-symbol">:subscription</span>, <span class="hljs-symbol">through:</span> <span class="hljs-symbol">:subscription_user</span>

  <span class="hljs-comment"># This method will be called by our webhook</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">update_subscription</span><span class="hljs-params">(stripe_subscription)</span></span>
    user = User.find_by(<span class="hljs-symbol">stripe_id:</span> stripe_subscription.customer)
    subscription = Subscription.find_by(<span class="hljs-symbol">stripe_price_id:</span> stripe_subscription.plan.id)

    Rails.logger.error(<span class="hljs-string">"Subscription not found for stripe_price_id: <span class="hljs-subst">#{stripe_subscription.plan.id}</span>"</span>) <span class="hljs-keyword">if</span> subscription.blank?

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">if</span> user.blank? <span class="hljs-params">||</span> subscription.blank?

    user.subscription_user.update(
      <span class="hljs-symbol">subscription:</span> subscription,
      <span class="hljs-symbol">stripe_product_id:</span> stripe_subscription.plan.product,
      <span class="hljs-symbol">stripe_subscription_id:</span> stripe_subscription.id
    )
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-comment"># app/models/subscription.rb</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Subscription</span> &lt; ApplicationRecord</span>
  has_and_belongs_to_many <span class="hljs-symbol">:users</span>
<span class="hljs-keyword">end</span>

<span class="hljs-comment"># app/models/subscription_user.rb</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SubscriptionUser</span> &lt; ApplicationRecord</span>
  <span class="hljs-keyword">self</span>.table_name = <span class="hljs-string">"subscriptions_users"</span>

  belongs_to <span class="hljs-symbol">:user</span>
  belongs_to <span class="hljs-symbol">:subscription</span>
<span class="hljs-keyword">end</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Note that we have created a <code>User#update_subscription</code> class method that takes the subscription response from Stripe that we can then leverage to find the user, corresponding subscription and associate them on our join <code>subscriptions_users</code> table. Also, the <code>stripe_subscription</code> is the <a target="_self" href="https://docs.stripe.com/api/subscriptions/object">subscription object</a> from Stripe.</div>
</div>

<h2 id="heading-creating-the-webhooks-controller">Creating the Webhooks Controller</h2>
<p>Next, we'll create a controller to handle incoming webhook event <a target="_blank" href="https://docs.stripe.com/api/events/types#event_types-customer.subscription.updated"><strong>customer.subscription.updated</strong></a> from Stripe:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># app/controllers/webhooks_controller.rb</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebhooksController</span> &lt; ApplicationController</span>
  before_action <span class="hljs-symbol">:setup_event</span>, <span class="hljs-symbol">only:</span> [<span class="hljs-symbol">:stripe</span>]
  before_action <span class="hljs-symbol">:setup_payload</span>, <span class="hljs-symbol">only:</span> [<span class="hljs-symbol">:stripe</span>]
  before_action <span class="hljs-symbol">:setup_signature_header</span>, <span class="hljs-symbol">only:</span> [<span class="hljs-symbol">:stripe</span>]
  before_action <span class="hljs-symbol">:setup_endpoint_secret</span>, <span class="hljs-symbol">only:</span> [<span class="hljs-symbol">:stripe</span>]

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">stripe</span></span>
    <span class="hljs-keyword">begin</span>
      @event = Stripe::Webhook.construct_event(
        @payload, @signature_header, @endpoint_secret
      )
    <span class="hljs-keyword">rescue</span> JSON::ParserError =&gt; _e
      render <span class="hljs-symbol">json:</span> { <span class="hljs-symbol">error:</span> <span class="hljs-string">"Invalid payload"</span> }, <span class="hljs-symbol">status:</span> <span class="hljs-number">400</span> <span class="hljs-keyword">and</span> <span class="hljs-keyword">return</span>
    <span class="hljs-keyword">rescue</span> Stripe::SignatureVerificationError =&gt; _e
      render <span class="hljs-symbol">json:</span> { <span class="hljs-symbol">error:</span> <span class="hljs-string">"Invalid signature"</span> }, <span class="hljs-symbol">status:</span> <span class="hljs-number">400</span> <span class="hljs-keyword">and</span> <span class="hljs-keyword">return</span>
    <span class="hljs-keyword">end</span>

    handle_event

    render <span class="hljs-symbol">json:</span> { <span class="hljs-symbol">message:</span> <span class="hljs-string">"Success"</span> }, <span class="hljs-symbol">status:</span> <span class="hljs-number">200</span>
  <span class="hljs-keyword">end</span>

  private

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup_event</span></span>
    @event = <span class="hljs-literal">nil</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup_payload</span></span>
    @payload = request.body.read
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup_signature_header</span></span>
    @signature_header = request.env[<span class="hljs-string">"HTTP_STRIPE_SIGNATURE"</span>]
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup_endpoint_secret</span></span>
    @endpoint_secret = ENV[<span class="hljs-string">"STRIPE_WEBHOOK_SECRET"</span>]
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle_event</span></span>
    <span class="hljs-keyword">case</span> @event.type
    <span class="hljs-keyword">when</span> <span class="hljs-string">"customer.subscription.updated"</span>
      handle_subscription_updated(@event.data.object)
    <span class="hljs-keyword">else</span>
      Rails.logger.info(<span class="hljs-string">"Unhandled event type: <span class="hljs-subst">#{@event.type}</span>"</span>)
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle_subscription_updated</span><span class="hljs-params">(subscription)</span></span>
    User.update_subscription(subscription)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The controller is pretty straightforward here. The important piece is <code>Stripe::Webhook.construct_event</code>. This method creates an object that normalizes the JSON string sent over by Stripe. This creates an instance of <code>Stripe::Event</code> , we then tap into the <code>data</code> property. The <code>data</code> property is an instance of <code>Stripe::Event::Data</code>. From there we retrieve the <a target="_self" href="https://docs.stripe.com/api/subscriptions/object">Subscription object</a> via the <code>object</code> property on <code>data</code>.</div>
</div>

<h2 id="heading-configure-routes">Configure Routes</h2>
<p>Add the webhook endpoint to your routes:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># config/routes.rb</span>

Rails.application.routes.draw <span class="hljs-keyword">do</span>
  <span class="hljs-comment"># other routes...</span>
  post <span class="hljs-string">'webhooks/stripe'</span>, <span class="hljs-symbol">to:</span> <span class="hljs-string">'webhooks#stripe'</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h2 id="heading-security-considerations">Security Considerations</h2>
<p>Stripe uses a signature verification system to ensure that webhook events are actually coming from Stripe. The <code>Stripe::Webhook.construct_event</code> method verifies this signature. You'll need to set the <code>STRIPE_WEBHOOK_SECRET</code> environment variable with your webhook signing secret from the Stripe dashboard.</p>
<h2 id="heading-testing">Testing</h2>
<p>Testing webhooks can be challenging since they involve external services. Here's a test example that mocks a Stripe webhook event:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># test/controllers/webhooks_controller_test.rb</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">"test_helper"</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">"mocha/minitest"</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WebhooksControllerTest</span> &lt; ActionDispatch::IntegrationTest</span>
  SECRET = <span class="hljs-string">"whsec_test_secret"</span>

  setup <span class="hljs-keyword">do</span>
    @user = users(<span class="hljs-symbol">:user_in_free_trial</span>)
  <span class="hljs-keyword">end</span>

  test <span class="hljs-string">"handle_subscription_updated updates subscription_user when user exists"</span> <span class="hljs-keyword">do</span>
    payload = {
      <span class="hljs-symbol">id:</span> <span class="hljs-string">"evt_123"</span>,
      <span class="hljs-symbol">object:</span> <span class="hljs-string">"event"</span>,
      <span class="hljs-symbol">type:</span> <span class="hljs-string">"customer.subscription.updated"</span>,
      <span class="hljs-symbol">data:</span> {
        <span class="hljs-symbol">object:</span> {
          <span class="hljs-symbol">customer:</span> @user.stripe_id,
          <span class="hljs-symbol">plan:</span> { <span class="hljs-symbol">id:</span> <span class="hljs-string">"price_def456"</span>, <span class="hljs-symbol">product:</span> <span class="hljs-string">"prod_12345678901"</span> },
          <span class="hljs-symbol">id:</span> <span class="hljs-string">"sub_123"</span>
        }
      }
    }.to_json

    ClimateControl.modify <span class="hljs-symbol">STRIPE_WEBHOOK_SECRET:</span> SECRET <span class="hljs-keyword">do</span>
      assert_equal <span class="hljs-string">"Free Trial"</span>, @user.subscription.name

      post webhooks_stripe_url, <span class="hljs-symbol">params:</span> payload, <span class="hljs-symbol">headers:</span> compute_headers(payload)

      @user.reload

      assert_equal <span class="hljs-string">"Basic - Monthly"</span>, @user.subscription.display_name
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">compute_headers</span><span class="hljs-params">(payload)</span></span>
    {
      <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
      <span class="hljs-string">"HTTP_STRIPE_SIGNATURE"</span>: compute_signature(payload)
    }
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">compute_signature</span><span class="hljs-params">(payload)</span></span>
    timestamp = Time.now
    timestamped_payload = <span class="hljs-string">"<span class="hljs-subst">#{timestamp.to_i}</span>.<span class="hljs-subst">#{payload}</span>"</span>
    scheme = <span class="hljs-string">"v1"</span>
    signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(<span class="hljs-string">"sha256"</span>), SECRET, timestamped_payload)

    <span class="hljs-string">"t=<span class="hljs-subst">#{timestamp.to_i}</span>,<span class="hljs-subst">#{scheme}</span>=<span class="hljs-subst">#{signature}</span>"</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">This test verifies that a users subscription is updated without having to mock <code>Stripe::Webhook.construct_event</code>, which is a common practice. However, it is a good idea to minimize the amount of mocking for such a critical piece of an application. To ensure the method runs smoothly, I’ve implemented a <code>compute_signature</code>, which generates a valid header value to check against. The generation of the signature itself can be found in Stripe’s library at <code>Stripe::Signature#generate_header</code>. More info can be found in the reference section below.</div>
</div>

<h2 id="heading-common-issues-and-solutions">Common Issues and Solutions</h2>
<ol>
<li><p><strong>Missing Environment Variables</strong>: Ensure that your <code>STRIPE_WEBHOOK_SECRET</code> is correctly set in all environments.</p>
</li>
<li><p><strong>Incorrect Signature</strong>: Double-check that you're using the correct signing secret from Stripe.</p>
</li>
<li><p><strong>Outdated Stripe API Version</strong>: Make sure your Stripe gem is up to date.</p>
</li>
<li><p><strong>Event Duplication</strong>: Stripe may send the same event multiple times. Your code should be idempotent (able to handle the same event multiple times without side effects).</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Integrating Stripe webhooks into your Rails application allows you to respond to payment events in real-time. This approach is more reliable than polling the Stripe API since it ensures you never miss an event. The implementation we've covered handles subscription updates, but you can easily extend it to handle other event types like <code>payment_intent.succeeded</code> or <code>invoice.payment_failed</code> . Remember to test your integration and keep it future proof by minimizing how much you mock the Stripe library. Happy coding!</p>
<hr />
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://docs.stripe.com/api/subscriptions/object">The Subscription object</a></p>
<p><a target="_blank" href="https://www.rubydoc.info/gems/stripe/Stripe/Event">Class: Stripe::Event</a></p>
<p><a target="_blank" href="https://www.rubydoc.info/gems/stripe/Stripe/Event/Data">Class: Stripe::Event::Data</a></p>
<p><a target="_blank" href="https://docs.stripe.com/api/events/types#event_types-customer.subscription.updated">customer.subscription.updated</a></p>
<p><a target="_blank" href="https://github.com/stripe/stripe-ruby/blob/master/test/stripe/webhook_test.rb#L14-L25">stripe-ruby/test/stripe /webhook_test.rb</a></p>
<p><a target="_blank" href="https://github.com/stripe/stripe-ruby/blob/master/lib/stripe/webhook.rb#L48-L57">stripe-ruby/lib/stripe /webhook.rb#generate_header</a></p>
]]></content:encoded></item><item><title><![CDATA[React, Vite & Production-Ready Docker]]></title><description><![CDATA[A step-by-step guide to containerizing your Vite React app for production, covering Docker best practices, Nginx configuration, and deployment.]]></description><link>https://alvincrespo.hashnode.dev/react-vite-production-ready-docker</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/react-vite-production-ready-docker</guid><category><![CDATA[Docker]]></category><category><![CDATA[React]]></category><category><![CDATA[vite]]></category><category><![CDATA[nginx]]></category><category><![CDATA[Devops]]></category><category><![CDATA[production]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Fri, 31 Jan 2025 20:19:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/j7AMlh2MMHc/upload/ad7596714c2a846733de6ec8bbcbb1b5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my <a target="_blank" href="https://alvincrespo.hashnode.dev/getting-started-with-react-vite-docker">previous article</a>, we set up a development environment for a <a target="_blank" href="https://vite.dev/">Vite</a> + <a target="_blank" href="https://react.dev/">React</a> application using <a target="_blank" href="https://www.docker.com/">Docker</a>. While that setup was perfect for development, production environments have different requirements around security, performance, and reliability. Today, we'll explore how to create a production-ready Docker container for your frontend application application.</p>
<h2 id="heading-key-differences-between-development-and-production">Key Differences Between Development and Production</h2>
<p>Before diving into the implementation, let's understand why we need a different setup for production:</p>
<ol>
<li><p>Development containers prioritize fast feedback loops and hot reloading</p>
</li>
<li><p>Production containers need to be optimized for performance and security</p>
</li>
<li><p>Development exposes development servers, while production uses proper web servers</p>
</li>
<li><p>Production builds should be minimized and optimized</p>
</li>
</ol>
<h2 id="heading-understanding-our-production-dockerfile">Understanding Our Production Dockerfile</h2>
<p>Let’s start by looking at the complete production Dockerfile:</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Build stage</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">23</span>-alpine as build

<span class="hljs-comment"># Set working directory</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Copy package files</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package.json package-lock.json ./</span>

<span class="hljs-comment"># Install dependencies</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm ci</span>

<span class="hljs-comment"># Copy source code</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>

<span class="hljs-comment"># Build the app</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm run build</span>

<span class="hljs-comment"># Serve stage</span>
<span class="hljs-keyword">FROM</span> nginx:alpine

<span class="hljs-comment"># Create a non-root user to run nginx</span>
<span class="hljs-keyword">RUN</span><span class="bash"> adduser -D -H -u 1001 -s /sbin/nologin webuser</span>

<span class="hljs-comment"># Create app directory</span>
<span class="hljs-keyword">RUN</span><span class="bash"> mkdir -p /app/www</span>

<span class="hljs-comment"># Copy built assets from build stage</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=build /app/dist /app/www</span>

<span class="hljs-comment"># Copy nginx config template</span>
<span class="hljs-keyword">COPY</span><span class="bash"> nginx.conf /etc/nginx/templates/default.conf.template</span>

<span class="hljs-comment"># Set correct ownership and permissions</span>
<span class="hljs-keyword">RUN</span><span class="bash"> chown -R webuser:webuser /app/www &amp;&amp; \
    chmod -R 755 /app/www &amp;&amp; \
    <span class="hljs-comment"># Nginx needs to read and write to these directories</span></span>
    chown -R webuser:webuser /var/cache/nginx &amp;&amp; \
    chown -R webuser:webuser /var/log/nginx &amp;&amp; \
    chown -R webuser:webuser /etc/nginx/conf.d &amp;&amp; \
    touch /var/<span class="hljs-keyword">run</span><span class="bash">/nginx.pid &amp;&amp; \
    chown -R webuser:webuser /var/run/nginx.pid &amp;&amp; \
    chmod -R 777 /etc/nginx/conf.d</span>

<span class="hljs-comment"># Expose port (will be overridden by Render)</span>
<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">80</span>

<span class="hljs-comment"># Tell nginx's template processing which variables to replace</span>
<span class="hljs-keyword">ENV</span> NGINX_ENVSUBST_TEMPLATE_DIR=/etc/nginx/templates
<span class="hljs-keyword">ENV</span> NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template
<span class="hljs-keyword">ENV</span> NGINX_ENVSUBST_OUTPUT_DIR=/etc/nginx/conf.d
<span class="hljs-keyword">ENV</span> PORT=<span class="hljs-number">80</span>

<span class="hljs-comment"># Switch to non-root user</span>
<span class="hljs-keyword">USER</span> webuser

<span class="hljs-comment"># Start nginx</span>
<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"nginx"</span>, <span class="hljs-string">"-g"</span>, <span class="hljs-string">"daemon off;"</span>]</span>
</code></pre>
<p>Okay, so there’s a lot going on here. Let's break down our production Dockerfile step by step:</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Build stage</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">23</span>-alpine as build

<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package.json package-lock.json ./</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm ci</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm run build</span>
</code></pre>
<p>This first stage is our build environment. We're using a <a target="_blank" href="https://docs.docker.com/build/building/multi-stage/">multi-stage build</a> pattern, which helps keep our final image size small. The <code>node:23-alpine</code> base image provides the Node.js runtime we need for our build step, while keeping the image size minimal thanks to <a target="_blank" href="https://alpinelinux.org/">Alpine Linux</a>.</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Serve stage</span>
<span class="hljs-keyword">FROM</span> nginx:alpine

<span class="hljs-comment"># Create a non-root user to run nginx</span>
<span class="hljs-keyword">RUN</span><span class="bash"> adduser -D -H -u 1001 -s /sbin/nologin webuser</span>

<span class="hljs-comment"># Create app directory and set up nginx</span>
<span class="hljs-keyword">RUN</span><span class="bash"> mkdir -p /app/www</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=build /app/dist /app/www</span>
<span class="hljs-keyword">COPY</span><span class="bash"> nginx.conf /etc/nginx/templates/default.conf.template</span>
</code></pre>
<p>The second stage configures Nginx to serve our static files. We're creating a dedicated non-root user for security best practices. The article <a target="_blank" href="https://www.docker.com/blog/understanding-the-docker-user-instruction/"><strong>Understanding the Docker USER Instruction</strong></a> by Jay Schmidt does an excellent job of explaining why this is a good idea to secure your container. It boils down to this:</p>
<blockquote>
<p>By using a non-root user, even if the attacker manages to break out of the application running in the container, they will have limited permissions if the container is running as a non-root user.</p>
</blockquote>
<p>The next step is to copy our built assets from the previous stage using <code>--from=build</code>. By basing this stage on nginx and only copying the built assets, we discard the Node.js environment and it’s build tools. Following this process ensures you have a lighter image at the end.</p>
<h2 id="heading-security-considerations">Security Considerations</h2>
<p>Our production Dockerfile implements several security best practices. We started securing our app by starting with Alpine, because it reduces the attack surface. When we created a non-root user we limit the permissions when run as a non-root user. The multi-stage approach allows us to limit the attack surface even further by discarding tooling and dependencies we don’t need in our final image. The next step is to set the correct ownership and permissions on files:</p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Set correct ownership and permissions</span>
<span class="hljs-keyword">RUN</span><span class="bash"> chown -R webuser:webuser /app/www &amp;&amp; \
    chmod -R 755 /app/www &amp;&amp; \
    chown -R webuser:webuser /var/cache/nginx &amp;&amp; \
    chown -R webuser:webuser /var/<span class="hljs-built_in">log</span>/nginx &amp;&amp; \
    chown -R webuser:webuser /etc/nginx/conf.d &amp;&amp; \
    touch /var/run/nginx.pid &amp;&amp; \
    chown -R webuser:webuser /var/run/nginx.pid &amp;&amp; \
    chmod -R 777 /etc/nginx/conf.d</span>
</code></pre>
<h2 id="heading-environment-configuration">Environment Configuration</h2>
<p>Our Dockerfile uses environment variables to configure Nginx:</p>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">ENV</span> NGINX_ENVSUBST_TEMPLATE_DIR=/etc/nginx/templates
<span class="hljs-keyword">ENV</span> NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template
<span class="hljs-keyword">ENV</span> NGINX_ENVSUBST_OUTPUT_DIR=/etc/nginx/conf.d
<span class="hljs-keyword">ENV</span> PORT=<span class="hljs-number">80</span>
</code></pre>
<p>This setup allows for runtime configuration of Nginx through environment variables, making the container more flexible across different deployment environments. For example, you might have different configurations for a test and staging environments and having this flexibility allows us to configure these environments easily.</p>
<h2 id="heading-essential-nginx-configuration">Essential Nginx Configuration</h2>
<p>To properly serve a single-page application (SPA), we need an Nginx configuration that handles client-side routing. Let’s take a look at the final Nginx configuration:</p>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {
    <span class="hljs-attribute">listen</span> <span class="hljs-variable">${PORT}</span>;
    <span class="hljs-attribute">server_name</span> localhost;
    <span class="hljs-attribute">root</span> /app/www;

    <span class="hljs-comment"># Security headers</span>
    <span class="hljs-attribute">add_header</span> X-Frame-Options <span class="hljs-string">"SAMEORIGIN"</span>;
    <span class="hljs-attribute">add_header</span> X-XSS-Protection <span class="hljs-string">"1; mode=block"</span>;
    <span class="hljs-attribute">add_header</span> X-Content-Type-Options <span class="hljs-string">"nosniff"</span>;

    <span class="hljs-comment"># Compression</span>
    <span class="hljs-attribute">gzip</span> <span class="hljs-literal">on</span>;
    <span class="hljs-attribute">gzip_types</span> text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    <span class="hljs-attribute">location</span> / {
        <span class="hljs-attribute">try_files</span> <span class="hljs-variable">$uri</span> <span class="hljs-variable">$uri</span>/ /index.html;
        <span class="hljs-attribute">expires</span> -<span class="hljs-number">1</span>;
    }

    <span class="hljs-comment"># Cache static assets</span>
    <span class="hljs-attribute">location</span> /assets {
        <span class="hljs-attribute">expires</span> <span class="hljs-number">1y</span>;
        <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"public, no-transform"</span>;
    }
}
</code></pre>
<p>Let's break down our Nginx configuration piece by piece</p>
<pre><code class="lang-nginx"><span class="hljs-section">server</span> {
    <span class="hljs-attribute">listen</span> <span class="hljs-variable">${PORT}</span>;
    <span class="hljs-attribute">server_name</span> localhost;
    <span class="hljs-attribute">root</span> /app/www;
</code></pre>
<p>This opening block configures:</p>
<ul>
<li><p><code>listen ${PORT}</code>: Uses an environment variable for the port, making it configurable at runtime</p>
</li>
<li><p><code>server_name</code> <a target="_blank" href="http://localhost"><code>localhost</code></a>: Defines the server name (this can be changed for production domains)</p>
</li>
<li><p><code>root /app/www</code>: Points to our built React application files</p>
</li>
</ul>
<pre><code class="lang-nginx">    <span class="hljs-attribute">add_header</span> X-Frame-Options <span class="hljs-string">"SAMEORIGIN"</span>;
    <span class="hljs-attribute">add_header</span> X-XSS-Protection <span class="hljs-string">"1; mode=block"</span>;
    <span class="hljs-attribute">add_header</span> X-Content-Type-Options <span class="hljs-string">"nosniff"</span>;
</code></pre>
<p>These security headers protect against common web vulnerabilities:</p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options"><code>X-Frame-Options</code></a>: Prevents clickjacking attacks by controlling how the site can be embedded in iframes</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection"><code>X-XSS-Protection</code></a>: Enables browser-level XSS filtering</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options"><code>X-Content-Type-Options</code></a>: Prevents MIME-type sniffing attacks</p>
</li>
</ul>
<pre><code class="lang-nginx">    <span class="hljs-attribute">gzip</span> <span class="hljs-literal">on</span>;
    <span class="hljs-attribute">gzip_types</span> text/plain text/css application/json application/javascript 
               text/xml application/xml application/xml+rss text/javascript;
</code></pre>
<p>The <a target="_blank" href="https://docs.nginx.com/nginx/admin-guide/web-server/compression/">compression configuration</a>:</p>
<ul>
<li><p>Enables gzip compression to reduce bandwidth usage</p>
</li>
<li><p>Specifies which file types to compress</p>
</li>
<li><p>Improves load times for end users</p>
</li>
</ul>
<pre><code class="lang-nginx">    <span class="hljs-attribute">location</span> / {
        <span class="hljs-attribute">try_files</span> <span class="hljs-variable">$uri</span> <span class="hljs-variable">$uri</span>/ /index.html;
        <span class="hljs-attribute">expires</span> -<span class="hljs-number">1</span>;
    }
</code></pre>
<p>This block handles the React application's client-side routing:</p>
<ul>
<li><p><a target="_blank" href="https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files"><code>try_files</code></a>: Attempts to serve the requested file, then directory, falling back to index.html</p>
</li>
<li><p><a target="_blank" href="https://nginx.org/en/docs/http/ngx_http_headers_module.html#expires"><code>expires</code></a> <code>-1</code>: Prevents caching of the main index.html file to ensure users get the latest version</p>
</li>
</ul>
<pre><code class="lang-nginx">    <span class="hljs-attribute">location</span> /assets {
        <span class="hljs-attribute">expires</span> <span class="hljs-number">1y</span>;
        <span class="hljs-attribute">add_header</span> Cache-Control <span class="hljs-string">"public, no-transform"</span>;
    }
</code></pre>
<p>The static asset configuration:</p>
<ul>
<li><p>Aggressively caches assets for one year (Vite's build process includes content hashes in filenames)</p>
</li>
<li><p><a target="_blank" href="https://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header"><code>add_header</code></a>: Adds <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control">cache control headers</a> to optimize browser and CDN caching</p>
</li>
</ul>
<h2 id="heading-building-and-running-in-production">Building and Running in Production</h2>
<ol>
<li>Build the image:</li>
</ol>
<pre><code class="lang-bash">docker build -t my-react-app:prod .
</code></pre>
<ol start="2">
<li>Run the container:</li>
</ol>
<pre><code class="lang-bash">docker run -p 80:80 my-react-app:prod
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">🎆</div>
<div data-node-type="callout-text">Congrats! You now have a production ready image you can use for deployments! Source code for this guide is located here: <a target="_self" href="https://github.com/alvincrespo/pulsar-point"><strong>https://github.com/alvincrespo/pulsar-point</strong></a></div>
</div>

<h2 id="heading-conclusionhttpsgithubcomalvincrespopulsar-point"><a target="_blank" href="https://github.com/alvincrespo/pulsar-point">Conclusion</a></h2>
<p><a target="_blank" href="https://github.com/alvincrespo/pulsar-point">Creating a production-ready</a> Docker container involves more than just building and serving your application. Security, performance, and reliability considerations should guide your configuration decisions. This setup provides a solid foundation that you can further customize based on your specific requirements.</p>
<p>Remember to:</p>
<ul>
<li><p>Regularly update base images and dependencies</p>
</li>
<li><p>Monitor container resource usage</p>
</li>
<li><p>Implement proper logging</p>
</li>
<li><p>Set up automated security scanning</p>
</li>
<li><p>Test your container in a staging environment before production deployment</p>
</li>
</ul>
<p>With these practices in place, your Vite based React application will be well-positioned for production use.</p>
<h2 id="heading-next-time">Next time…</h2>
<p>In my follow up article(s), we’ll cover a few additional details we haven’t covered yet:</p>
<ul>
<li><p>SSL/TLS Configuration</p>
</li>
<li><p>CORS Headers (if needed)</p>
</li>
<li><p>Browser Caching Strategy</p>
</li>
<li><p>Error Pages</p>
</li>
<li><p>Health Checks and Monitoring</p>
</li>
<li><p>Production Optimization Tips</p>
</li>
<li><p>CI/CD Integration</p>
</li>
<li><p>Configuring CDN for Static Assets</p>
</li>
</ul>
<p>In the meantime, if you have any questions or need clarification, feel free to <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform"><strong>reach out</strong></a>!</p>
]]></content:encoded></item><item><title><![CDATA[Stakeholder Communications: A Framework]]></title><description><![CDATA[Learn how to reduce client escalations with a proven stakeholder communication framework. Discover practical tips for engineers to improve communication.]]></description><link>https://alvincrespo.hashnode.dev/stakeholder-communications-a-framework</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/stakeholder-communications-a-framework</guid><category><![CDATA[project management]]></category><category><![CDATA[stakeholders]]></category><category><![CDATA[communication]]></category><category><![CDATA[management]]></category><category><![CDATA[engineering-management]]></category><category><![CDATA[client management]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Tue, 21 Jan 2025 14:12:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/QtdCaV6tYH0/upload/c139b725a1a96303a184e9802c0cdcfc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Facilitating honest, authentic engagement, while not overwhelming stakeholders and contributors with information and updates (or starving them of information), is the best way to help individuals and groups appreciate project pitfalls, understand project progress, and, most importantly, emotionally connect with the initiative.</p>
<p>Karen A. Brown, Nancy Lea Hyer, and Richard Ettenson - <a target="_blank" href="https://learning.oreilly.com/library/view/protect-your-project/53863MIT58309/toc.html#chap-1">Protect Your Project From Escalating Doubts</a></p>
</blockquote>
<p>In the fast-paced world of software development, technical excellence alone isn't enough. I discovered this truth the hard way when stakeholder escalations became a recurring challenge. Despite delivering high-quality solutions that exceeded expectations, I was missing something crucial: effective stakeholder communication. Let’s start by understanding what stakeholder communication is.</p>
<h2 id="heading-understanding-effective-stakeholder-communication">Understanding Effective Stakeholder Communication</h2>
<p>Effective stakeholder communication is more than sending status updates – it's about creating clarity, alignment, and trust. In software engineering, it means delivering the right information to the right people at the right time, ensuring everyone understands both progress and impact. It’s very easy, as engineers, to focus on our technical contributions as the communication and assume people understand what we’re talking about - but thats not the case.</p>
<p>When we’re communicating our contributions we aim to achieve these key elements:</p>
<p><strong>Transparency</strong>: Share both successes and challenges openly.</p>
<p><strong>Consistency</strong>: Maintain regular communication rhythms.</p>
<p><strong>Relevance</strong>: Tailor messages to each stakeholder's needs and interests.</p>
<p><strong>Actionability</strong>: Provide clear context for decisions and next steps.</p>
<p>In my experience, a project is more likely to succeed if these objectives are met in any communication framework. Now, let me share an experience on why this became important to me and should be a reason for you to make a priority as a software engineer.</p>
<h2 id="heading-the-warning-signs">The Warning Signs</h2>
<p>The patterns were clear and becoming quite costly. Client concerns would suddenly escalate into emergency meetings with our CEO and CTO. These 45-minute sessions followed a predictable script: 25 minutes of stakeholder concerns, followed by 10 minutes of engineering status updates, and 10 minutes of Q&amp;A. The most telling part? After receiving project status information, stakeholders consistently left satisfied. We weren't facing technical issues – we had a communication gap.</p>
<p>At this point, I could have waited for project management to improve this. Perhaps, I could even voice this in a retro and make it an idea that the whole team could tackle. However, this just isn’t the way my brain works. I want my projects to be successful. I want my colleagues to be successful. I want <strong>everyone</strong> to win.</p>
<p>So I decided to take the reigns one day and build out a proposed framework.</p>
<h2 id="heading-building-the-framework">Building the Framework</h2>
<p>To bridge this gap, I developed a three-pillar communication framework:</p>
<h3 id="heading-1-customized-cadence">1. Customized Cadence</h3>
<p>The foundation starts with understanding each stakeholder's preferred rhythm. Through targeted conversations, we explore their work pressures, success metrics, and communication preferences. This insight helps with recommending and formalizing communication frequencies – daily, weekly, bi-weekly, or monthly. When consulting, you might add this to your contract. As a FTE, then this might be something you formalize on your own schedule.</p>
<h3 id="heading-2-tailored-content">2. Tailored Content</h3>
<p>Not all stakeholders speak the same language. Some want technical depth – pull request names and implementation details like "implementing Redux for state management." Others need business value translations – "integrated strategy for consistent user experience." The key is matching the message to the audience. As a consultant, this is something you bring up during the discovery phase. As a FTE, your best bet in understanding folks preferred communication style could be derived by your 1:1’s with them.</p>
<h3 id="heading-3-structured-documentation">3. Structured Documentation</h3>
<p>To make this sustainable, implementing internal systems for tracking and aggregating contributions is important - you do not want this to be a manual process. Using semantic pull requests, is a good way to standardize documentation of contributions. This makes composing stakeholder updates efficient and consistent, ensuring no critical updates fall through the cracks.</p>
<h2 id="heading-the-impact">The Impact</h2>
<p>When I was a consultant, I saw client escalations drop by 80% across all projects. More importantly, this led to an increase in the client retention rate and improved the client lifetime value metrics. The framework caught potential issues early, allowing us to adapt before they became problems.</p>
<p>When I saw these improvements, I made this a natural part of my communication method. I use this same framework today and although it changes, which is expected, it has led to drastic improvements in every opportunity I’ve had.</p>
<h2 id="heading-key-lessons">Key Lessons</h2>
<ol>
<li><p><strong>Proactive Communication Prevents Fires</strong>: Don't wait for end-of-project surveys to learn about communication gaps. Regular, structured updates build trust and visibility.</p>
</li>
<li><p><strong>One Size Doesn't Fit All</strong>: Take time to understand each stakeholder's needs and adapt your communication style accordingly. The same update can be technical or business-focused depending on the audience.</p>
</li>
<li><p><strong>Systematize for Scale</strong>: Good communication shouldn't depend on individual memory. Build systems that make it easy to track and share progress consistently.</p>
</li>
</ol>
<h2 id="heading-looking-forward">Looking Forward</h2>
<p>This framework isn't just about avoiding problems – it's about building lasting relationships. When stakeholders understand project progress and feel heard, they become partners in success rather than distant observers.</p>
<p>Remember: Technical excellence is your foundation, but clear communication is what builds trust and ensures your work gets the recognition it deserves.</p>
<hr />
<p>I hope you found this article helpful! If you have any questions or just want to chat, feel free to <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform"><strong>reach out</strong></a>!</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://www.ascertra.com/blog/pmi-study-reveals-poor-communication-leads-to-project-failure-one-third-of-the-time#:~:text=%E2%80%9CCompanies%20risk%20$135%20million%20for,%2C%20and%20within%20goals\).%E2%80%9D">Poor Communication Leads to Project Failure One Third of the Time</a></p>
<p><a target="_blank" href="https://www.projectmanagement.com/blog-post/18979/are-your-communication-habits-good-enough--#=">Are Your Communication Habits Good Enough?</a></p>
<p><a target="_blank" href="https://www.trueprojectinsight.com/blog/project-office/stakeholder-engagement-fearlessly">Stakeholder Engagement: Fearlessly Driving Project Success!</a></p>
<p><a target="_blank" href="https://learning.oreilly.com/library/view/protect-your-project/53863MIT58309/chapter001.html#h1-1">Protect Your Project From Escalating Doubts</a></p>
]]></content:encoded></item><item><title><![CDATA[Tool Breakdown: browser-actions/setup-chrome]]></title><description><![CDATA[Explore the core mechanics of browser-actions/setup-chrome Github action, including detailed bash and Node.js implementations for handling Chrome…]]></description><link>https://alvincrespo.hashnode.dev/tool-breakdown-browser-actionssetup-chrome</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/tool-breakdown-browser-actionssetup-chrome</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Bash]]></category><category><![CDATA[github-actions]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 20 Jan 2025 18:43:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/t5YUoHW6zRo/upload/9447e331545d6949be1145a4b7af613e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this new series, "Tool Breakdown", I'm walking through the core mechanics of the tools I use in various projects. I'm starting with a deep dive into a critical component of the <a target="_blank" href="https://github.com/browser-actions/setup-chrome"><code>browser-actions/setup-chrome</code></a> Github action. After encountering version mismatches between Google Chrome and Chromedriver in my CI pipeline, I investigated how this tool actually works. Understanding its mechanics is particularly valuable when debugging version conflicts or customizing the installation process for specific CI/CD requirements.</p>
<p>This article focuses on how the tool downloads, unpacks, and installs both Chrome and its driver. If you're looking for the complete code, you can find it in the accompanying repository here: <a target="_blank" href="https://github.com/alvincrespo/chrome-installer">https://github.com/alvincrespo/chrome-installer</a>.</p>
<h2 id="heading-a-simple-bash-script">A simple bash script</h2>
<p>Before we examine the Github action's implementation, let's look at a bash script that performs the same core operations. This script demonstrates the fundamental process for downloading and installing Google Chrome on Ubuntu/Debian-based systems.</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-built_in">cd</span> /tmp

<span class="hljs-comment"># Create tmp directory to hold .deb file</span>
mkdir -p /tmp/deb-LGbDgE &amp;&amp; <span class="hljs-built_in">cd</span> /tmp/deb-LGbDgE

<span class="hljs-comment"># Retrieve the stable .deb file and name it google-chrome.deb</span>
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb -O google-chrome.deb

<span class="hljs-comment"># Extract the contents of the .deb file</span>
<span class="hljs-comment"># ar is a utility specifically designed to work with Debian packages</span>
ar x google-chrome.deb

<span class="hljs-comment"># Create tmp directory to hold the extracted contents fo the data.tar.xz file</span>
mkdir -p /tmp/chrome-Epds2F &amp;&amp; <span class="hljs-built_in">cd</span> /tmp/chrome-Epds2F

<span class="hljs-comment"># Extracts the contents of data.tar.xz</span>
tar -xf /tmp/deb-LGbDgE/data.tar.xz --directory /tmp/chrome-Epds2F --strip-components 4 ./opt/google

<span class="hljs-comment"># verify chrome version</span>
./chrome --version
</code></pre>
<p>The installation process follows three main steps:</p>
<ol>
<li><p>Download the stable Google Chrome Debian package. This package contains everything needed for a complete Chrome installation.</p>
</li>
<li><p>Extract the data.tar.xz file from the downloaded Debian package using the <a target="_blank" href="https://manpages.debian.org/stretch/binutils/ar.1.en.html">ar</a> utility. The ar utility is specifically designed for handling .deb packages and maintaining their integrity during extraction.</p>
</li>
<li><p>Extract the Google Chrome executable from data.tar.xz. This final step places the Chrome binary in a location where it can be executed directly.</p>
</li>
</ol>
<p>Note that this script requires root or sudo privileges to perform system-level operations. The script also implements basic security practices by using randomly-named temporary directories and cleaning up after execution.</p>
<h2 id="heading-a-nodejsjavascript-script">A Node.js/JavaScript script</h2>
<p>The below script is a translation of the bash script above into JavaScript, following the same strategy used in <code>browser-actions/setup-chrome</code>. This script extracts the logic in <a target="_blank" href="https://github.com/browser-actions/setup-chrome/blob/master/src/channel_linux.ts#L35-L59">downloadBrowser</a> and <a target="_blank" href="https://github.com/browser-actions/setup-chrome/blob/master/src/channel_linux.ts#L61-L92">installBrowser</a> and combines them so you can easily follow the strategy of downloading, extracting and installing the Google Chrome browser.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// First, install required packages inside the container:</span>
<span class="hljs-comment">// npm init -y &amp;&amp; npm pkg set type=module</span>
<span class="hljs-comment">// npm install @actions/tool-cache @actions/exec</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Then, run the script using Node.js:</span>
<span class="hljs-comment">// node main.js</span>

<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> tc <span class="hljs-keyword">from</span> <span class="hljs-string">'@actions/tool-cache'</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> exec <span class="hljs-keyword">from</span> <span class="hljs-string">'@actions/exec'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs/promises'</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'path'</span>;
<span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> <span class="hljs-string">'os'</span>;

<span class="hljs-comment">// Step 1: Set up the URL for Chrome stable</span>
<span class="hljs-keyword">const</span> chromeUrl = <span class="hljs-string">'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb'</span>;

<span class="hljs-comment">// Step 2: Download Chrome</span>
<span class="hljs-keyword">const</span> archive = <span class="hljs-keyword">await</span> tc.downloadTool(chromeUrl);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Downloaded Chrome to:'</span>, archive);

<span class="hljs-comment">// Step 3: Create temporary directories</span>
<span class="hljs-keyword">const</span> tmpdir = <span class="hljs-keyword">await</span> fs.mkdtemp(path.join(os.tmpdir(), <span class="hljs-string">'deb-'</span>));
<span class="hljs-keyword">const</span> extdir = <span class="hljs-keyword">await</span> fs.mkdtemp(path.join(os.tmpdir(), <span class="hljs-string">'chrome-'</span>));
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Temporary directory:'</span>, tmpdir);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Extraction directory:'</span>, extdir);

<span class="hljs-comment">// Step 4: Extract the .deb package using ar</span>
<span class="hljs-keyword">await</span> exec.exec(<span class="hljs-string">'ar'</span>, [<span class="hljs-string">'x'</span>, archive], { <span class="hljs-attr">cwd</span>: tmpdir });

<span class="hljs-comment">// Step 5: List contents of tmpdir to see what ar extracted</span>
<span class="hljs-keyword">const</span> tmpContents = <span class="hljs-keyword">await</span> fs.readdir(tmpdir);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Contents after ar extraction:'</span>, tmpContents);

<span class="hljs-comment">// Step 6: Extract data.tar.xz using tar</span>
<span class="hljs-keyword">await</span> exec.exec(<span class="hljs-string">'tar'</span>, [
    <span class="hljs-string">'-xf'</span>,
    path.join(tmpdir, <span class="hljs-string">'data.tar.xz'</span>),
    <span class="hljs-string">'--directory'</span>,
    extdir,
    <span class="hljs-string">'--strip-components'</span>,
    <span class="hljs-string">'4'</span>,
    <span class="hljs-string">'./opt/google'</span>
]);

<span class="hljs-comment">// Step 7: List the extracted Chrome files</span>
<span class="hljs-keyword">const</span> chromeFiles = <span class="hljs-keyword">await</span> fs.readdir(extdir);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Extracted Chrome files:'</span>, chromeFiles);

<span class="hljs-comment">// Step 8: Remove the google-chrome symlink (if it exists)</span>
<span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> fs.unlink(path.join(extdir, <span class="hljs-string">'google-chrome'</span>));
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Removed google-chrome symlink'</span>);
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'No symlink to remove or error:'</span>, error.message);
}

<span class="hljs-comment">// Step 9: Examine the final structure</span>
<span class="hljs-keyword">const</span> finalFiles = <span class="hljs-keyword">await</span> fs.readdir(extdir);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Final Chrome installation files:'</span>, finalFiles);
</code></pre>
<p>Similar to our bash implementation, this Node.js script follows the same three core steps:</p>
<ol>
<li><p>Download the stable Debian package using the <code>@actions/tool-cache</code> utility</p>
</li>
<li><p>Extract the Debian package using the <code>ar</code> utility</p>
</li>
<li><p>Extract the Google Chrome executable from the resulting data.tar.xz file</p>
</li>
</ol>
<p>While this JavaScript implementation may appear more verbose than its bash counterpart, it offers significant advantages in terms of maintainability and extensibility. The <code>browser-actions/setup-chrome</code> action leverages these benefits to:</p>
<ul>
<li><p>Detect and adapt to different operating systems dynamically</p>
</li>
<li><p>Map dependencies based on the target operating system</p>
</li>
<li><p>Handle version resolution and compatibility checks</p>
</li>
<li><p>Provide detailed logging and error handling</p>
</li>
<li><p>Implement cleanup and security measures</p>
</li>
</ul>
<h2 id="heading-conclusion-and-followup">Conclusion and Followup</h2>
<p>In this article, we've explored the fundamental approach to downloading and installing Google Chrome through both bash and Node.js implementations. These examples demonstrate the core functionality that powers the <code>browser-actions/setup-chrome</code> GitHub action. By understanding these mechanics, you're better equipped to debug version conflicts and customize the installation process for your specific needs. This exploration also illustrates a broader principle in software development: examining source code not only resolves immediate technical challenges but often reveals valuable insights into software architecture and implementation patterns.</p>
<p>In the next article, we’ll go through and look at how the driver itself is also installed and verifying that the driver and chrome version match. Until then, If you have any questions or need clarification, feel free to <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform"><strong>reach out</strong></a>!</p>
]]></content:encoded></item><item><title><![CDATA[Getting Started with React + Vite + Docker]]></title><description><![CDATA[Learn to set up a React application with Vite and Docker.]]></description><link>https://alvincrespo.hashnode.dev/getting-started-with-react-vite-docker</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/getting-started-with-react-vite-docker</guid><category><![CDATA[React]]></category><category><![CDATA[vite]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Docker compose]]></category><category><![CDATA[local development]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Thu, 16 Jan 2025 02:35:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/OLRXnzXFBjo/upload/0e1ea2d39a548e2d5a35ca5631920bf1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’ve recently jumped back into React / Frontend development and was curious what tools the cool kids are using these days. At work, we use create react app, which seems to have been deprecated and isn’t even mentioned in the React docs anymore. So I did some research and found out about <a target="_blank" href="https://vite.dev/">Vite</a>, which is amazing because I really did not like <a target="_blank" href="https://webpack.js.org/">webpack</a> when I last worked with React. I decided to put together a getting started guide for you that sets up a containerized React application with Docker.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p><a target="_blank" href="https://nodejs.org/en">Node.js</a> (v23 or later)</p>
</li>
<li><p><a target="_blank" href="https://www.docker.com/products/docker-desktop/">Docker</a> and <a target="_blank" href="https://docs.docker.com/compose/">Docker Compose</a></p>
</li>
<li><p>Basic familiarity with <a target="_blank" href="https://react.dev/">React</a> and terminal commands</p>
</li>
</ul>
<hr />
<h2 id="heading-create-a-new-vite-project">Create a New Vite Project</h2>
<p>Ok, lets get started by creating a new Vite project. This is done by using <a target="_blank" href="https://docs.npmjs.com/cli/v10/commands/npm-init">npm create</a>.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a new Vite project</span>
npm create vite@latest my-react-app
<span class="hljs-built_in">cd</span> my-react-app

<span class="hljs-comment"># Install dependencies</span>
npm install
</code></pre>
<h2 id="heading-set-up-the-project-structure">Set Up the Project Structure</h2>
<p>To get Docker and Nginx configured to serve up the app within a container, we need to create the following files at the root of the project. In addition to this, we’re going to set up a local custom domain to access the app at <code>http://myreactapp</code>.</p>
<p><code>docker-compose.yml</code></p>
<pre><code class="lang-yaml"><span class="hljs-attr">services:</span>
  <span class="hljs-attr">app:</span>
    <span class="hljs-attr">build:</span>
      <span class="hljs-attr">context:</span> <span class="hljs-string">.</span>
      <span class="hljs-attr">dockerfile:</span> <span class="hljs-string">Dockerfile.dev</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"80:5173"</span>  <span class="hljs-comment"># Map container's 5173 to host's 80</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">.:/app</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">/app/node_modules</span>  <span class="hljs-comment"># Prevents local node_modules from mounting</span>
    <span class="hljs-attr">environment:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">NODE_ENV=development</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-attr">app_net:</span>
        <span class="hljs-attr">aliases:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-string">myreactapp</span>

<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">app_net:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">app_network</span>
</code></pre>
<p><code>Dockerfile.dev</code></p>
<pre><code class="lang-dockerfile"><span class="hljs-comment"># Use Node image for development</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">23</span>-alpine

<span class="hljs-comment"># Set working directory</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Copy package files</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package.json package-lock.json ./</span>

<span class="hljs-comment"># Install dependencies</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm ci</span>

<span class="hljs-comment"># Set host to allow external connections</span>
<span class="hljs-keyword">ENV</span> VITE_HOST=<span class="hljs-number">0.0</span>.<span class="hljs-number">0.0</span>

<span class="hljs-comment"># Expose Vite's port</span>
<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">5173</span>

<span class="hljs-comment"># Start development server</span>
<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"npm"</span>, <span class="hljs-string">"run"</span>, <span class="hljs-string">"dev"</span>, <span class="hljs-string">"--"</span>, <span class="hljs-string">"--host"</span>]</span>
</code></pre>
<p><a target="_blank" href="http://setup.sh"><code>setup.sh</code></a> (for local domain configuration)</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

<span class="hljs-comment"># Check if script is run with sudo</span>
<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$EUID</span>"</span> -ne 0 ]; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"Please run with sudo"</span>
  <span class="hljs-built_in">exit</span> 1
<span class="hljs-keyword">fi</span>

<span class="hljs-comment"># Add domain to /etc/hosts if not already present</span>
<span class="hljs-keyword">if</span> ! grep -q <span class="hljs-string">"myreactapp"</span> /etc/hosts; <span class="hljs-keyword">then</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"127.0.0.1 myreactapp"</span> &gt;&gt; /etc/hosts
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"Added myreactapp to /etc/hosts"</span>
<span class="hljs-keyword">else</span>
  <span class="hljs-built_in">echo</span> <span class="hljs-string">"myreactapp already in /etc/hosts"</span>
<span class="hljs-keyword">fi</span>

<span class="hljs-comment"># Flush DNS cache</span>
dscacheutil -flushcache
killall -HUP mDNSResponder
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Flushed DNS cache"</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"Setup complete! You can now access your app at http://myreactapp"</span>
</code></pre>
<p><code>package.json</code></p>
<p>To make things easy, let’s add the following scripts:</p>
<pre><code class="lang-json">    <span class="hljs-string">"docker:dev"</span>: <span class="hljs-string">"docker compose -f docker-compose.dev.yml up --build"</span>,
    <span class="hljs-string">"docker:dev:down"</span>: <span class="hljs-string">"docker compose -f docker-compose.dev.yml down"</span>,
    <span class="hljs-string">"docker:clean"</span>: <span class="hljs-string">"docker compose -f docker-compose.dev.yml down -v"</span>
</code></pre>
<h2 id="heading-configure-the-development-environment">Configure the Development Environment</h2>
<p>Make the setup script executable:</p>
<pre><code class="lang-bash">chmod +x setup.sh
</code></pre>
<p>Run the setup script to configure local domain (requires sudo):</p>
<pre><code class="lang-bash">sudo ./setup.sh
</code></pre>
<h2 id="heading-build-and-run-the-application">Build and Run the Application</h2>
<p>Build and start the Docker container:</p>
<pre><code class="lang-bash">npm run docker:dev
</code></pre>
<p>🎆🎆🎆 Congrats! You can access the application at <a target="_blank" href="http://myreactapp"><code>http://myreactapp</code></a>.</p>
<p>Source code for this guide is located here: <a target="_blank" href="https://github.com/alvincrespo/pulsar-point">https://github.com/alvincrespo/pulsar-point</a></p>
<hr />
<h2 id="heading-development-workflow">Development Workflow</h2>
<p>For local development without Docker:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<h2 id="heading-troubleshooting">Troubleshooting</h2>
<p>If the site doesn't load:</p>
<ul>
<li><p>Check if Docker containers are running: <code>docker compose ps</code></p>
</li>
<li><p>Verify local DNS: <code>ping myreactapp</code></p>
</li>
<li><p>Check Docker logs: <code>docker compose logs</code></p>
</li>
</ul>
<p>If changes aren't reflecting:</p>
<ul>
<li><p>Rebuild the Docker image: <code>docker compose up --build</code></p>
</li>
<li><p>Clear browser cache</p>
</li>
<li><p>Check if the correct files are being served: <code>docker exec -it container_name ls /app</code></p>
</li>
</ul>
<h2 id="heading-next-steps">Next Steps</h2>
<ul>
<li><p>Create the production level <code>Dockerfile</code> + <code>docker-compose.yml</code></p>
</li>
<li><p>Configure CI/CD pipelines</p>
</li>
<li><p>Add environment-specific configurations</p>
</li>
<li><p>Set up monitoring and logging</p>
</li>
<li><p>Implement container health checks</p>
</li>
<li><p>Security considerations for the production level <code>Dockerfile</code></p>
</li>
</ul>
<hr />
<p>Vite is an excellent frontend tooling solution when working with React. Combined with Docker's containerization you have a development environment that's both efficient and scalable. While this setup serves as an excellent starting point, it can be further customized to meet specific project requirements, whether that's implementing CI/CD pipelines, or integrating additional services. In a follow up article, I will sharing a preliminary guide putting together a production level image that addresses the above next steps.</p>
<p>If you have any questions or need clarification, feel free to <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform"><strong>reach out</strong></a>!</p>
]]></content:encoded></item><item><title><![CDATA[Resolve the "error while removing network" with Docker + Docker Compose]]></title><description><![CDATA[Create shared networks or combine compose files to resolve Docker's "active endpoints" errors.]]></description><link>https://alvincrespo.hashnode.dev/resolve-the-error-while-removing-network-with-docker-docker-compose</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/resolve-the-error-while-removing-network-with-docker-docker-compose</guid><category><![CDATA[Docker]]></category><category><![CDATA[Docker compose]]></category><category><![CDATA[docker-network]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Tue, 07 Jan 2025 01:54:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/52jRtc2S_VE/upload/9bad0270b9dd6ad61f36878df35ad2bb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>Docker version 4.37.1 or later</p>
</li>
<li><p>Basic familiarity with Docker Compose</p>
</li>
<li><p>Multiple Docker Compose files in your environment</p>
</li>
</ul>
<hr />
<h2 id="heading-the-problem">The Problem</h2>
<p>This week I ran into a fun issue at work having to do with setting up our local development environment. We have multiple microservices that need to be run and this is all managed via Ansible + Docker Compose files. The error that I ran into this week is below:</p>
<pre><code class="lang-plaintext">Error response from daemon: error while removing network: network docker_default id ABC has active endpoints
</code></pre>
<hr />
<p>Now, I’ve never run into this error before so this was completely new to me. My guess is something with Docker 4.37.1 made recreating the default network and explicit action. I’m not entirely 100% sure. I did some digging around and found the following that was super helpful:</p>
<blockquote>
<p>Compose now recreates containers when the volume or network configuration changes</p>
<p><a target="_blank" href="https://docs.docker.com/compose/releases/release-notes/#2320">https://docs.docker.com/compose/releases/release-notes/#2320</a></p>
</blockquote>
<h2 id="heading-understanding-docker-networks">Understanding Docker Networks</h2>
<p>This got me thinking…what are networks?! Yes, I never thought about it before - so I decided to educate myself and here was the key to my issue:</p>
<blockquote>
<p>By default Compose sets up a single <a target="_blank" href="https://docs.docker.com/reference/cli/docker/network/create/">network</a> for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by the service's name.</p>
<p><a target="_blank" href="https://docs.docker.com/compose/how-tos/networking/">https://docs.docker.com/compose/how-tos/networking/</a></p>
</blockquote>
<p>So, if this is the case then, wouldn’t running multiple compose files mean that the default network would be destroyed and created with the next compose call? It turns out, the answer is <em>yes</em>.</p>
<p>For example, lets consider the following process:</p>
<ul>
<li><p>Initialize Applications (init.yml)</p>
</li>
<li><p>Start Applications (apps.yml)</p>
</li>
</ul>
<p>Once we run <code>docker compose -f init.yml up</code> then the subsequent call to <code>docker compose -f apps.yml</code> could lead us to the active endpoints error. This was further confirmed by this comment in the following thread:</p>
<blockquote>
<p>Compose by default build your containers as if they are one network connected to each other</p>
<p>…</p>
<p>keep in mind that you could use external networks so compose don’t create new network but use a pre-built docker network</p>
<p><a target="_blank" href="https://forums.docker.com/t/is-it-possible-to-stop-docker-compose-from-creating-a-default-network/129805/4">https://forums.docker.com/t/is-it-possible-to-stop-docker-compose-from-creating-a-default-network/129805/4</a></p>
</blockquote>
<p>At this point, I had two options:</p>
<ol>
<li><p>Create a custom shared network across compose files, as per the recommendation in the above comment, or</p>
</li>
<li><p>Use one docker compose file, eliminating the need to run <code>docker compose</code> multiple times</p>
</li>
</ol>
<hr />
<h2 id="heading-solutions">Solutions</h2>
<h3 id="heading-option-1-combining-docker-compose-configurations">Option 1: Combining <code>docker compose</code> configurations</h3>
<p>It turns out, you can do this simply and is documented:</p>
<blockquote>
<h4 id="heading-specifying-multiple-compose-files"><em>Specifying multiple Compose files</em></h4>
<p>You can supply multiple <code>-f</code> configuration files. When you supply multiple files, Compose combines them into a single configuration. Compose builds the configuration in the order you supply the files. Subsequent files override and add to their predecessors.</p>
<p>For example, consider this comman<a target="_blank" href="https://docs.docker.com/reference/cli/docker/compose/#specifying-multiple-compose-files">d line:</a></p>
<pre><code class="lang-console">$ docker compose -f docker-compose.yml -f docker-compose.admin.yml run backup_db
</code></pre>
<p><a target="_blank" href="https://docs.docker.com/reference/cli/docker/compose/#specifying-multiple-compose-files">https://docs.docker.com/reference/cli/docker/compose/#specifying-multiple-compose-files</a></p>
</blockquote>
<p>Simplifying the ansible script to do this is possibly the easier option here as it would simplify things and solve the issue. However, because I was curious about docker networks, I decided to go with option #1.</p>
<h3 id="heading-option-2-custom-docker-compose-networks">Option 2: Custom <code>docker compose</code> networks</h3>
<p>This option solved my issue completely. Although I had to modify multiple docker compose configurations, it made which networks services were communicating under and explicit defined thing. Although having a default network is awesome, surfacing this to the team really did help in communicating how this stuff works.</p>
<p>The first thing you need to do is create the shared network:</p>
<pre><code class="lang-plaintext">docker network create shared_network
</code></pre>
<p>Creating this shared network is part of the ansible task for setting up the microservices, so it’s an automated step. I would recommend doing the same in your onboarding process, since you probably won’t remember this and it’ll make your team happier.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">❗</div>
<div data-node-type="callout-text">Please note the above are just examples, not the real docker compose configurations.</div>
</div>

<p><strong>init.yml</strong></p>
<pre><code class="lang-plaintext">services:
  app_init:
    image: myapp
    environment:
      STATE: init
    networks:
     - shared_network

networks:
  shared_network:
    external: true
</code></pre>
<p><strong>apps.yml</strong></p>
<pre><code class="lang-plaintext">services:
  app:
    image: myapp
    environment:
      STATE: application
    networks:
     - shared_network

networks:
  shared_network:
    external: true
</code></pre>
<p>If you want more information on how this works, please read Docker’s <a target="_blank" href="https://docs.docker.com/compose/how-tos/networking/#specify-custom-networks">Specify Custom Networks</a> documentation.</p>
<hr />
<h2 id="heading-troubleshooting-tips">Troubleshooting tips</h2>
<p>When dealing with Docker network issues, these commands can be helpful:</p>
<ol>
<li>List all networks:</li>
</ol>
<pre><code class="lang-plaintext">docker network ls
</code></pre>
<ol start="2">
<li>Inspect a specific network:</li>
</ol>
<pre><code class="lang-plaintext">docker network inspect shared_network
</code></pre>
<ol start="3">
<li>Check which containers are connected to a network:</li>
</ol>
<pre><code class="lang-plaintext">docker network inspect shared_network -f '{{range .Containers}}{{.Name}} {{end}}'
</code></pre>
<p>Common issues to watch for:</p>
<ul>
<li><p>Ensure the shared network exists before running compose files that reference it</p>
</li>
<li><p>Check for containers still connected to networks you're trying to remove</p>
</li>
<li><p>Verify network names match exactly across all compose files</p>
</li>
</ul>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Docker Compose creates a default network for each configuration by default. When running multiple compose files sequentially, this can lead to the "has active endpoints" error as compose tries to remove and recreate networks. You can resolve this either by:</p>
<ol>
<li><p>Creating a custom shared network and explicitly configuring all services to use it</p>
</li>
<li><p>Combining your compose files using the <code>-f</code> flag to create one shared default network</p>
</li>
</ol>
<p>While I opted for the custom network solution to make service communication more explicit, both approaches are valid depending on your specific needs.</p>
<p>Remember that the examples provided are simplified for illustration - adapt them to match your actual service configurations and requirements.</p>
<p>If you have any questions or need clarification, feel free to <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform">reach out</a>!</p>
]]></content:encoded></item><item><title><![CDATA[Rails 8's Lazy Route Loading + Devise]]></title><description><![CDATA[Learn about the implications of Rails 8's lazy route loading on Devise and how to address related issues for smooth development and testing.]]></description><link>https://alvincrespo.hashnode.dev/rails-8s-lazy-route-loading-devise</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/rails-8s-lazy-route-loading-devise</guid><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[devise]]></category><category><![CDATA[authentication]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Minitest]]></category><category><![CDATA[routing]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Sun, 05 Jan 2025 12:14:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cWpYKaJysU0/upload/ea2da66167be41576b3b81b02b61de48.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Rails 8.0 introduces a significant change to <a target="_blank" href="https://github.com/rails/rails/pull/52012">route loading behavior</a>, lazy loading routes by default in development and test. This change has implications for gems that interact with Rails' routing system, particularly Devise, which I personally use on a couple of side projects. The issue in particular that I was running into was an error when running my tests that looked like this:</p>
<pre><code class="lang-plaintext">Error:
UserTest#test_find_by_or_new_returns_a_new_user_if_no_user_is_found:
RuntimeError: Could not find a valid mapping for #&lt;User id: 986848094, email: "new.user@example.io", created_at: "2025-01-05 11:34:09.738943000 +0000", updated_at: "2025-01-05 11:34:09.738943000 +0000", role: "gardener", subscription_plan_id: nil, accepted_user_agreement: false, accepted_user_agreement_on: nil, stripe_id: nil, trial_started_at: nil, trial_ends_at: nil, deleted_at: nil, previous_email: nil, uuid: "a5826724-7509-416b-abd1-6e0a10302993"&gt;
    app/models/user.rb:83:in `find_by_or_new'
    test/models/user_test.rb:99:in `block in &lt;class:UserTest&gt;'
</code></pre>
<p>After doing some research, I found that this issue was related to the lazy loading route change in Rails 8. Let's check out how this change affects Devise and the potential impact it can have on any of your dependencies that hook into the Rails routing system.</p>
<h2 id="heading-understanding-the-problem">Understanding the Problem</h2>
<h3 id="heading-rails-8s-lazy-route-loading">Rails 8's Lazy Route Loading</h3>
<p>In Rails 8.0, routes are no longer eagerly loaded by default in development and test environments. This change aims to improve application boot time by loading routes only when they're needed. While this optimization is beneficial for most applications, it creates a challenge for dependencies that rely on route information being available during initialization.</p>
<h3 id="heading-devises-route-dependency">Devise's Route Dependency</h3>
<p>Devise builds its mappings during the route loading phase. These mappings are crucial for Devise's functionality as they contain information about authenticated resources (like User, Admin, etc.) and their corresponding routes. Previously, Devise stored these mappings in a class variable accessed through a simple <code>mattr_reader</code>:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># https://github.com/heartcombo/devise/blob/v4.9.4/lib/devise.rb</span>

<span class="hljs-comment"># Store scopes mappings.</span>
mattr_reader <span class="hljs-symbol">:mappings</span>
@@mappings = {}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">add_mapping</span><span class="hljs-params">(resource, options)</span></span>
  mapping = Devise::Mapping.new(resource, options)
  @@mappings[mapping.name] = mapping
  @@default_scope <span class="hljs-params">||</span>= mapping.name
  @@helpers.each { <span class="hljs-params">|h|</span> h.define_helpers(mapping) }
  mapping
<span class="hljs-keyword">end</span>
</code></pre>
<pre><code class="lang-ruby"><span class="hljs-comment"># https://github.com/heartcombo/devise/blob/v4.9.4/lib/devise/rails/routes.rb</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">devise_for</span><span class="hljs-params">(*resources)</span></span>
  <span class="hljs-comment"># ...</span>
  resources.each <span class="hljs-keyword">do</span> <span class="hljs-params">|resource|</span>
    mapping = Devise.add_mapping(resource, options)
</code></pre>
<p>This worked fine when routes were eagerly loaded, but with Rails 8's lazy loading, the mappings might not be available when they're first accessed.</p>
<h2 id="heading-the-solution">The Solution</h2>
<p>The fix involves modifying how Devise accesses its mappings. Instead of using a simple <code>mattr_reader</code>, the solution implements a custom getter method that ensures routes are loaded before accessing the mappings:</p>
<pre><code class="lang-ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">mappings</span></span>
  Rails.application.try(<span class="hljs-symbol">:reload_routes_unless_loaded</span>)
  @@mappings
<span class="hljs-keyword">end</span>
</code></pre>
<p><strong><em>Jerome Dalbert</em></strong> <em>at</em> <a target="_blank" href="https://github.com/heartcombo/devise/issues/5705"><em>https://github.com/heartcombo/devise/issues/5705</em></a></p>
<h3 id="heading-how-it-works">How It Works</h3>
<ol>
<li><p>When the <code>mappings</code> method is called, it first checks if routes need to be loaded</p>
</li>
<li><p><code>reload_routes_unless_loaded</code> is called on the Rails application, which:</p>
<ul>
<li><p>Checks if routes are already loaded</p>
</li>
<li><p>Loads them if necessary</p>
</li>
<li><p>Does nothing if they're already available</p>
</li>
</ul>
</li>
<li><p>Only then does it return the mappings stored in the class variable</p>
</li>
</ol>
<p>The <code>reload_routes_unless_loaded</code> method is new in Rails 8, introduced in <a target="_blank" href="https://github.com/rails/rails/pull/52012">https://github.com/rails/rails/pull/52012</a>:  </p>
<pre><code class="lang-ruby"><span class="hljs-comment"># railties/lib/rails/application.rb</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reload_routes_unless_loaded</span> <span class="hljs-comment"># :nodoc:</span></span>
  initialized? &amp;&amp; routes_reloader.execute_<span class="hljs-keyword">unless</span>_loaded
<span class="hljs-keyword">end</span>
</code></pre>
<p>Which in turn calls the <code>execute_unless_loaded</code> method on the <code>RoutesReloader</code> instance:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># railties/lib/rails/application/routes_reloader.rb</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">initialize</span></span>
  @paths      = []
  @route_sets = []
  @external_routes = []
  @eager_load = <span class="hljs-literal">false</span>
  @loaded = <span class="hljs-literal">false</span>
<span class="hljs-keyword">end</span>

<span class="hljs-comment"># ...</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">execute_unless_loaded</span></span>
  <span class="hljs-keyword">unless</span> @loaded
    execute
    ActiveSupport.run_load_hooks(<span class="hljs-symbol">:after_routes_loaded</span>, Rails.application)
    <span class="hljs-literal">true</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>This helps with application boot performance for applications with large amounts of routes that don’t need to be loaded all at once. The tradeoff here is that dependencies need to take into account this new strategy if they depend on rails routing being entirely loaded at the start.</p>
<h3 id="heading-implementation-details">Implementation Details</h3>
<p>By using <code>try(:reload_routes_unless_loaded)</code>, it:</p>
<ul>
<li><p>Maintains backward compatibility with older Rails versions that don't have this method</p>
</li>
<li><p>Handles the route loading only when necessary</p>
</li>
<li><p>Ensures that Devise's mappings are always available when needed</p>
</li>
</ul>
<h2 id="heading-short-term-solution">Short term solution</h2>
<p>For those who need an immediate solution while waiting for an official Devise update, a temporary fix can be implemented via an initializer:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># config/initializers/devise_rails8_patch.rb</span>

<span class="hljs-keyword">require</span> <span class="hljs-string">'devise'</span>
Devise <span class="hljs-comment"># make sure it's already loaded</span>

<span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">Devise</span></span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self</span>.<span class="hljs-title">mappings</span></span>
    Rails.application.try(<span class="hljs-symbol">:reload_routes_unless_loaded</span>)
    @@mappings
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p><strong><em>Jonathan Rochkind</em></strong> <em>at</em> <a target="_blank" href="https://github.com/heartcombo/devise/pull/5728#issuecomment-2539418211"><em>https://github.com/heartcombo/devise/pull/5728#issuecomment-2539418211</em></a></p>
<p>You can also implement this in your <code>test_helper.rb</code>, by adding this to the end of the file:</p>
<pre><code class="lang-ruby">ActiveSupport.on_load(<span class="hljs-symbol">:action_mailer</span>) <span class="hljs-keyword">do</span>
  Rails.application.reload_routes_<span class="hljs-keyword">unless</span>_loaded
<span class="hljs-keyword">end</span>
</code></pre>
<p><strong><em>Matt Brictson</em></strong> <em>at</em> <a target="_blank" href="https://github.com/heartcombo/devise/issues/5705#issuecomment-2442370072"><em>https://github.com/heartcombo/devise/issues/5705#issuecomment-2442370072</em></a></p>
<h2 id="heading-impact-and-best-practices">Impact and Best Practices</h2>
<p>This change highlights important considerations for gem maintainers and Rails developers:</p>
<ol>
<li><p><strong>Initialization Order</strong>: Be mindful of when your code needs access to routes and other Rails components</p>
</li>
<li><p><strong>Lazy Loading Compatibility</strong>: Consider how your gem or application might be affected by lazy loading in Rails 8</p>
</li>
<li><p><strong>Backward Compatibility</strong>: Ensure solutions work across different Rails versions when possible</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This change in Rails 8 directly impacts dependencies that rely on how routing works by eager loading routes when they are used. Devise 4.x currently has an issue with this strategy that is incompatible with Rails 8, specifically when running tests. The fix above has been merged in the main branch of Devise, but the short term solutions above help provide an immediate workaround.</p>
<p>It's a reminder of the importance of understanding the frameworks we build upon and their lifecycle events. For Rails developers upgrading to Rails 8.0, being aware of these changes and their implications will help ensure a smooth transition, especially when using gems that interact deeply with Rails' routing system.</p>
<hr />
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://github.com/rails/rails/pull/52012">Defer route drawing to the first request, or when url_helpers called. #52012 (retry)</a></p>
<p><a target="_blank" href="https://github.com/rails/rails/pull/51614">Defer route drawing to the first request, or when url_helpers called #51614 (reverted)</a></p>
<p><a target="_blank" href="https://github.com/heartcombo/devise/pull/5728">Make Devise.mappings work with lazy loaded routes.</a></p>
<p><a target="_blank" href="https://github.com/heartcombo/devise/issues/5694">Test helpers don't work on the Rails main branch (8.0.0.alpha)</a></p>
]]></content:encoded></item><item><title><![CDATA[How Test Coverage impacts Annual Recurring Revenue (ARR)]]></title><description><![CDATA[Effective test coverage reduces risk, enhances maintainability, and positively impacts Annual Recurring Revenue (ARR) for software systems.]]></description><link>https://alvincrespo.hashnode.dev/how-test-coverage-impacts-annual-recurring-revenue-arr</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/how-test-coverage-impacts-annual-recurring-revenue-arr</guid><category><![CDATA[Annual Recurring Revenue ]]></category><category><![CDATA[test coverage]]></category><category><![CDATA[engineering-management]]></category><category><![CDATA[Engineering metrics]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 02 Dec 2024 10:25:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/24j8h-9ME8o/upload/61ad831b71aa95d138330a0bd6cdf8b7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Over a 25-year life expectancy of a large software system, almost fifty cents out of every dollar will go to finding and fixing bugs.</p>
<p>UNDERSTANDING, FINDING AND FIXING DEFICIENCIES. Herb K. The Cost of Poor Software Quality in the US: A 2022 Report. <a target="_blank" href="https://www.it-cisq.org/wp-content/uploads/sites/6/2022/11/CPSQ-Report-Nov-22-2.pdf">Link</a>.</p>
</blockquote>
<h1 id="heading-introduction">Introduction</h1>
<p>It’s always been challenging to connect engineering metrics to business outcomes for me. After reading Iccha Sethi’s latest post, <a target="_blank" href="https://icchasethi.medium.com/tying-engineering-metrics-to-business-metrics-f4df7651e026">Tying Engineering Metrics to Business Metrics</a>, I decided to dig into these engineering metrics further, starting with test coverage. We all know that test coverage is important, we want our changes to have a positive impact on our customer - not the other way around. In this article, I attempt to explain the important relationship that exists between test coverage and <a target="_blank" href="https://www.wallstreetprep.com/knowledge/annual-recurring-revenue-arr/">Annual Recurring Revenue</a> (ARR).</p>
<hr />
<h1 id="heading-test-coverage">Test Coverage</h1>
<p>Test coverage encompasses the extent to which a codebase is automatically tested. This is a common technical measure that affects a number of upstream goals, but it mainly works in two ways: lowering support tickets and speeding up the release of new features. Let’s look at how that works in practice, beginning with quality assurance.</p>
<h2 id="heading-quality-assurance">Quality Assurance</h2>
<p>There are various types of test that cover different aspects of the code being committed, the most common types of tests include:</p>
<ul>
<li><p><em>Automated verification</em> of functionality that ensures consistent behavior across code changes, preventing regression-related support tickets.</p>
</li>
<li><p><em>Regression testing</em> that catches unintended side effects when modifying existing features, maintaining feature velocity during updates.</p>
</li>
<li><p>and finally, <em>Edge case detection,</em> which helps identify corner cases that might otherwise surface as customer-reported issues.</p>
</li>
</ul>
<h2 id="heading-testing-strategies">Testing Strategies</h2>
<p>There is no single right approach to testing, so having a multi-faceted strategy is important. Different types of tests and the requirements of those tests may be best suited for one strategy over another. Most teams have the following set of strategies:</p>
<p><strong>Automated Testing Pipeline</strong></p>
<p>Implementation of comprehensive automated testing suites that include unit tests, integration tests, and end-to-end tests running on every code change. This ensures continuous validation of functionality throughout the development lifecycle while enabling rapid feature deployment.</p>
<p><strong>Dedicated QA Team with Manual Testing</strong></p>
<p>A specialized team of people who perform systematic manual testing, exploratory testing, and user acceptance testing (UAT). They focus on user experience, edge cases, and real-world usage scenarios that might be difficult to automate, preventing future support tickets.</p>
<p><strong>Staged Deployments</strong></p>
<p>This strategy implements multiple environments (staging, alpha, beta, production) with a progressive testing plan for each stage. This typically includes canary releases and feature flag management to gradually roll out changes while monitoring for potential issues that could impact customer satisfaction.</p>
<h2 id="heading-primary-goals">Primary Goals</h2>
<p>Test coverage can only reduce support tickets and improve team velocity if it accomplishes two key objects; reducing risk and improving maintainability over time. Risk can never be truly eliminated with any strategy, so our goal here is to minimize it. Maintenance starts day one, any code written - is already in maintenance mode. Let’s look at some key research about these two topics real quick.</p>
<h3 id="heading-reduce-risk"><strong>Reduce Risk</strong></h3>
<p>Test coverage significantly reduces various risks that directly impact support ticket volume and feature velocity:</p>
<p><strong>Production Incidents</strong></p>
<p>Well-tested code dramatically reduces the likelihood of critical bugs making it to production, protecting against service disruptions that could impact customer satisfaction and retention. As noted in industry research:</p>
<blockquote>
<p>In 2022, <a target="_blank" href="https://www.it-cisq.org/the-cost-of-poor-quality-software-in-the-us-a-2022-report/">CISQ</a> reported that poor software quality costs the US $2.41 trillion, with <strong>operational failures</strong> amounting to <strong>$1.81 trillion</strong>.</p>
<p><em>Software incidents - what do they really cost you. Kaushik T.</em> <a target="_blank" href="https://spike.sh/blog/software-incidents-what-they-really-cost-you/#:~:text=Cost%20of%20Software%20Incidents,for%20U.S.%20financial%20services%20firms"><em>Link</em></a></p>
</blockquote>
<p><strong>Financial Risk</strong></p>
<p>Early bug detection through comprehensive testing prevents costly fixes and support escalations:</p>
<blockquote>
<p>The costs associated with data loss and downtime can be staggering for a small business. According to Framingham, Mass.-based consulting firm IDC, 80% of small businesses have experienced downtime at some point in the past, with costs ranging from $82,200 to $256,000 for a single event. What does this mean for IT? Every minute counts in a data recovery scenario – to the tune of $137 to $427 per minute.</p>
<p><em>Downtime costs small businesses up to $427 per minute. Mark B.</em> <a target="_blank" href="https://web.archive.org/web/20191111180818/https://www.carbonite.com/blog/article/2015/10/downtime-costs-small-businesses-up-to-$427-per-minute/"><em>Link</em></a></p>
</blockquote>
<p><strong>Reputation Risk</strong></p>
<p>Stable, reliable software builds trust with customers and protects the company's market reputation. This directly impacts ARR, as improving customer retention by just 5% could lead to profits of 25-95%. High test coverage helps maintain this stability while enabling rapid feature development.</p>
<p><strong>Security Risk</strong></p>
<p>Test coverage that includes security testing helps identify vulnerabilities before they can be exploited, protecting both the company and its customers. This is particularly crucial for products depending on open source software (OSS), where regular dependency updates require confident testing to maintain both security and feature velocity.</p>
<h3 id="heading-maintainability"><strong>Maintainability</strong></h3>
<p>Well-tested code is easier to refactor and extend, facilitating long-term maintenance. Changing requirements and sudden pivots are expected in software development and testing ensures that the engineering team can shift quickly when needed. When risks are minimized and confidence is high, the team can respond quickly to the changing needs of the business.</p>
<blockquote>
<p>Over a 25-year life expectancy of a large software system, almost fifty cents out of every dollar will go to finding and fixing bugs.</p>
<p><em>Herb K. (2022). The Cost of Poor Software Quality in the US: A 2022 Report.</em> <a target="_blank" href="https://www.it-cisq.org/wp-content/uploads/sites/6/2022/11/CPSQ-Report-Nov-22-2.pdf"><em>Link</em></a></p>
</blockquote>
<p>High maintainability through test coverage enables teams to:</p>
<ul>
<li><p>Deploy changes with <em>greater confidence</em>, reducing time spent on support issues</p>
</li>
<li><p>Implement new features more <em>rapidly</em> without fear of breaking existing functionality</p>
</li>
<li><p><em>Respond</em> quickly to market demands while maintaining system stability</p>
</li>
<li><p>Refactor and modernize code without introducing new support tickets</p>
</li>
</ul>
<p>This improved maintainability directly supports both reduced support ticket volume and increased feature velocity, creating a positive feedback loop that enhances ARR growth potential.</p>
<hr />
<h1 id="heading-annual-recurring-revenue-arr">Annual Recurring Revenue (ARR)</h1>
<p>Annual Recurring Revenue (ARR) is a critical metric for SaaS businesses, representing the normalized annual value of subscription contracts or a multi-year contract. The relationship between test coverage and ARR flows through several interconnected pathways, primarily through its impact on support tickets and feature velocity.</p>
<h2 id="heading-support-tickets-impact-on-arr">Support Tickets Impact on ARR</h2>
<p>Support tickets are a leading indicator of customer satisfaction. If there are less bug-related support tickets, technical issues will have faster resolution times. In turn, this will lead to a stable product that has higher customer satisfaction.</p>
<p>When customers are confident in the product they're more likely to 1) renew their subscriptions, 2) expand their usage of the product and 3) recommend the product to others (reducing the customer acquisition costs).</p>
<p>Service Level Agreements (SLAs) are also directly tied to support tickets. SLAs include a contractual obligation to resolve issues and also include financial penalties:</p>
<ul>
<li><p>Missed response time SLAs can trigger penalty clauses, directly reducing ARR</p>
</li>
<li><p>Repeated SLA breaches may activate contract termination clauses, leading to customer loss</p>
</li>
<li><p>High ticket volumes can overwhelm support teams, causing cascading SLA failures across multiple customers</p>
</li>
</ul>
<p>Maintaining high test coverage and reducing support tickets ensures companies can better meet their SLA commitments, avoiding these negative financial impacts and protecting their ARR.</p>
<h2 id="heading-feature-velocitys-connection-to-arr">Feature Velocity's Connection to ARR</h2>
<p>Feature velocity, the speed at which new features can be reliably delivered, directly influences a company's ability to meet evolving market demands, stay competitive, capture additional revenue and expand into adjacent market segments. A culture of testing, focused on a high test coverage goals, can accomplish the following:</p>
<ol>
<li><p>Reducing regression bugs that slow down development</p>
</li>
<li><p>Enabling confident refactoring to support new features</p>
</li>
<li><p>Allowing parallel development streams without quality degradation</p>
</li>
<li><p>Decreasing time spent on bug fixes vs. new development</p>
</li>
</ol>
<p>Teams that can ship features quickly and confidently tend to support their companies ARR growth. If you can get valuable features to market faster, you're giving yourself a real edge. Faster time-to-market features that generate increases customer satisfaction as the product is innovating and continuously providing value.</p>
<h2 id="heading-quantifying-the-arr-impact">Quantifying the ARR Impact</h2>
<p>In the context of this article, test coverage ensures that systematically reduce support tickets while improving feature velocity. If we achieve these goals, the combined effect will have a substantial positive impact on ARR. This is accomplished with direct cost savings and shifting resources to revenue growth opportunities.</p>
<h3 id="heading-direct-cost-savings"><strong>Direct Cost Savings</strong></h3>
<p>When support tickets are reduced, support costs are lowered. The support team can focus on other valuable areas that improve the customer experience. Engineering costs are also significantly reduced as less time is spend on bug fixes. A support team that elevates the customer experience + an engineering team that is laser focused on revenue growth opportunities equates to decreased customer churn-related revenue loss as the product will continuously push more valuable experiences.</p>
<h3 id="heading-revenue-growth-opportunities"><strong>Revenue Growth Opportunities</strong></h3>
<p>An engineering team focused on revenue-generating features leads to higher customer satisfaction rates as usage of the application continues to expand. This places the company in a very competitive position in the market as it continues to deliver value while maintaining existing critical systems. Happy customers will improve referral rates and customer acquisition costs should go down.</p>
<p>This creates a positive feedback loop - better quality leads to happier customers, which drives growth, which lets you invest more in quality.</p>
<h3 id="heading-an-example"><strong>An Example</strong></h3>
<p><strong>Assumption:</strong> We have decided to focus exclusively on test coverage and two new features. We want support tickets to decrease so our support team can focus on working closely with customers to improve our customer experience. We also want our team velocity to improve by building trust in the existing systems so we can expand on them.</p>
<p><strong>Goal</strong>:</p>
<p>20-35% Lower Customer Churn Rates</p>
<p><strong>Base:</strong> 1000 customers * $1000/year = $1,000,000 base ARR</p>
<p><strong>Strategy:</strong></p>
<ul>
<li><p>Fewer frustrating bugs that might cause customers to leave</p>
</li>
<li><p>Faster resolution of issues when they do occur</p>
</li>
</ul>
<p><strong>Breakdown:</strong></p>
<p>If a company has a 15% annual churn rate:</p>
<ul>
<li><p>15% churn = 150 customers lost = $150,000 lost</p>
</li>
<li><p>25% reduction in churn = new churn of 11.25% (15% * 0.75)</p>
</li>
<li><p>New customers lost: 1000 x 11.25% = 113 customers</p>
</li>
<li><p>New loss: 113 * 1000 = $113,000</p>
</li>
<li><p>Savings: $150,000 - $113,000 = $37,000</p>
</li>
</ul>
<p><strong>Goal:</strong></p>
<p>15-25% Higher Expansion Revenue</p>
<p><strong>Strategy:</strong></p>
<ul>
<li><p>Customers trust the product more due to reliability</p>
</li>
<li><p>Sales teams can focus on upselling rather than handling complaints</p>
</li>
<li><p>Customers are more likely to adopt new features when core functionality is stable</p>
</li>
</ul>
<p><strong>Breakdown:</strong></p>
<p>If average customer expansion is $200/year across 1000 customers:</p>
<ul>
<li><p>Current expansion: 1000 * $200 = $200,000</p>
</li>
<li><p>20% improvement: $200,000 * 1.2 = $240,000</p>
</li>
<li><p>Additional ARR: $240,000 - $200,000 = $40,000</p>
</li>
</ul>
<p><strong>Goal:</strong></p>
<p>10-20% Improvement in New Customer Acquisition through Referrals</p>
<p><strong>Strategy:</strong></p>
<ul>
<li><p>They see regular feature improvements</p>
</li>
<li><p>Word-of-mouth about product reliability spreads</p>
</li>
</ul>
<p><strong>Breakdown:</strong></p>
<p>If 20% of new customers (100/year) come from referrals at $1000/year each:</p>
<ul>
<li><p>Current referral revenue: 100 * $1,000 = $100,000</p>
</li>
<li><p>With 15% improvement: 115 * $1,000 = $115,000</p>
</li>
<li><p>Additional ARR: $115,000 - $100,000 = $15,000</p>
</li>
</ul>
<p><strong>Combined Impact:</strong></p>
<p>If base ARR is $1,000,000:</p>
<ul>
<li><p>Reduced churn: +$37,000</p>
</li>
<li><p>Increased expansion: +$40,000</p>
</li>
<li><p>More referrals: +$15,000</p>
</li>
<li><p>Total ARR impact: +$92,000 (9.2% improvement)</p>
</li>
</ul>
<p>These numbers are particularly powerful because they compound over time:</p>
<ul>
<li><p>Year 1: $92,000 additional ARR</p>
</li>
<li><p>Year 2: Previous $92,000 + new improvements</p>
</li>
<li><p>Year 3+: Continued compounding effect</p>
</li>
</ul>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>Explaining why test coverage matters to folks outside of engineering can be tricky. But when you break down how it impacts the business, the story becomes pretty clear: better test coverage means you can ship features faster and more reliably, which keeps customers happy and helps grow your revenue.</p>
<p>When your team can confidently push code to production and your services stay stable, you're not just making engineers' lives easier. You're building trust with your customers, keeping them around longer, and making them more likely to recommend your product to others. This is especially crucial if you're running a subscription-based business where every churned customer directly hits your bottom line.</p>
<p>I hope this breakdown helps you make a stronger case for investing in test coverage. Whether you're talking to your product team, executives, or other stakeholders, you now have concrete examples of how technical quality translates to business success. Feel free to use these examples and references in your next conversation about why test coverage deserves attention and resources.</p>
<p>In the meantime, let me know what you think. You can catch me on <a target="_blank" href="https://bsky.app/profile/alvincrespo.bsky.social">Bluesky</a> or reach out via this <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform">Google Form</a>. Have a great day!</p>
<hr />
<h1 id="heading-references">References</h1>
<ol>
<li><p>Sethi, I. (2020). <em>Tying Engineering Metrics to Business Metrics</em>. Medium. <a target="_blank" href="https://icchasethi.medium.com/tying-engineering-metrics-to-business-metrics-f4df7651e026">Link</a></p>
</li>
<li><p>Humble, J., &amp; Farley, D. (2010). <em>Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation</em>. Addison-Wesley.</p>
</li>
<li><p><a target="_blank" href="https://bsky.app/profile/alvincrespo.bsky.social">Jones,</a> C. (2017). <em>Software Quality</em><a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform"><em>: Analysis</em></a> <em>and Guidelines for Success</em>. McGraw-Hill Education.</p>
</li>
<li><p>Consortium for IT Software Quality (CISQ). (2020). <em>The Cost of Poor Software Quality in the US: A 2020 Report</em>. <a target="_blank" href="https://www.it-cisq.org/the-cost-of-poor-software-quality-in-the-us-a-2020-report/">Link</a></p>
</li>
<li><p>Federico, T. (2019). <em>Why Software Testing is Necessary for Delivering Superior Customer Experiences.</em> DZone*.* <a target="_blank" href="https://web.archive.org/web/20191203131404/https://dzone.com/articles/why-software-testing-is-necessary-for-delivering-s">Link</a></p>
</li>
<li><p>Boehm, B., &amp; Basili, V. R. (2001). Software defect reduction top 10 lis<a target="_blank" href="https://bsky.app/profile/alvincrespo.bsky.social">t. <em>IEEE</em></a> <em>Computer</em>, 34(1), 135-137. <a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform">doi:10.1109</a><a target="_blank" href="https://doi.org/10.1109/2.962984">/2.962984</a></p>
</li>
<li><p><em>UNDERSTANDING, FINDING AND FIXING DEFICIENCIES. Herb K. The Cost of Poor Software Quality in the US: A 2022 Report.</em> <a target="_blank" href="https://www.it-cisq.org/wp-content/uploads/sites/6/2022/11/CPSQ-Report-Nov-22-2.pdf"><em>Link</em></a><em>.</em></p>
</li>
<li><p>Marius. K. (2021). <em>Customer Acquisition vs. Customer Retention: What Data Says?.</em> <a target="_blank" href="https://www.markinblog.com/customer-loyalty-retention-statistics/">Link</a></p>
</li>
<li><p>Kaushik T. (2024). Software incidents - what do they really cost you. <a target="_blank" href="https://spike.sh/blog/software-incidents-what-they-really-cost-you/#:~:text=Cost%20of%20Software%20Incidents,for%20U.S.%20financial%20services%20firms">Link</a></p>
</li>
<li><p>Mark B. (2018). Downtime costs smal<a target="_blank" href="https://bsky.app/profile/alvincrespo.bsky.social">l busin</a>esses up to $427 per minute<a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform">. Link</a></p>
</li>
<li><p><a target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSd3FJbsjj8kqY3HF2HixnwsNQ2VyQYQNomasGQBIq0r6FAMJQ/viewform">S</a>tep-by-Step Guide to Understanding Annual Recurring Revenue. <a target="_blank" href="https://www.wallstreetprep.com/knowledge/annual-recurring-revenue-arr/">Link</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Enhancing a Scalable Export in Ruby on Rails: Lessons Learned]]></title><description><![CDATA[Learn how to tackle concurrency issues in Ruby on Rails export systems using file locking and commit strategies for reliable data handling]]></description><link>https://alvincrespo.hashnode.dev/enhancing-a-scalable-export-in-ruby-on-rails-lessons-learned</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/enhancing-a-scalable-export-in-ruby-on-rails-lessons-learned</guid><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Ruby]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[background jobs]]></category><category><![CDATA[workers]]></category><category><![CDATA[zip]]></category><category><![CDATA[lock files]]></category><category><![CDATA[exports]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Fri, 18 Oct 2024 10:00:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729176649932/2541f3fc-eb32-4bd9-adef-12c3807934e5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my <a target="_blank" href="https://alvincrespo.hashnode.dev/build-a-scalable-export-in-ruby-on-rails">last blog post</a>, I walked you through the implementation of a scalable export system in a Ruby on Rails application. Since then, I’ve encountered a few challenges, particularly around concurrency, file locking, and ensuring that data exports are reliably processed when <strong>multiple jobs need to write to the same ZIP file</strong>. In this post, I'll dive deeper into those challenges and share the solutions I found to make the export system even more robust.</p>
<h2 id="heading-the-challenge-concurrent-jobs-and-zip-files"><strong>The Challenge: Concurrent Jobs and ZIP Files</strong></h2>
<p>When you're building a feature to export user data, especially in large applications, handling concurrency is key. Each user might have various types of data to export, such as notes, files, or other content, and all of this needs to be bundled into a single ZIP file.</p>
<p>In my case, multiple background jobs (<code>ExportUserUploadedContentJob</code> and <code>ExportUserNotesJob</code>) were responsible for fetching the data and adding it to the same ZIP file. Initially, everything seemed straightforward—each job would write its content to the ZIP file, and a cleanup job would handle the rest. However, this caused problems when jobs tried to access the ZIP file simultaneously, leading to incomplete data in the final file. After debugging, I realized the following issues:</p>
<ul>
<li><p><strong>Race conditions</strong>: Multiple jobs trying to write to the same ZIP file concurrently.</p>
</li>
<li><p><strong>Incomplete writes</strong>: Some jobs didn’t finish writing before another job tried to access the file, resulting in missing content.</p>
</li>
<li><p><strong>File not properly closed</strong>: The ZIP file wasn’t always flushed and saved to disk after every write.</p>
</li>
</ul>
<p>To address these issues, I implemented a series of improvements, starting with how we manage exports in the database.</p>
<hr />
<h2 id="heading-managing-exports-migration-and-model"><strong>Managing Exports: Migration and Model</strong></h2>
<p>Making an <code>Export</code> model would help me to monitor the status of several export jobs, control task completion, and track statistics like file size and time elapsed, allowing me to track the process of every export.</p>
<h3 id="heading-migration-for-the-exports-table"><strong>Migration for the</strong> <code>exports</code> Table</h3>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CreateExports</span> &lt; ActiveRecord::Migration[7.0]</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">change</span></span>
    create_table <span class="hljs-symbol">:exports</span> <span class="hljs-keyword">do</span> <span class="hljs-params">|t|</span>
      t.references <span class="hljs-symbol">:user</span>, <span class="hljs-symbol">null:</span> <span class="hljs-literal">false</span>, <span class="hljs-symbol">foreign_key:</span> <span class="hljs-literal">true</span>
      t.string <span class="hljs-symbol">:prefix</span>, <span class="hljs-symbol">null:</span> <span class="hljs-literal">false</span>
      t.integer <span class="hljs-symbol">:jobs_completed</span>, <span class="hljs-symbol">default:</span> <span class="hljs-number">0</span>
      t.integer <span class="hljs-symbol">:total_jobs</span>, <span class="hljs-symbol">default:</span> <span class="hljs-number">2</span>  <span class="hljs-comment"># Adjust for the number of jobs you plan to run</span>
      t.datetime <span class="hljs-symbol">:started_at</span>
      t.datetime <span class="hljs-symbol">:completed_at</span>
      t.integer <span class="hljs-symbol">:file_size</span>, <span class="hljs-symbol">default:</span> <span class="hljs-number">0</span>
      t.timestamps
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-export-model"><strong>Export Model</strong></h3>
<p>The <code>Export</code> model tracks the start and completion of jobs, how many jobs have completed, and other metrics like the size of the final ZIP file. This allows us to track the state of an export, making it easy to determine when all jobs are finished and trigger the final cleanup and upload process.</p>
<p>Here’s the key structure for managing export state:</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Export</span> &lt; ApplicationRecord</span>
  belongs_to <span class="hljs-symbol">:user</span>

  <span class="hljs-comment"># Mark the start of the export</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mark_started</span></span>
    update!(<span class="hljs-symbol">started_at:</span> Time.current)
  <span class="hljs-keyword">end</span>

  <span class="hljs-comment"># Mark the completion and calculate elapsed time</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mark_completed</span><span class="hljs-params">(zip_file_path)</span></span>
    update!(
      <span class="hljs-symbol">completed_at:</span> Time.current,
      <span class="hljs-symbol">file_size:</span> File.size(zip_file_path)  <span class="hljs-comment"># Get file size in bytes</span>
    )
  <span class="hljs-keyword">end</span>

  <span class="hljs-comment"># Increment job completion and check if all jobs are finished</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mark_job_complete</span></span>
    increment!(<span class="hljs-symbol">:jobs_completed</span>)
    jobs_completed == total_jobs
  <span class="hljs-keyword">end</span>

  <span class="hljs-comment"># Calculate the total time taken for the export</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">time_elapsed</span></span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span> <span class="hljs-keyword">unless</span> completed_at &amp;&amp; started_at
    completed_at - started_at
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-changes-to-the-exportsjob-job-coordination"><strong>Changes to the</strong> <code>ExportsJob</code>: Job Coordination</h3>
<p>The <code>ExportsJob</code> is responsible for coordinating the different export jobs that will append data to the same ZIP file. Before launching the jobs, we make sure the ZIP file is created and ready for use.</p>
<pre><code class="lang-ruby"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExportsJob</span> &lt; ApplicationJob</span>
  queue_as <span class="hljs-symbol">:default</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">perform</span><span class="hljs-params">(user_id)</span></span>
    prefix = SecureRandom.hex(<span class="hljs-number">8</span>)
    zip_file_path = Rails.root.join(<span class="hljs-string">"tmp"</span>, <span class="hljs-string">"<span class="hljs-subst">#{prefix}</span>_export.zip"</span>).to_s

    <span class="hljs-comment"># Create an empty ZIP file before jobs start</span>
    Zip::File.open(zip_file_path, Zip::File::CREATE) {}

    <span class="hljs-comment"># Create a new export tracking record and mark the start</span>
    export = Export.create!(<span class="hljs-symbol">user_id:</span> user_id, <span class="hljs-symbol">prefix:</span> prefix, <span class="hljs-symbol">total_jobs:</span> <span class="hljs-number">2</span>)
    export.mark_started

    <span class="hljs-comment"># Launch export jobs concurrently</span>
    ExportUserUploadedContentJob.perform_later(user_id, zip_file_path, export.id)
    ExportUserNotesJob.perform_later(user_id, zip_file_path, export.id)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<ul>
<li><p><strong>Create the ZIP file</strong>: Ensures that an empty ZIP file is created before any background job tries to write to it. This prevents errors where the file doesn’t exist when jobs attempt to append data.</p>
</li>
<li><p><strong>Job coordination</strong>: Each job is launched concurrently, but they will use file locks to ensure they don’t interfere with each other.</p>
</li>
</ul>
<hr />
<h2 id="heading-file-locking-and-proper-commit-handling"><strong>File Locking and Proper Commit Handling</strong></h2>
<h3 id="heading-file-locking-for-safe-concurrent-access"><strong>File Locking for Safe Concurrent Access</strong></h3>
<p>To solve these issues, I implemented a file locking mechanism using Ruby’s <a target="_blank" href="https://ruby-doc.org/3.3.4/File.html#method-i-flock"><code>flock</code></a> method. This ensures that only one job can write to the ZIP file at a time. If another job tries to access the file while it's locked, it waits or retries until the lock is released.</p>
<p>Here’s how the file locking looks in practice:</p>
<pre><code class="lang-ruby">File.open(zip_file_path, <span class="hljs-string">'r+'</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|file|</span>
  <span class="hljs-keyword">if</span> file.flock(File::LOCK_EX <span class="hljs-params">| File::LOCK_NB)
    # Perform ZIP operations...
    file.flock(File::LOCK_UN)  # Release the lock
  <span class="hljs-keyword">else</span>
    # Retry <span class="hljs-keyword">if</span> lock is unavailable
    retry_job(wait: 5.seconds)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span></span>
</code></pre>
<p>This guarantees exclusive access to the file during write operations and prevents race conditions.</p>
<h3 id="heading-ensuring-proper-commits-with-zipfilecommit"><strong>Ensuring Proper Commits with</strong> <code>Zip::File#commit</code></h3>
<p>Even with the locking mechanism in place, I noticed that some data was still missing from the final ZIP file. The reason? The ZIP file wasn’t always being flushed to disk after each write. To resolve this, I added the <a target="_blank" href="https://www.rubydoc.info/github/rubyzip/rubyzip/Zip/File#commit-instance_method"><code>zipfile.commit</code></a> method at the end of each job to ensure all changes were saved:</p>
<pre><code class="lang-ruby">Zip::File.open(zip_file_path, Zip::File::CREATE) <span class="hljs-keyword">do</span> <span class="hljs-params">|zipfile|</span>
  <span class="hljs-comment"># Write content to the ZIP file...</span>
  zipfile.commit  <span class="hljs-comment"># Ensure the file is flushed and saved</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>This simple change ensures that each job commits its work before releasing the lock, preventing data loss.</p>
<p>Here is a full example of file locking and commiting would look like in a job:</p>
<pre><code class="lang-ruby"><span class="hljs-keyword">require</span> <span class="hljs-string">"zip"</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">"csv"</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExportUserNotesJob</span> &lt; ApplicationJob</span>
  queue_as <span class="hljs-symbol">:default</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">perform</span><span class="hljs-params">(user_id, zip_file_path, export_id)</span></span>
    user = User.find(user_id)

    File.open(zip_file_path, <span class="hljs-string">"r+"</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|file|</span>
      Rails.logger.info <span class="hljs-string">"<span class="hljs-subst">#{<span class="hljs-keyword">self</span>.<span class="hljs-keyword">class</span>.name}</span> writing to <span class="hljs-subst">#{zip_file_path}</span>"</span>
      <span class="hljs-keyword">if</span> file.flock(File::LOCK_EX <span class="hljs-params">| File::LOCK_NB)
        Rails.logger.info "Lock acquired by #{<span class="hljs-keyword">self</span>.<span class="hljs-keyword">class</span>.name} <span class="hljs-keyword">for</span> #{zip_file_path}"

        csv_content = CSV.generate(headers: <span class="hljs-literal">true</span>) <span class="hljs-keyword">do</span> |</span>csv<span class="hljs-params">|
          csv &lt;&lt; [ "Title", "Body" ]
          user.notes.find_each <span class="hljs-keyword">do</span> |</span>note<span class="hljs-params">|
            csv &lt;&lt; [ note.title, note.body.to_plain_text ]
          <span class="hljs-keyword">end</span>
        <span class="hljs-keyword">end</span>

        file.get_output_stream("user_notes.csv") <span class="hljs-keyword">do</span> |</span>f<span class="hljs-params">|
          f.write(csv_content)
        <span class="hljs-keyword">end</span>

        file.commit

        file.flock(File::LOCK_UN)  # Unlock the file
        Rails.logger.info "Lock released by #{<span class="hljs-keyword">self</span>.<span class="hljs-keyword">class</span>.name} <span class="hljs-keyword">for</span> #{zip_file_path}"
      <span class="hljs-keyword">else</span>
        Rails.logger.info "Failed to acquire lock <span class="hljs-keyword">for</span> #{<span class="hljs-keyword">self</span>.<span class="hljs-keyword">class</span>.name}, retrying..."
        retry_job(wait: 5.seconds)
        <span class="hljs-keyword">return</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>

    # Update export progress
    export = Export.find(export_id)
    <span class="hljs-keyword">if</span> export.mark_job_complete
      ExportCleanupJob.perform_later(user_id, zip_file_path, export.prefix)
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span></span>
</code></pre>
<p>In the above job, we are getting all notes for a user and creating a CSV for their requested export. We start by opening the zip file, locking it with the a bitwise OR of <code>File::LOCK_EX | File::LOCK_NB</code>. Once the zip is locked we proceed with generating the CSV content, outputting it to the zip file and ultimately ensuring the content of the zip is committed. Once thats done, we unlock the zip and move on with the job. If the lock fails to be acquired we log out the failure and retry the job after 5 seconds.</p>
<hr />
<h2 id="heading-key-takeaways"><strong>Key Takeaways</strong></h2>
<ul>
<li><p><strong>File locking</strong> with <code>flock</code> is essential when multiple background jobs need to write to the same file concurrently.</p>
</li>
<li><p>Always <strong>commit</strong> changes when modifying a ZIP file in a concurrent environment to ensure data is saved properly.</p>
</li>
<li><p>Adding retry logic helps manage cases where a job cannot immediately acquire the lock, allowing the system to recover gracefully.</p>
</li>
</ul>
<p>These small but powerful adjustments have made my export process more reliable and scalable.</p>
<hr />
<h2 id="heading-alternative-approaches">Alternative Approaches</h2>
<p>When expanding on the coordination of multiple export jobs using a ZIP file, it's important to weigh the <strong>tradeoffs</strong> and consider <strong>alternative approaches</strong> depending on your application’s needs, scalability, and complexity. Here are some tradeoffs and alternatives worth exploring.</p>
<h3 id="heading-file-locking">File Locking</h3>
<p>My current approach locks the ZIP file before writing and releases the lock after it’s done. While this prevents race conditions, file locking comes with its own tradeoffs:</p>
<ul>
<li><p><strong>Pro</strong>: Simple and easy to implement. It provides an effective way to prevent concurrency issues when multiple jobs write to the same file.</p>
</li>
<li><p><strong>Con</strong>: Lock contention can arise when many jobs are trying to access the same file at once. If several jobs are queued to write to the ZIP file, they must wait for the file lock to be released, which can slow down the process.</p>
</li>
</ul>
<p><strong>Alternatives</strong></p>
<ul>
<li><p><strong>Database-Backed Job Queue Coordination</strong>: Instead of relying on file locks, you can store the results of each job in the database, then have a single process handle creating the ZIP file. This avoids locking issues but adds the overhead of managing results in the database.</p>
</li>
<li><p><strong>Distributed Locking Services</strong>: For large-scale systems, using a distributed locking service such as Redis-based locking (e.g., with <code>Redlock</code>) allows for more robust concurrency control. This helps ensure locks are respected across distributed systems, which is useful when dealing with multiple servers or processes.</p>
</li>
</ul>
<h3 id="heading-sequential-job-execution">Sequential Job Execution</h3>
<p>Although jobs are triggered concurrently, the need for file locking causes them to effectively run sequentially when writing to the ZIP file, as each job must wait for the previous one to finish.</p>
<ul>
<li><p><strong>Pro</strong>: Simple and predictable. Jobs run in sequence and only one writes to the ZIP at a time.</p>
</li>
<li><p><strong>Con</strong>: This limits the speed at which jobs can complete since they cannot write in parallel.</p>
</li>
</ul>
<p><strong>Alternatives</strong></p>
<ul>
<li><p><strong>Write Each Job’s Output to Separate Files</strong>: Instead of having each job write directly to the ZIP, have each job write its output to a temporary file. Once all jobs are complete, you can use a final job to combine all the temporary files into a single ZIP file. This allows each job to run concurrently and avoids file contention.</p>
</li>
<li><p><strong>Stream the Output</strong>: For very large exports, instead of writing the entire ZIP to disk in one go, you can stream the output directly to the user or to cloud storage (such as S3). This avoids large intermediate files and can reduce the overall time to delivery.</p>
</li>
</ul>
<h3 id="heading-resource-usage">Resource Usage</h3>
<ul>
<li><p><strong>Pro</strong>: Using a single ZIP file reduces memory overhead compared to storing each piece of data in memory before finalizing the export.</p>
</li>
<li><p><strong>Con</strong>: Writing large files to disk can consume significant disk space and I/O resources, especially when many exports are happening simultaneously.</p>
</li>
</ul>
<p><strong>Alternatives</strong></p>
<ul>
<li><p><strong>In-Memory Zip Creation</strong>: If the exports are relatively small, you can create the ZIP file in memory using <code>StringIO</code> or a similar mechanism. This reduces disk I/O but increases memory usage.</p>
</li>
<li><p><strong>Direct Streaming to Cloud Storage</strong>: Instead of writing the ZIP file to local disk, you could stream each part of the ZIP directly to cloud storage (e.g., AWS S3) as the jobs are processed. This reduces the need for local disk space but may require more complex coordination.</p>
</li>
</ul>
<h3 id="heading-failure-handling">Failure Handling</h3>
<p>With multiple concurrent jobs writing to a single file, ensuring failure handling and retries are robust is important. If one job fails to complete, the entire export could be incomplete or corrupted.</p>
<ul>
<li><p><strong>Pro</strong>: Jobs can retry upon failure, ensuring eventual completion.</p>
</li>
<li><p><strong>Con</strong>: If retries are not handled carefully (e.g., ensuring the state of the ZIP file isn’t corrupted), multiple failures can still result in partial exports.</p>
</li>
</ul>
<p><strong>Alternatives</strong></p>
<ul>
<li><p><strong>Atomic File Writes</strong>: Using temporary files for each job and only moving them into the final ZIP once completed ensures that partial failures do not corrupt the final file. This way, even if a job fails, you can retry it without affecting the rest of the export.</p>
</li>
<li><p><strong>Job State Tracking</strong>: Implement tracking of each job’s state in the database. If a job fails, it can be retried without corrupting the overall export, and the ZIP creation can be resumed once the failed job completes successfully.</p>
</li>
</ul>
<p>Depending on the scenario, such as large data sets or high concurrency requirements, a mixture of these approaches will be needed. Keeping it simple is the first step. Once you learn more about the behavior of your system, thats when taking a closer look at these alternatives might be the right choice for you.</p>
<hr />
<h2 id="heading-final-thoughts"><strong>Final Thoughts</strong></h2>
<p>Enabling users to have full control of data starts with creating an exporting system that is easy, fast and scalable. Kicking off concurrent jobs that lookup, generate and manage files can be complex. In my personal project I circumvented race conditions and ensured that each job accurately writes to a ZIP file with file locking and proper file committing. Tracking exports significantly made it easier to debug and manage the system. Implementing these practices in your Ruby on Rails applications can save significant complications in the future.  </p>
<p>Let me know if you have similar problems and what techniques you have applied to go beyond them! Drop a comment or reach out to me on my <a target="_blank" href="https://alvincrespo.com/">website</a>, I’m always up for a friendly chat.</p>
<hr />
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://ruby-doc.org/3.3.4/File.html#method-i-flock">File#flock</a></p>
<p><a target="_blank" href="https://www.rubydoc.info/github/rubyzip/rubyzip/Zip/File#commit-instance_method">Zip::File#commit</a></p>
]]></content:encoded></item><item><title><![CDATA[Build a Scalable Export in Ruby on Rails]]></title><description><![CDATA[Learn to build and scale data export features in Ruby on Rails using AWS S3, with tips on performance and efficiency]]></description><link>https://alvincrespo.hashnode.dev/build-a-scalable-export-in-ruby-on-rails</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/build-a-scalable-export-in-ruby-on-rails</guid><category><![CDATA[Ruby]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[background worker]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Wed, 16 Oct 2024 10:07:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/7zj4G2bpQWY/upload/ed20cf62031ee37aaeb5e7f48dd69d92.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there! If you're a software developer with a few years of expertise or an entrepreneur establishing a platform and realize your customers require a way to export their data, this post is for you. I've been creating SaaS applications for 15 years and have done a decent amount of export work. I recently created a feature in a Ruby on Rails that enabled customers to export their uploaded content from AWS S3 and thought I'd share some of it with you.</p>
<p>By the end of this post, you'll understand how to not only develop a similar solution, but also make it efficient and scalable. Ready? Let's dive in!</p>
<h2 id="heading-why-build-an-export-job">Why Build an Export Job?</h2>
<p>So, why do you need an export job in the first place? Well, if you’re dealing with user-uploaded content—there’s a good chance your users will want to download their data at some point. It could be for regulatory reasons, reporting, backups, or simply peace of mind. That’s where an export job comes in.</p>
<p>Now, let’s break down the key steps.</p>
<h2 id="heading-setting-up-the-exportjob-class">Setting Up the ExportJob Class</h2>
<p>Here’s the core of the solution—an <code>ExportsJob</code> class that we can use to gather all the files a user has uploaded and zip them up for easy download. Below is the code, and I’ll explain each part in a friendly, step-by-step way:</p>
<pre><code class="lang-ruby"><span class="hljs-keyword">require</span> <span class="hljs-string">"zip"</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">"open-uri"</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExportsJob</span> &lt; ApplicationJob</span>
  queue_as <span class="hljs-symbol">:default</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">perform</span><span class="hljs-params">(user_id)</span></span>
    user = User.find(user_id)
    s3_client = Aws::S3::Client.new
    s3_resource = Aws::S3::Resource.new(<span class="hljs-symbol">client:</span> s3_client)
    bucket_name = ENV.fetch(<span class="hljs-string">"AWS_S3_BUCKET"</span>, <span class="hljs-string">"your-s3-bucket-name"</span>)
    bucket = s3_resource.bucket(bucket_name)
    prefix = SecureRandom.hex(<span class="hljs-number">8</span>)

    zip_file_path = Rails.root.join(<span class="hljs-string">"tmp"</span>, <span class="hljs-string">"<span class="hljs-subst">#{prefix}</span>_export.zip"</span>)

    Zip::File.open(zip_file_path, Zip::File::CREATE) <span class="hljs-keyword">do</span> <span class="hljs-params">|zipfile|</span>
      bucket.objects(<span class="hljs-symbol">prefix:</span> user.uuid).each <span class="hljs-keyword">do</span> <span class="hljs-params">|object|</span>
        file_name = ActiveStorage::Blob.find_by(<span class="hljs-symbol">key:</span> object.key).filename
        zipfile.get_output_stream(file_name) <span class="hljs-keyword">do</span> <span class="hljs-params">|f|</span>
          object.get <span class="hljs-keyword">do</span> <span class="hljs-params">|chunk|</span>
            f.write(chunk)
          <span class="hljs-keyword">end</span>
        <span class="hljs-keyword">end</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>

    export_key = <span class="hljs-string">"exports/<span class="hljs-subst">#{prefix}</span>_export.zip"</span>
    File.open(zip_file_path, <span class="hljs-string">"rb"</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|file|</span>
      s3_client.put_object(<span class="hljs-symbol">bucket:</span> bucket_name, <span class="hljs-symbol">key:</span> export_key, <span class="hljs-symbol">body:</span> file)
    <span class="hljs-keyword">end</span>

    File.delete(zip_file_path)

    UserMailer.export_ready(user, export_key).deliver_now
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-setting-up-your-aws-s3-integration">Setting Up Your AWS S3 Integration</h3>
<p>First things first, we need to pull in the right tools to interact with your file storage. In this case, I’m using AWS S3 for file storage, so make sure you’ve got the AWS SDK set up and configured in your app.</p>
<p>You’ll want to start by creating an initializer to configure the AWS library:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># config/initializers/aws.rb</span>

<span class="hljs-keyword">require</span> <span class="hljs-string">"aws-sdk-s3"</span>

Aws.config.update(
  <span class="hljs-symbol">region:</span> ENV.fetch(<span class="hljs-string">"AWS_REGION"</span>, <span class="hljs-string">"us-east-1"</span>),
  <span class="hljs-symbol">credentials:</span> Aws::Credentials.new(
    ENV.fetch(<span class="hljs-string">"AWS_ACCESS_KEY_ID"</span>),
    ENV.fetch(<span class="hljs-string">"AWS_SECRET_ACCESS_KEY"</span>)
  )
)
</code></pre>
<p>Going back to our job, let’s create an S3 client, S3 resource and retrieve an instance of the bucket, or <a target="_blank" href="https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Bucket.html"><code>Aws::S3::Bucket</code></a>.</p>
<pre><code class="lang-ruby">s3_client = Aws::S3::Client.new
s3_resource = Aws::S3::Resource.new(<span class="hljs-symbol">client:</span> s3_client)
bucket_name = ENV.fetch(<span class="hljs-string">"AWS_S3_BUCKET"</span>, <span class="hljs-string">"your-s3-bucket-name"</span>)
bucket = s3_resource.bucket(bucket_name)
</code></pre>
<p>Make sure you replace <code>"your-s3-bucket-name"</code> with the correct bucket name. If you haven’t set up your bucket yet, head over to the AWS Console and do that first. You’ll need the bucket name handy for this job. Setting up and configuring an S3 bucket is beyond the scope of this post, but I’ll write another one up soon.</p>
<h3 id="heading-gathering-the-files">Gathering the Files</h3>
<p>Next, I wanted to gather all of the files uploaded by a user. Each file is stored in S3 with a unique <code>key</code> tied to the user's <code>uuid</code>. Side note, the <code>uuid</code> being used here is a an identifier for the referring object on S3, not the unique identifier of the users record in the application. In this step, we loop through those files and add them to a zip archive:</p>
<pre><code class="lang-ruby">bucket.objects(<span class="hljs-symbol">prefix:</span> user.uuid).each <span class="hljs-keyword">do</span> <span class="hljs-params">|object|</span>
  file_name = ActiveStorage::Blob.find_by(<span class="hljs-symbol">key:</span> object.key).filename
  zipfile.get_output_stream(file_name) <span class="hljs-keyword">do</span> <span class="hljs-params">|f|</span>
    object.get <span class="hljs-keyword">do</span> <span class="hljs-params">|chunk|</span>
      f.write(chunk)
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>There are a couple of items to note here.</p>
<ol>
<li><p><code>bucket.objects(prefix: user.uuid)</code> returns an instance of <code>Aws::S3::ObjectSummary::Collection</code></p>
</li>
<li><p>It might be worth exploring the inherited <code>limit</code> method from <code>Aws::Resources::Collection</code> to paginate over results.</p>
</li>
<li><p>Another optimization that can be made here is to eager load <code>ActiveStorage::Blob</code> instances, although that has it’s own tradeoffs here.</p>
</li>
</ol>
<h3 id="heading-compressing-the-files-into-a-zip">Compressing the Files into a Zip</h3>
<p>We’re utilizing <a target="_blank" href="https://github.com/rubyzip/rubyzip"><code>rubyzip</code></a> to create a <code>zip</code> file, so you’ll want to add the dependency to your Gemfile:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># Gemfile</span>

gem <span class="hljs-string">"rubyzip"</span>
</code></pre>
<p>The <code>rubyzip</code> library makes it super easy to compress files. When working with large datasets, memory management is key, so we use <a target="_blank" href="https://www.rubydoc.info/github/rubyzip/rubyzip/Zip%2FFile:get_output_stream"><code>get_output_stream</code></a> to write data to the zip file in chunks rather than loading it all into memory at once. This way, even if a user has a ton of files, the process won’t choke on large data volumes.</p>
<pre><code class="lang-ruby">Zip::File.open(zip_file_path, Zip::File::CREATE) <span class="hljs-keyword">do</span> <span class="hljs-params">|zipfile|</span>
  <span class="hljs-comment"># Add files to the zip here...</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-uploading-the-zip-file-to-s3">Uploading the Zip File to S3</h3>
<p>Once we’ve zipped up all the user’s files, we need to store that zip file somewhere. In this case, I upload the zip file back to S3 under an <code>exports/</code> folder:</p>
<pre><code class="lang-ruby">export_key = <span class="hljs-string">"exports/<span class="hljs-subst">#{prefix}</span>_export.zip"</span>
File.open(zip_file_path, <span class="hljs-string">"rb"</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|file|</span>
  s3_client.put_object(<span class="hljs-symbol">bucket:</span> bucket_name, <span class="hljs-symbol">key:</span> export_key, <span class="hljs-symbol">body:</span> file)
<span class="hljs-keyword">end</span>
</code></pre>
<p>I generate a random <code>prefix</code> so each export has a unique name. After uploading the file, it’s easy for the user to download it.</p>
<h3 id="heading-cleanup-and-notify-the-user">Cleanup and Notify the User</h3>
<p>After uploading the zip, it’s good housekeeping to delete the local temporary file. Also, it’s crucial to notify the user when their export is ready. Here, I send an email notification, but you could also send an in-app notification or SMS, depending on what works best for your app:</p>
<pre><code class="lang-ruby">File.delete(zip_file_path)
UserMailer.export_ready(user, export_key).deliver_now
</code></pre>
<p>And that's it! The user gets notified, and they can download their data whenever they want.</p>
<h2 id="heading-pro-tips-for-scaling-your-export-job">Pro Tips for Scaling Your Export Job</h2>
<p>If your app grows or you start getting users with massive amounts of data, here are a few things to keep in mind:</p>
<ol>
<li><p><strong>Batch Your Exports</strong>: For really large exports, you might want to break it up into smaller batches to avoid timeouts or memory issues. Depending on the volume of data being exported, you might need a pipeline or job that creates + manages sub-jobs / exports.</p>
</li>
<li><p><strong>Use Background Jobs</strong>: This job runs asynchronously using <code>ActiveJob</code> + <code>Sidekiq</code>, which is perfect for long-running tasks.</p>
</li>
<li><p><strong>Monitor Performance</strong>: Keep an eye on performance. Make sure the export job doesn’t eat up too many resources and slow down your app.</p>
</li>
</ol>
<h2 id="heading-wrapping-it-up">Wrapping It Up</h2>
<p>So, that’s how I built an export job in Ruby on Rails to ensure users could easily download all their uploaded content. If you’re an engineer looking to implement something similar or an entrepreneur who needs a solution like this for your app, I hope you found this post helpful! Feel free to reach out if you have any questions, or connect with me on my blog for more technical insights.</p>
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Bucket.html">AWS::S3::Bucket</a></p>
<p><a target="_blank" href="https://github.com/rubyzip/rubyzip">rubyzip</a></p>
]]></content:encoded></item><item><title><![CDATA[Disabling .env files for Github Copilot]]></title><description><![CDATA[Disable GitHub Copilot for .env files in VSCode by configuring language mode to plaintext. Learn how step-by-step.]]></description><link>https://alvincrespo.hashnode.dev/disabling-env-files-for-github-copilot</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/disabling-env-files-for-github-copilot</guid><category><![CDATA[github copilot]]></category><category><![CDATA[Environment variables]]></category><category><![CDATA[dotfiles]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Sat, 28 Sep 2024 11:04:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/NeWmr345VC4/upload/76cd8981e14812604fe0473cd3d11b06.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I was curious if there was a way to configure Github copilot to NOT have access to certain files in a project and found that - it’s not necessarily straightforward. It turns out that there are no dotfiles you can set up or a setting to explicitly tell copilot not to have access to certain files in your project, which seems problematic from a security perspective. However, there is a way to “disable” Github copilot by setting the language mode to “plaintext” in VSCode.</p>
<hr />
<h1 id="heading-configuring-language-mode">Configuring Language Mode</h1>
<p>There are three ways to configure the language mode.</p>
<h2 id="heading-file-in-focus-shortcuts">File in focus (shortcuts)</h2>
<p>With the env var file open and in focus, do the following</p>
<ol>
<li><p>Open the Command Palette by pressing <code>Cmd+Shift+P</code>.</p>
</li>
<li><p>Type <code>Change Language Mode</code> and select it.</p>
</li>
<li><p>In the language mode dropdown, type <code>plaintext</code> and select it.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519307422/2f7b2f36-cace-44fd-b66f-a88f62a68ab5.png" alt="Open the Command Pallete" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519314375/055a8e05-bfe4-4355-a629-edb66b1d0a81.png" alt="Change Language Model" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519318382/adca8f06-6d01-447e-b482-b99ec0900519.png" alt="Verify Plaintext is selected" class="image--center mx-auto" /></p>
<h2 id="heading-file-in-focus-gui">File in focus (gui)</h2>
<p>With the env var file open and in focus, do the following</p>
<ol>
<li><p>At the bottom right of the status bar, click on the language mode selector.</p>
</li>
<li><p>Select <code>Configure File Association for ‘.env’</code></p>
</li>
<li><p>Type <code>plaintext</code> and select it.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519546693/7f89d085-e3d4-426e-96cc-9274f76e68ac.png" alt="Click on Language Mode Selector at the bottom right" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519555216/d50d2366-2f74-41db-a781-68e4d5053f86.png" alt="Select Configure File Association for '.env'" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727519558544/6c0a5966-49fc-4937-87b5-f211d8feab3b.png" alt="Type plaintext and select it" class="image--center mx-auto" /></p>
<h2 id="heading-user-settings-json">User Settings (JSON)</h2>
<ol>
<li><p>Open the Command Palette by pressing <code>Cmd+Shift+P</code>.</p>
</li>
<li><p>Type <code>open user settings</code> and select it.</p>
</li>
<li><p>With the settings.json file open, add the following:</p>
</li>
</ol>
<pre><code class="lang-ruby"><span class="hljs-string">"files.associations"</span>: {
    <span class="hljs-string">".env"</span>: <span class="hljs-string">"plaintext"</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727520335193/42e46d90-6c72-4a4a-b44a-48bb745a90c5.png" alt="Open Command Palette and type &quot;open user settings&quot;" class="image--center mx-auto" /></p>
<h2 id="heading-user-settings-ui">User Settings (UI)</h2>
<ol>
<li><p>Open the Command Palette by pressing <code>Cmd+Shift+,</code>.</p>
</li>
<li><p>Search <code>associations</code></p>
</li>
<li><p>Add <code>.env</code> as an item and set it to <code>plaintext</code></p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727520525150/c77c0806-0666-4bb6-adb1-953806f07957.png" alt="Adding .env to settings in UI" class="image--center mx-auto" /></p>
<h3 id="heading-bonus-wildcard-env-var-files">Bonus: Wildcard env var files</h3>
<p>Setting <code>.env</code> as the file association to your settings will explicitely tell Github Copilot to disable itself for the <code>.env</code> file, however it will NOT disable itself for other file like <code>.env.local</code> or <code>.env.development</code>. So it’s a best practice to add a wildcard AFTER the <code>v</code> like so:</p>
<pre><code class="lang-ruby"><span class="hljs-string">"files.associations"</span>: {
    <span class="hljs-string">".env*"</span>: <span class="hljs-string">"plaintext"</span>
}
</code></pre>
<hr />
<h1 id="heading-conclusion">Conclusion</h1>
<p>There is no way to explicitly tell Github Copilot to ignore certain files. That is, unless, you have a Github Copilot Business account - which then <a target="_blank" href="https://github.com/orgs/community/discussions/11254#discussioncomment-8638961">affords you this ability</a>. With the above technique, there are some considerations per Github’s documentation:</p>
<blockquote>
<ul>
<li><p>In Copilot Chat in Visual Studio Code and Visual Studio, content exclusions are not applied when you use the <code>@github</code> chat participant in your question.</p>
</li>
<li><p>It's possible that Copilot may use semantic information from an excluded file if the information is provided by the IDE in a non-excluded file. Examples of such content include type information and hover-over definitions for symbols used in code.</p>
</li>
<li><p><a target="_blank" href="https://docs.github.com/en/copilot/managing-copilot/managing-github-copilot-in-your-organization/setting-policies-for-copilot-in-your-organization/excluding-content-from-github-copilot#limitations">Excluding content from Github Copilot - Limitations of content exclusions</a></p>
</li>
</ul>
</blockquote>
<hr />
<h1 id="heading-references">References</h1>
<p><a target="_blank" href="https://stackoverflow.com/questions/77780462/how-to-exclude-specific-files-like-env-from-github-copilot-in-vs-code">https://stackoverflow.com/questions/77780462/how-to-exclude-specific-files-like-env-from-github-copilot-in-vs-code</a></p>
<p><a target="_blank" href="https://docs.github.com/en/copilot/managing-copilot/managing-github-copilot-in-your-organization/setting-policies-for-copilot-in-your-organization/excluding-content-from-github-copilot#limitations">https://docs.github.com/en/copilot/managing-copilot/managing-github-copilot-in-your-organization/setting-policies-for-copilot-in-your-organization/excluding-content-from-github-copilot#limitations</a></p>
<p><a target="_blank" href="https://github.com/orgs/community/discussions/11254#discussioncomment-8638961">https://github.com/orgs/community/discussions/11254#discussioncomment-8638961</a></p>
<p><a target="_blank" href="https://github.com/orgs/community/discussions/13334">https://github.com/orgs/community/discussions/13334</a></p>
]]></content:encoded></item><item><title><![CDATA[Testing ViewComponent w/ Capybara]]></title><description><![CDATA[Learn how to test ViewComponent with Capybara, including custom assertions and detailed explanations using the Trix Editor as an example.]]></description><link>https://alvincrespo.hashnode.dev/testing-viewcomponent-w-capybara</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/testing-viewcomponent-w-capybara</guid><category><![CDATA[trix-editor]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[viewcomponent]]></category><category><![CDATA[capybara]]></category><category><![CDATA[Integration Testing]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Trix]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Tue, 13 Aug 2024 11:00:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/NiFAsfF1_Ww/upload/62cb60818bb9308c7652f0251b9f671f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Today I was writing some tests and dug into a little bit of ViewComponent and Capybara. Most of time you read a tutorial and just kind of get whatever done, here I'm going to explain in detail what my test is doing and why it's important.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If you're using the <a target="_blank" href="https://trix-editor.org/">Trix</a> editor, I also show you how to test your view components with a nice helper inspired by <a target="_blank" href="https://medium.com/@thinkolson">Will Olson's</a> article <a target="_blank" href="https://medium.com/eighty-twenty/testing-the-trix-editor-with-capybara-and-minitest-158f895ad15f"><strong>Testing the Trix Editor with Capybara and MiniTest</strong></a><strong>.</strong></div>
</div>

<hr />
<h2 id="heading-setup">Setup</h2>
<p>Here you'll see the component, it's template and associated test. This component is responsible for rendering out a form that can be used in multiple parts of an application; including <code>/notes</code>, <code>garden/:id/notes</code> and <code>/garden/:garden_id/plants/:plant_id/notes</code>. To support this usage, we pass in <code>form_options</code> to the component that then gets used by the <code>form_with</code> view helper.</p>
<p>To keep this article simple, we're just going to verify the form renders the title, summary and body of a note.</p>
<p><strong>Component</strong></p>
<pre><code class="lang-ruby"><span class="hljs-comment"># app/components/note_form_component.rb</span>

<span class="hljs-comment"># frozen_string_literal: true</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NoteFormComponent</span> &lt; ViewComponent::Base</span>
  delegate <span class="hljs-symbol">:rich_text_area_tag</span>, <span class="hljs-symbol">to:</span> <span class="hljs-symbol">:helpers</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">initialize</span><span class="hljs-params">(<span class="hljs-symbol">form_options:</span>)</span></span>
    <span class="hljs-keyword">super</span>

    @form_options = form_options
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p><strong>Template</strong></p>
<pre><code class="lang-erb"><span class="hljs-comment">&lt;%# app/components/note_form_component.html.erb  %&gt;</span><span class="xml">

<span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form_with(**@form_options) <span class="hljs-keyword">do</span> <span class="hljs-params">|form|</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.label <span class="hljs-symbol">:title</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_field <span class="hljs-symbol">:title</span>, <span class="hljs-symbol">autofocus:</span> <span class="hljs-symbol">:true</span>, <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">input</span>" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.label <span class="hljs-symbol">:summary</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.text_area <span class="hljs-symbol">:summary</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"field"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.label <span class="hljs-symbol">:body</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.rich_text_area <span class="hljs-symbol">:body</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex flex-row-reverse items-center mt-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> form.submit </span><span class="xml"><span class="hljs-tag">%&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">%=</span></span></span><span class="ruby"> link_to <span class="hljs-string">"Cancel Note"</span>, <span class="hljs-symbol">:back</span>, <span class="hljs-class"><span class="hljs-keyword">class</span>: "<span class="hljs-title">mr</span>-4" </span></span><span class="xml"><span class="hljs-tag">%&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">%</span></span></span><span class="ruby"> <span class="hljs-keyword">end</span> </span><span class="xml"><span class="hljs-tag">%&gt;</span></span>
</code></pre>
<p><strong>Test</strong></p>
<pre><code class="lang-ruby"><span class="hljs-comment"># test/components/note_form_component_test.rb</span>

<span class="hljs-keyword">require</span> <span class="hljs-string">'test_helper'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NoteFormComponentTest</span> &lt; ViewComponent::TestCase</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">form_options</span></span>
    { <span class="hljs-symbol">form_options:</span> { <span class="hljs-symbol">model:</span> Note.new, <span class="hljs-symbol">url:</span> <span class="hljs-string">'/notes'</span>, <span class="hljs-symbol">local:</span> <span class="hljs-literal">true</span> } }
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_component_renders_form_with_title_field</span></span>
      <span class="hljs-comment"># assert the hell out of this</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<hr />
<h2 id="heading-viewcomponent-capybara">ViewComponent + Capybara</h2>
<p>The ViewComponent docs mention that we can use Capybara in our specs and I want specifically want to use <a target="_blank" href="https://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Matchers#assert_selector-instance_method"><code>assert_selector</code></a> to verify the contents of my components are rendered.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">📕</div>
<div data-node-type="callout-text"><code>assert_selector</code> is a "Matcher" in Capybara. It asserts that an element is found at lease once.</div>
</div>

<p>To verify that all my elements are within a "form", I'm going to use <code>assert_selector</code> with a block and then verify all my elements are within it. This is done like so:</p>
<pre><code class="lang-ruby">
  assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
      <span class="hljs-comment"># assert a form field</span>
  <span class="hljs-keyword">end</span>
</code></pre>
<p>Let's start with the title of the note:</p>
<pre><code class="lang-ruby">  assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
    assert_selector <span class="hljs-symbol">:field</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'title'</span>
  <span class="hljs-keyword">end</span>
</code></pre>
<p>Ah, we have a few things going on here:</p>
<ol>
<li><p><code>assert_selector</code> can be used in different ways</p>
</li>
<li><p>There is a <code>field</code> type of selector</p>
</li>
<li><p>We can pass attributes to verify a field</p>
</li>
</ol>
<p>The documentation for <code>assert_selector</code> states the following:</p>
<pre><code class="lang-plaintext">assert_selector(*args, &amp;optional_filter_block) ⇒ Object

Parameters:
kind (Symbol) — Optional selector type (:css, :xpath, :field, etc.). Defaults to default_selector.
locator (String) — The locator for the specified selector
options (Hash) — a customizable set of options
</code></pre>
<p>The <code>kind</code> parameter defaults to something called <code>default_selector</code>, which is defined by <code>Capybara::Selector</code>. It turns out we can make our assertions cleaner by using <code>:field</code> as our selector:</p>
<pre><code class="lang-plaintext">:field - Select field elements (input [not of type submit, image, or hidden], textarea, select)
Locator: Matches against the id, test_id attribute, name, placeholder, or associated label text
Filters:
:name (String, Regexp) - Matches the name attribute
:placeholder (String, Regexp) - Matches the placeholder attribute
:type (String) - Matches the type attribute of the field or element type for 'textarea' and 'select'
:readonly (Boolean) - Match on the element being readonly
:with (String, Regexp) - Matches the current value of the field
:checked (Boolean) - Match checked fields?
:unchecked (Boolean) - Match unchecked fields?
:disabled (Boolean, :all) - Match disabled field? (Default: false)
:multiple (Boolean) - Match fields that accept multiple values
:valid (Boolean) - Match fields that are valid/invalid according to HTML5 form validation
:validation_message (String, Regexp) - Matches the elements current validationMessage
</code></pre>
<p>We can also use <code>:button</code> to verify the submit button renders correctly:</p>
<pre><code class="lang-plaintext">:button - Find buttons ( input [of type submit, reset, image, button] or button elements )
Locator: Matches the id, test_id attribute, name, value, or title attributes, string content of a button, or the alt attribute of an image type button or of a descendant image of a button
Filters:
:name (String, Regexp) - Matches the name attribute
:title (String) - Matches the title attribute
:value (String) - Matches the value of an input button
:type (String) - Matches the type attribute
:disabled (Boolean, :all) - Match disabled buttons (Default: false)
</code></pre>
<p>Using <code>name</code> to identify the field's we want to verify, we will have the following assertions:</p>
<pre><code class="lang-ruby">
<span class="hljs-comment"># Verify the title field</span>
assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
  assert_selector <span class="hljs-symbol">:field</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'title'</span>
<span class="hljs-keyword">end</span>

<span class="hljs-comment"># Verify the submit button</span>
assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
  assert_selector <span class="hljs-symbol">:button</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'commit'</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>However, we have an issue. Path helpers don't work with view components, so using <code>notes_path</code> or <code>notes_urls</code> wouldn't work if we passed it in with <code>form_options</code>. To prevent the <code>ActionController::UrlGenerationError</code> error, we then need to wrap our assertions with <code>with_request_url</code>. Let's keep it simple and hardcode the url it:</p>
<pre><code class="lang-ruby">with_request_url <span class="hljs-string">'/notes/new'</span> <span class="hljs-keyword">do</span>
  render_inline(NoteFormComponent.new(<span class="hljs-symbol">form_options:</span>))

  assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
    assert_selector <span class="hljs-symbol">:field</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'title'</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<hr />
<h2 id="heading-custom-assertions">Custom Assertions</h2>
<p>As a bonus to this article, we're going to write a helper we can use to assert that the trix editor is rendered within our view component. Let's create a <code>capybara_helpers.rb</code> file and place it in <code>test/support</code>. You might need to create the <code>support</code> directory as it's not a default with built-in Rails usage of Minitest.</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># test/support/capybara_helpers.rb</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">assert_trix_editor</span><span class="hljs-params">(id)</span></span>
  assert_selector(<span class="hljs-symbol">:xpath</span>, <span class="hljs-string">"//*[@id='<span class="hljs-subst">#{id}</span>']"</span>, <span class="hljs-symbol">visible:</span> <span class="hljs-literal">false</span>)
<span class="hljs-keyword">end</span>
</code></pre>
<p>Once you've got the helper written, we need to ensure that we load this file in, we can do that in <code>test_helpers.rb</code>:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># test/test_helper.rb</span>

Dir[<span class="hljs-string">"<span class="hljs-subst">#{File.dirname(__FILE_<span class="hljs-number">_</span>)}</span>/support/**/*.rb"</span>].each { <span class="hljs-params">|f|</span> <span class="hljs-keyword">require</span> f }
</code></pre>
<p>Place this before the <code>module ActiveSupport</code>:</p>
<pre><code class="lang-ruby">ENV[<span class="hljs-string">'RAILS_ENV'</span>] <span class="hljs-params">||</span>= <span class="hljs-string">'test'</span>

require_relative <span class="hljs-string">'../config/environment'</span>
<span class="hljs-keyword">require</span> <span class="hljs-string">'rails/test_help'</span>

Dir[<span class="hljs-string">"<span class="hljs-subst">#{File.dirname(__FILE_<span class="hljs-number">_</span>)}</span>/support/**/*.rb"</span>].each { <span class="hljs-params">|f|</span> <span class="hljs-keyword">require</span> f }

<span class="hljs-class"><span class="hljs-keyword">module</span> <span class="hljs-title">ActiveSupport</span></span>
  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestCase</span></span>
    <span class="hljs-comment"># Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.</span>
    fixtures <span class="hljs-symbol">:all</span>
    <span class="hljs-comment"># Add more helper methods to be used by all tests here...</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>Now that we have our capybara helpers being loaded, we can utilize it similarly to our previous assertions:</p>
<pre><code class="lang-ruby">with_request_url <span class="hljs-string">'/notes/new'</span> <span class="hljs-keyword">do</span>
  assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
    assert_trix_editor <span class="hljs-string">'body'</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>The final product of our test's will look something like this:</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># test/components/note_form_component_test.rb</span>

<span class="hljs-keyword">require</span> <span class="hljs-string">'test_helper'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NoteFormComponentTest</span> &lt; ViewComponent::TestCase</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">form_options</span></span>
    { <span class="hljs-symbol">form_options:</span> { <span class="hljs-symbol">model:</span> Note.new, <span class="hljs-symbol">url:</span> <span class="hljs-string">'/notes'</span>, <span class="hljs-symbol">local:</span> <span class="hljs-literal">true</span> } }
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_component_renders_form_with_title_field</span></span>
    with_request_url <span class="hljs-string">'/notes/new'</span> <span class="hljs-keyword">do</span>
      render_inline(NoteFormComponent.new(<span class="hljs-symbol">form_options:</span>))

      assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
        assert_selector <span class="hljs-symbol">:field</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'title'</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_component_renders_form_with_summary_field</span></span>
    with_request_url <span class="hljs-string">'/notes/new'</span> <span class="hljs-keyword">do</span>
      render_inline(NoteFormComponent.new(<span class="hljs-symbol">form_options:</span>))

      assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
        assert_selector <span class="hljs-symbol">:field</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'summary'</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_component_renders_form_with_content_field</span></span>
    with_request_url <span class="hljs-string">'/notes/new'</span> <span class="hljs-keyword">do</span>
      render_inline(NoteFormComponent.new(<span class="hljs-symbol">form_options:</span>))

      assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
        assert_trix_editor <span class="hljs-string">'body'</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_component_renders_form_with_submit_button</span></span>
    with_request_url <span class="hljs-string">'/notes/new'</span> <span class="hljs-keyword">do</span>
      render_inline(NoteFormComponent.new(<span class="hljs-symbol">form_options:</span>))

      assert_selector <span class="hljs-string">'form'</span> <span class="hljs-keyword">do</span>
        assert_selector <span class="hljs-symbol">:button</span>, <span class="hljs-symbol">name:</span> <span class="hljs-string">'commit'</span>
      <span class="hljs-keyword">end</span>
    <span class="hljs-keyword">end</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>ViewComponent + Capybara is a perfect match for declaratively writing tests that verify your components state. This example is straightforward in that it only tests the default state of the form, but it demonstrates how simple it to write integration tests. These tests can be extended to use <a target="_blank" href="https://www.rubydoc.info/gems/capybara/Capybara/Node/Actions:fill_in">fill_in</a> and <a target="_blank" href="https://www.rubydoc.info/gems/capybara/Capybara%2FNode%2FActions:click_button">click_button</a> to ensure functionality. Why don't you give it a try? 🙂</p>
<hr />
<h2 id="heading-references">References</h2>
<p><a target="_blank" href="https://medium.com/eighty-twenty/testing-the-trix-editor-with-capybara-and-minitest-158f895ad15f">Testing the Trix Editor with Capybara and MiniTest</a></p>
<p><a target="_blank" href="https://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Matchers#assert_selector-instance_method">Capybara::Node::Matchers#assert_selector</a></p>
<p><a target="_blank" href="https://rubydoc.info/github/jnicklas/capybara/Capybara/Selector">Capybara::Selector</a></p>
<p><a target="_blank" href="https://viewcomponent.org/guide/testing.html">ViewComponent - Testing</a></p>
]]></content:encoded></item><item><title><![CDATA[[Tips] Docker aliases with zsh using Ohmyzsh]]></title><description><![CDATA[Streamline Docker tasks with ohmyzsh's aliases in zsh for efficient automation]]></description><link>https://alvincrespo.hashnode.dev/tips-docker-aliases-with-zsh-using-ohmyzsh</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/tips-docker-aliases-with-zsh-using-ohmyzsh</guid><category><![CDATA[ohmyzsh]]></category><category><![CDATA[zsh]]></category><category><![CDATA[shell]]></category><category><![CDATA[shell scripting]]></category><category><![CDATA[Docker]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 12 Aug 2024 11:02:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/vS7LVkPyXJU/upload/811d405615d6394a3928956851ef41b3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I use <a target="_blank" href="https://ohmyz.sh/">ohmyzsh</a> as my preferred shell setup. I also use <a target="_blank" href="https://www.docker.com/">Docker</a>. Recently, I've been focused on automating the setup and teardown of my applications. This is where ohmyzsh's excellent support for docker comes in, as it has many aliases that help with shortening the use of common tasks:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/docker">https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/docker</a></div>
<p> </p>
<p>You can add it to your <code>.zshrc</code> plugin list:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723459967123/b0cf90d2-45fc-4022-b545-5860f65a163a.png" alt class="image--center mx-auto" /></p>
<p>When you restart your shell, you'll have access to commands like</p>
<ul>
<li><p><code>dipru</code> (<code>docker image prune -a</code>),</p>
</li>
<li><p><code>dps</code> (<code>docker ps</code>) and</p>
</li>
<li><p><code>dvls</code> (<code>docker volume ls</code>).</p>
</li>
</ul>
<p>Additionally, if you enable stacking, you'll able to pass options to aliases like <code>dcls</code> (<code>docker container ls</code>). However, be aware of the following issue:</p>
<blockquote>
<p>This enables Zsh to understand commands like <code>docker run -it ubuntu</code>. However, by enabling this, this also makes Zsh complete <code>docker run -u&lt;tab&gt;</code> with <code>docker run -uapprox</code> which is not valid. The users have to put the space or the equal sign themselves before trying to complete.</p>
</blockquote>
<p>Anyways, that's it for today! Ohmyzsh gives us many tools out of the box, docker aliases with autocompletion is one of them. Enable it and you'll have access to many commands you won't need to maintain yourself.</p>
<hr />
<h1 id="heading-references">References</h1>
<p><a target="_blank" href="https://ohmyz.sh/">Ohmyzsh</a></p>
<p><a target="_blank" href="https://www.docker.com/">Docker</a></p>
<p><a target="_blank" href="https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/docker">ohmyzsh - docker reference</a></p>
<p><a target="_blank" href="https://docs.docker.com/reference/cli/docker/system/prune/">docker system prune</a></p>
<p><a target="_blank" href="https://docs.docker.com/reference/cli/docker/image/prune/">docker image prune</a></p>
<p><a target="_blank" href="https://docs.docker.com/reference/cli/docker/container/ls/">docker container ls</a></p>
<p><a target="_blank" href="https://docs.docker.com/reference/cli/docker/volume/ls/">docker volume ls</a></p>
]]></content:encoded></item><item><title><![CDATA[Tips for Working with Complex Normalized Databases]]></title><description><![CDATA[Optimize database performance with highly normalized architectures using tips on denormalization, indexing, caching, and query optimization.]]></description><link>https://alvincrespo.hashnode.dev/tips-for-working-with-complex-normalized-databases</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/tips-for-working-with-complex-normalized-databases</guid><category><![CDATA[MySQL]]></category><category><![CDATA[SQL]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[database design]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Tue, 30 Jul 2024 12:18:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/1iVKwElWrPA/upload/c19548c2d2332cd935e7613297ef9df2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We’ve all been taught the benefits of normalizing our data. So I won’t bore you with those details, but to sum it up:</p>
<blockquote>
<p>Normalization is the process of organizing data in a database. It includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.</p>
<p>Microsoft 365 - <a target="_blank" href="https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description">Description of normalization</a></p>
</blockquote>
<p>To be honest, normalization never really crossed my mind until recently when I’ve had to deal with multiple legacy applications that were “highly normalized”. And when I say “highly normalized” I mean “HIGHLY NORMALIZED” - to the point where it just doesn’t make sense anymore. Which reminded me of this amazing article by Coding Horror: <a target="_blank" href="https://blog.codinghorror.com/maybe-normalizing-isnt-normal/">Maybe Normalizing Isn’t Normal</a>.</p>
<p>The problem is that, unless you’re really <em>lucky</em>, you won’t need to worry about things like this. Instead of talking about this hypothetically, let's walk through a specific scenario and try different techniques out to understand the complexities of this topic. Once we've gone over this scenario lets talk through the technicalities to better understand why highly normalized architectures could be problematic and review optimizations we can consider to improve our experience.</p>
<h2 id="heading-the-scenario">The Scenario</h2>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You can check out the code for this article <a target="_blank" href="https://github.com/alvincrespo/normalized-architectures-perf">here</a>.</div>
</div>

<p>You’re working on an established legacy, large-scale SASS (software as a service) based inventory management system. The system consists of inventory items, and each inventory item has a category, supplier, warehouse and various attributes. A client has requested a report and this report needs to display the item's details including it's supplier name and warehouse name.</p>
<p>Here’s a simplified schema, without the multi-tenancy (just to keep things simple):</p>
<p>Each item references entries in the <code>categories</code>, <code>suppliers</code>, and <code>warehouses</code> tables. Attributes for each item are stored in the <code>item_attributes</code> table. This all make sense and is pretty easy to whip up:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> items (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    category_id <span class="hljs-built_in">INT</span>,
    supplier_id <span class="hljs-built_in">INT</span>,
    warehouse_id <span class="hljs-built_in">INT</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    updated_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (category_id) <span class="hljs-keyword">REFERENCES</span> categories(<span class="hljs-keyword">id</span>),
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (supplier_id) <span class="hljs-keyword">REFERENCES</span> suppliers(<span class="hljs-keyword">id</span>),
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (warehouse_id) <span class="hljs-keyword">REFERENCES</span> warehouses(<span class="hljs-keyword">id</span>)
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> categories (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    updated_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> suppliers (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    updated_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> warehouses (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    location <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    updated_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> item_attributes (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    item_id <span class="hljs-built_in">INT</span>,
    attribute_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    attribute_value <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    updated_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    <span class="hljs-keyword">FOREIGN</span> <span class="hljs-keyword">KEY</span> (item_id) <span class="hljs-keyword">REFERENCES</span> items(<span class="hljs-keyword">id</span>)
);

<span class="hljs-comment">-- To illustrate the denormalization strategy mentioned, here’s an example of a denormalized items_denormalized table:</span>

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> items_denormalized (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span> AUTO_INCREMENT PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    category_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>),
    supplier_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>),
    warehouse_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>),
    attribute_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>),
    attribute_value <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">255</span>),
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    updated_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">UPDATE</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);

<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_items_id <span class="hljs-keyword">ON</span> items(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_categories_id <span class="hljs-keyword">ON</span> categories(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_suppliers_id <span class="hljs-keyword">ON</span> suppliers(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_warehouses_id <span class="hljs-keyword">ON</span> warehouses(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_item_attributes_item_id <span class="hljs-keyword">ON</span> item_attributes(item_id);
</code></pre>
<h2 id="heading-seeding-data">Seeding Data</h2>
<p>For any performance work we do, it’s important to be able to reproduce the scale we’re anticipating in order to get a good idea of how our application will perform. That’s why I’ve put together the following seeding script:</p>
<pre><code class="lang-ruby"><span class="hljs-keyword">require</span> <span class="hljs-string">'faker'</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_records</span><span class="hljs-params">(message, &amp;block)</span></span>
  puts <span class="hljs-string">"Creating <span class="hljs-subst">#{message}</span>."</span>
  starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  <span class="hljs-keyword">yield</span> <span class="hljs-keyword">if</span> block_given?
  ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  elapsed = ending - starting
  puts <span class="hljs-string">"<span class="hljs-subst">#{message.capitalize}</span> created. <span class="hljs-subst">#{elapsed}</span>"</span>
<span class="hljs-keyword">end</span>

puts <span class="hljs-string">'Truncating database...'</span>
ActiveRecord::Tasks::DatabaseTasks.truncate_all
puts <span class="hljs-string">'Database truncated.'</span>

create_records(<span class="hljs-string">'categories'</span>) <span class="hljs-keyword">do</span>
  <span class="hljs-number">10</span>.times <span class="hljs-keyword">do</span>
    Category.create(<span class="hljs-symbol">name:</span> Faker::Book.genre)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

create_records(<span class="hljs-string">'suppliers'</span>) <span class="hljs-keyword">do</span>
  <span class="hljs-number">25</span>.times <span class="hljs-keyword">do</span>
    Supplier.create(<span class="hljs-symbol">name:</span> Faker::Company.name)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

create_records(<span class="hljs-string">'warehouses'</span>) <span class="hljs-keyword">do</span>
  <span class="hljs-number">1000</span>.times <span class="hljs-keyword">do</span>
    Warehouse.create(<span class="hljs-symbol">name:</span> Faker::Company.name, <span class="hljs-symbol">location:</span> Faker::Address.full_address)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

create_records(<span class="hljs-string">'items'</span>) <span class="hljs-keyword">do</span>
  categories = Category.all.to_a
  suppliers = Supplier.all.to_a
  warehouses = Warehouse.all.to_a

  items = <span class="hljs-number">100_000</span>.times.map <span class="hljs-keyword">do</span>
    {
      <span class="hljs-symbol">name:</span> Faker::Commerce.product_name,
      <span class="hljs-symbol">category_id:</span> categories.sample.id,
      <span class="hljs-symbol">supplier_id:</span> suppliers.sample.id,
      <span class="hljs-symbol">warehouse_id:</span> warehouses.sample.id
    }
  <span class="hljs-keyword">end</span>

  items.each_slice(<span class="hljs-number">1000</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|batch|</span>
    Item.insert_all(batch)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

create_records(<span class="hljs-string">'item attributes'</span>) <span class="hljs-keyword">do</span>
  items = Item.all

  <span class="hljs-comment"># We'll bump this up later to 1_000_000 in order to see</span>
  <span class="hljs-comment"># the perf issues come up.</span>
  item_attributes = <span class="hljs-number">100_000</span>.times.map <span class="hljs-keyword">do</span>
    {
      <span class="hljs-symbol">attribute_name:</span> Faker::Lorem.word,
      <span class="hljs-symbol">attribute_value:</span> Faker::Lorem.word,
      <span class="hljs-symbol">item_id:</span> items.sample.id
    }
  <span class="hljs-keyword">end</span>

  item_attributes.each_slice(<span class="hljs-number">1000</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|batch|</span>
    ItemAttribute.insert_all(batch)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

create_records(<span class="hljs-string">'denormalized items'</span>) <span class="hljs-keyword">do</span>
  items_with_associations = Item.includes(<span class="hljs-symbol">:category</span>, <span class="hljs-symbol">:supplier</span>, <span class="hljs-symbol">:warehouse</span>)

  denormalized_items_attributes = []

  items_with_associations.find_each(<span class="hljs-symbol">batch_size:</span> <span class="hljs-number">1000</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|item|</span>
    denormalized_items_attributes &lt;&lt; {
      <span class="hljs-symbol">name:</span> item.name,
      <span class="hljs-symbol">item_id:</span> item.id,
      <span class="hljs-symbol">category_name:</span> item.category.name,
      <span class="hljs-symbol">category_id:</span> item.category.id,
      <span class="hljs-symbol">supplier_name:</span> item.supplier.name,
      <span class="hljs-symbol">supplier_id:</span> item.supplier.id,
      <span class="hljs-symbol">warehouse_name:</span> item.warehouse.name,
      <span class="hljs-symbol">warehouse_id:</span> item.warehouse.id,
      <span class="hljs-symbol">created_at:</span> DateTime.now,
      <span class="hljs-symbol">updated_at:</span> DateTime.now
    }
  <span class="hljs-keyword">end</span>

  denormalized_items_attributes.each_slice(<span class="hljs-number">1000</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|batch|</span>
    ItemDenormalized.insert_all(batch)
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<p>This seeding script helps create records for all our entities. You can fine tune the script to create more or less records to stress test the architecture. Which is exactly what we're going to to do in a few moments.</p>
<p>Now, remember, this will be running on your local computer so we’re not testing production level resources here. Hopefully, you can have a production level environment to experiment with different strategies, but the point here isn't to replicate production - but get a good understanding of the complexities of working with highly normalized architectures.</p>
<p>When we run the seeds, we’ll get the following logs:</p>
<pre><code class="lang-sh">bundle <span class="hljs-built_in">exec</span> rails db:seed
Truncating database...
Database truncated.
Creating categories.
Categories created. 3.226257999893278
Creating suppliers.
Suppliers created. 0.1299410001374781
Creating warehouses.
Warehouses created. 4.184017000021413
Creating items.
Items created. 7.629256000043824
Creating item attributes.
Item attributes created. 59.715396999847144
Creating denormalized items.
Denormalized items created. 12.066422999836504
</code></pre>
<p>Alright, let’s start running some queries.</p>
<h2 id="heading-performance-what-performance">Performance? What performance?!</h2>
<p>So, let’s say I want all items except those from McDermott-Casper, a supplier who has gone bankrupt. Also, I don’t want items that have the attributes enim and/or modi associated to them:</p>
<p>We can write a query, with ActiveRecord, pretty easily like this:</p>
<pre><code class="lang-ruby">excluded_suppliers =
  Supplier
    .select(<span class="hljs-string">'id'</span>)
    .where(<span class="hljs-symbol">name:</span> <span class="hljs-string">"McDermott-Casper"</span>)
    .to_sql

excluded_attributes =
  ItemAttribute
    .select(<span class="hljs-symbol">:item_id</span>)
    .where(<span class="hljs-symbol">attribute_name:</span> [<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>])
    .to_sql

Item
  .distinct
  .select(<span class="hljs-string">'items.id, items.name, categories.name AS category_name, suppliers.name AS supplier_name, warehouses.name AS warehouse_name'</span>)
  .joins(<span class="hljs-symbol">:category</span>, <span class="hljs-symbol">:supplier</span>, <span class="hljs-symbol">:warehouse</span>)
  .left_outer_joins(<span class="hljs-symbol">:item_attributes</span>)
  .where(<span class="hljs-string">"items.supplier_id NOT IN (<span class="hljs-subst">#{excluded_suppliers}</span>)"</span>)
  .where(<span class="hljs-string">"items.id NOT IN(<span class="hljs-subst">#{excluded_attributes}</span>)"</span>)
  .to_a
</code></pre>
<p>The conditions to exclude items based on our scenario are utilized in the <code>WHERE</code> conditionals as embedded subqueries, while we join category, supplier, warehouse and (left outer join) item attributes to ensure that we retrieve only the matching items of our condition.</p>
<p>Alright, let’s test this out:</p>
<pre><code class="lang-ruby">bundle exec rails c
Loading development environment (Rails <span class="hljs-number">7.1</span>.<span class="hljs-number">3.4</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">001</span>* excluded_suppliers =
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">002</span>&gt;   Supplier
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">003</span>&gt;     .select(<span class="hljs-string">'id'</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">004</span>&gt;     .where(<span class="hljs-symbol">name:</span> <span class="hljs-string">"McDermott-Casper"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">005</span>&gt;     .to_sql
=&gt; <span class="hljs-string">"SELECT \"suppliers\".\"id\" FROM \"suppliers\" WHERE \"suppliers\".\"name\" = 'McDermott-Casper'"</span>
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">006</span>* excluded_attributes =
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">007</span>&gt;   ItemAttribute
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">00</span>8&gt;     .select(<span class="hljs-symbol">:item_id</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">00</span>9&gt;     .where(<span class="hljs-symbol">attribute_name:</span> [<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>])
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">010</span>&gt;     .to_sql
=&gt; <span class="hljs-string">"SELECT \"item_attributes\".\"item_id\" FROM \"item_attributes\" WHERE \"item_attributes\".\"attribute_name\" IN ('enim', 'modi')"</span>
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">011</span>&gt; Item
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">012</span>&gt;   .distinct
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">013</span>&gt;   .select(<span class="hljs-string">'items.id, items.name, categories.name AS category_name, suppliers.name AS supplier_name, warehouses.name AS warehouse_name'</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">014</span>&gt;   .joins(<span class="hljs-symbol">:category</span>, <span class="hljs-symbol">:supplier</span>, <span class="hljs-symbol">:warehouse</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">015</span>&gt;   .left_outer_joins(<span class="hljs-symbol">:item_attributes</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">016</span>&gt;   .where(<span class="hljs-string">"items.supplier_id NOT IN (<span class="hljs-subst">#{excluded_suppliers}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">017</span>&gt;   .where(<span class="hljs-string">"items.id NOT IN(<span class="hljs-subst">#{excluded_attributes}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">01</span>8&gt;   .to_a
  Item Load (<span class="hljs-number">535.5</span>ms)  SELECT DISTINCT items.id, items.name, categories.name AS category_name, suppliers.name AS supplier_name, warehouses.name AS warehouse_name FROM <span class="hljs-string">"items"</span> INNER JOIN <span class="hljs-string">"categories"</span> ON <span class="hljs-string">"categories"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"category_id"</span> INNER JOIN <span class="hljs-string">"suppliers"</span> ON <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"supplier_id"</span> INNER JOIN <span class="hljs-string">"warehouses"</span> ON <span class="hljs-string">"warehouses"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"warehouse_id"</span> LEFT OUTER JOIN <span class="hljs-string">"item_attributes"</span> ON <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"item_id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"id"</span> WHERE (items.supplier_id NOT IN (SELECT <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"id"</span> FROM <span class="hljs-string">"suppliers"</span> WHERE <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"name"</span> = <span class="hljs-string">'McDermott-Casper'</span>)) AND (items.id NOT IN(SELECT <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"item_id"</span> FROM <span class="hljs-string">"item_attributes"</span> WHERE <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"attribute_name"</span> IN (<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>)))
=&gt;
</code></pre>
<p>Awesome! We’re at sub-second fetches.</p>
<p>Alright. Let’s see what happens when we bump up the number of attributes in the system to…lets say a million. We can do this by running the following code, extracted from the seed script:</p>
<pre><code class="lang-ruby">  items = Item.all

  <span class="hljs-comment"># We'll bump this up later to 1_000_000 in order to see</span>
  <span class="hljs-comment"># the perf issues come up.</span>
  item_attributes = <span class="hljs-number">900_000</span>.times.map <span class="hljs-keyword">do</span>
    {
      <span class="hljs-symbol">attribute_name:</span> Faker::Lorem.word,
      <span class="hljs-symbol">attribute_value:</span> Faker::Lorem.word,
      <span class="hljs-symbol">item_id:</span> items.sample.id
    }
  <span class="hljs-keyword">end</span>

  item_attributes.each_slice(<span class="hljs-number">1000</span>) <span class="hljs-keyword">do</span> <span class="hljs-params">|batch|</span>
    ItemAttribute.insert_all(batch)
  <span class="hljs-keyword">end</span>
</code></pre>
<p>Now keep in mind that the above had 1,187 item attribute records that matched enim or modi.</p>
<pre><code class="lang-ruby">irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">001</span>* excluded_suppliers =
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">002</span>&gt;   Supplier
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">003</span>&gt;     .select(<span class="hljs-string">'id'</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">004</span>&gt;     .where(<span class="hljs-symbol">name:</span> <span class="hljs-string">"McDermott-Casper"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">005</span>&gt;     .to_sql
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">006</span>&gt; 
=&gt; <span class="hljs-string">"SELECT \"suppliers\".\"id\" FROM \"suppliers\" WHERE \"suppliers\".\"name\" = 'McDermott-Casper'"</span>
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">007</span>* excluded_attributes =
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">00</span>8&gt;   ItemAttribute
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">00</span>9&gt;     .select(<span class="hljs-symbol">:item_id</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">010</span>&gt;     .where(<span class="hljs-symbol">attribute_name:</span> [<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>])
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">011</span>&gt;     .to_sql
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">012</span>&gt; 
=&gt; <span class="hljs-string">"SELECT \"item_attributes\".\"item_id\" FROM \"item_attributes\" WHERE \"item_attributes\".\"attribute_name\" IN ('enim', 'modi')"</span>
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">013</span>&gt; Item
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">014</span>&gt;   .distinct
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">015</span>&gt;   .select(<span class="hljs-string">'items.id, items.name, categories.name AS category_name, suppliers.name AS supplier_name, warehouses.name AS warehouse_name'</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">016</span>&gt;   .joins(<span class="hljs-symbol">:category</span>, <span class="hljs-symbol">:supplier</span>, <span class="hljs-symbol">:warehouse</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">017</span>&gt;   .left_outer_joins(<span class="hljs-symbol">:item_attributes</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">01</span>8&gt;   .where(<span class="hljs-string">"items.supplier_id NOT IN (<span class="hljs-subst">#{excluded_suppliers}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">01</span>9&gt;   .where(<span class="hljs-string">"items.id NOT IN(<span class="hljs-subst">#{excluded_attributes}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">020</span>&gt;   .to_a
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">021</span>&gt; 
  Item Load (<span class="hljs-number">3002.4</span>ms)  SELECT DISTINCT items.id,
</code></pre>
<p>Whoa! Ok. Now we’re at 3s.</p>
<p>The problem will only get worse as more items are added to the system over time and in relation item_attributes will continue to impact this specific query. When 900,000 more attributes were added there was an increase of the number of records that matched <code>enim</code> or <code>modi</code>. In fact we went from 1,187 to 12,154 records.</p>
<p>This kind of scale is completely normal and really shouldn’t be unexpected. As the number of attributes for items can increase significantly over time in an inventory management system for all sorts of reasons. Ok, so more records were added - of course performance would be impacted. What exactly is happening?</p>
<h2 id="heading-is-normalization-really-the-issue-here">Is normalization really the issue here?</h2>
<p>I’m going to remove the joins to categories and warehouses:</p>
<pre><code class="lang-ruby">irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">02</span>9&gt; Item
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">030</span>&gt;   .distinct
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">031</span>&gt;   .select(<span class="hljs-string">'items.id, items.name, suppliers.name AS supplier_name'</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">032</span>&gt;   .joins(<span class="hljs-symbol">:supplier</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">033</span>&gt;   .left_outer_joins(<span class="hljs-symbol">:item_attributes</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">034</span>&gt;   .where(<span class="hljs-string">"items.supplier_id NOT IN (<span class="hljs-subst">#{excluded_suppliers}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">035</span>&gt;   .where(<span class="hljs-string">"items.id NOT IN(<span class="hljs-subst">#{excluded_attributes}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">036</span>&gt;   .to_a
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">037</span>&gt;
  Item Load (<span class="hljs-number">1938.4</span>ms)  SELECT DISTINCT items.id, items.name, suppliers.name AS supplier_name FROM <span class="hljs-string">"items"</span> INNER JOIN <span class="hljs-string">"suppliers"</span> ON <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"supplier_id"</span> LEFT OUTER JOIN <span class="hljs-string">"item_attributes"</span> ON <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"item_id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"id"</span> WHERE (items.supplier_id NOT IN (SELECT <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"id"</span> FROM <span class="hljs-string">"suppliers"</span> WHERE <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"name"</span> = <span class="hljs-string">'McDermott-Casper'</span>)) AND (items.id NOT IN(SELECT <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"item_id"</span> FROM <span class="hljs-string">"item_attributes"</span> WHERE <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"attribute_name"</span> IN (<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>)))
=&gt;
</code></pre>
<p>Ok, so yeah, we get a ~30% improvement just removing the join. Let's run an explain on these and try to understand what's going on.</p>
<pre><code class="lang-sql">Unique  (cost=80266.89..84016.89 rows=250000 width=99)
  -&gt;  Sort  (cost=80266.89..80891.89 rows=250000 width=99)
        Sort Key: items.id, items.name, categories.name, suppliers.name, warehouses.name
        -&gt;  Hash Join  (cost=20105.00..44177.93 rows=250000 width=99)
              Hash Cond: (items.warehouse_id = warehouses.id)
              -&gt;  Hash Join  (cost=20066.50..43480.40 rows=250000 width=89)
                    Hash Cond: (items.supplier_id = suppliers.id)
                    -&gt;  Hash Join  (cost=20030.63..42785.86 rows=250000 width=78)
                          Hash Cond: (items.category_id = categories.id)
                          -&gt;  Hash Right Join  (cost=19998.80..42094.91 rows=250000 width=54)
                                Hash Cond: (item_attributes.item_id = items.id)
                                -&gt;  Seq Scan on item_attributes  (cost=0.00..19471.00 rows=1000000 width=8)
                                -&gt;  Hash  (cost=19686.30..19686.30 rows=25000 width=54)
                                      -&gt;  Seq Scan on items  (cost=16933.30..19686.30 rows=25000 width=54)
                                            Filter: ((NOT (hashed SubPlan 1)) AND (NOT (hashed SubPlan 2)))
                                            SubPlan 1
                                              -&gt;  Seq Scan on suppliers suppliers_1  (cost=0.00..24.38 rows=1 width=8)
"                                                    Filter: ((name)::text = 'McDermott-Casper'::text)"
                                            SubPlan 2
                                              -&gt;  Gather  (cost=1000.00..16878.93 rows=11996 width=8)
                                                    Workers Planned: 2
                                                    -&gt;  Parallel Seq Scan on item_attributes item_attributes_1  (cost=0.00..14679.33 rows=4998 width=8)
"                                                          Filter: ((attribute_name)::text = ANY ('{enim,modi}'::text[]))"
                          -&gt;  Hash  (cost=19.70..19.70 rows=970 width=40)
                                -&gt;  Seq Scan on categories  (cost=0.00..19.70 rows=970 width=40)
                    -&gt;  Hash  (cost=21.50..21.50 rows=1150 width=27)
                          -&gt;  Seq Scan on suppliers  (cost=0.00..21.50 rows=1150 width=27)
              -&gt;  Hash  (cost=26.00..26.00 rows=1000 width=26)
                    -&gt;  Seq Scan on warehouses  (cost=0.00..26.00 rows=1000 width=26)
</code></pre>
<p>The plan above is telling us the output of each join is funneled into the next one:</p>
<p>(items &lt;&gt; warehouses) -&gt; (items &lt;&gt; suppliers) -&gt; (items &lt;&gt; categories)</p>
<p>Because of the multiple joins, we essentially increase the performance impact as more data is spread out across your database, e.g. normalization.</p>
<p>Now, let’s look at the plan after we remove the joins:</p>
<pre><code class="lang-sql">Unique  (cost=73750.91..76250.91 rows=250000 width=49)
  -&gt;  Sort  (cost=73750.91..74375.91 rows=250000 width=49)
        Sort Key: items.id, items.name, suppliers.name
        -&gt;  Hash Join  (cost=20034.68..42789.45 rows=250000 width=49)
              Hash Cond: (items.supplier_id = suppliers.id)
              -&gt;  Hash Right Join  (cost=19998.80..42094.91 rows=250000 width=38)
                    Hash Cond: (item_attributes.item_id = items.id)
                    -&gt;  Seq Scan on item_attributes  (cost=0.00..19471.00 rows=1000000 width=8)
                    -&gt;  Hash  (cost=19686.30..19686.30 rows=25000 width=38)
                          -&gt;  Seq Scan on items  (cost=16933.30..19686.30 rows=25000 width=38)
                                Filter: ((NOT (hashed SubPlan 1)) AND (NOT (hashed SubPlan 2)))
                                SubPlan 1
                                  -&gt;  Seq Scan on suppliers suppliers_1  (cost=0.00..24.38 rows=1 width=8)
"                                        Filter: ((name)::text = 'McDermott-Casper'::text)"
                                SubPlan 2
                                  -&gt;  Gather  (cost=1000.00..16878.93 rows=11996 width=8)
                                        Workers Planned: 2
                                        -&gt;  Parallel Seq Scan on item_attributes item_attributes_1  (cost=0.00..14679.33 rows=4998 width=8)
"                                              Filter: ((attribute_name)::text = ANY ('{enim,modi}'::text[]))"
              -&gt;  Hash  (cost=21.50..21.50 rows=1150 width=27)
                    -&gt;  Seq Scan on suppliers  (cost=0.00..21.50 rows=1150 width=27)
</code></pre>
<p>Ok, so we get a better query plan. Less joins, less data to scan and therefore more performance. However, doing this won't meet the requirements. Remember, the report needs the names of the associated suppliers and warehouses. Let's see what happens when we denormalize the data and simplify the lookup process.</p>
<pre><code class="lang-ruby">irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">074</span>* excluded_suppliers =
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">075</span>&gt;   Supplier
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">076</span>&gt;     .select(<span class="hljs-string">'id'</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">077</span>&gt;     .where(<span class="hljs-symbol">name:</span> <span class="hljs-string">"McDermott-Casper"</span>)
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">07</span>8&gt;     .to_sql
irb(main)<span class="hljs-symbol">:</span><span class="hljs-number">07</span>9&gt; 
irb(main)<span class="hljs-symbol">:</span>08<span class="hljs-number">0</span>* excluded_attributes =
irb(main)<span class="hljs-symbol">:</span>081&gt;   ItemAttribute
irb(main)<span class="hljs-symbol">:</span>082&gt;     .select(<span class="hljs-symbol">:item_id</span>)
irb(main)<span class="hljs-symbol">:</span>083&gt;     .where(<span class="hljs-symbol">attribute_name:</span> [<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>])
irb(main)<span class="hljs-symbol">:</span>084&gt;     .to_sql
irb(main)<span class="hljs-symbol">:</span>085&gt; 
irb(main)<span class="hljs-symbol">:</span>086&gt; ItemDenormalized
irb(main)<span class="hljs-symbol">:</span>087&gt;   .distinct
irb(main)<span class="hljs-symbol">:</span>088&gt;   .select(<span class="hljs-string">'items_denormalized.id as id, items_denormalized.category_name as category_name, items_denormalized.supplier_name as supplier_name, items_denormalized.warehouse_name as warehouse_name'</span>)
irb(main)<span class="hljs-symbol">:</span>089&gt;   .joins(<span class="hljs-symbol">:supplier</span>)
irb(main)<span class="hljs-symbol">:</span>09<span class="hljs-number">0</span>&gt;   .left_outer_joins(<span class="hljs-symbol">:item_attributes</span>)
irb(main)<span class="hljs-symbol">:</span>091&gt;   .where(<span class="hljs-string">"items_denormalized.supplier_id NOT IN (<span class="hljs-subst">#{excluded_suppliers}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span>092&gt;   .where(<span class="hljs-string">"items_denormalized.item_id NOT IN(<span class="hljs-subst">#{excluded_attributes}</span>)"</span>)
irb(main)<span class="hljs-symbol">:</span>093&gt;   .to_a
irb(main)<span class="hljs-symbol">:</span>094&gt; 
  ItemDenormalized Load (<span class="hljs-number">1107.3</span>ms)  SELECT DISTINCT items_denormalized.id as id,
</code></pre>
<p>In this example, the lookup on the denormalized table performed similarly to when we removed the joins (1107.3ms v. 1938.4ms). The difference is that we have the category and warehouse names. Denormalization does introduce multiple complexities that need to be handled; such as redundancy and integrity of the data, e.g. what happens when categories are updated? or when warehouses are deleted?</p>
<p>Putting that aside though, we see that denormalization handles certain scenarios well when it comes to performance. We should consider it's benefits when building applications that will inevitably need to scale. In our example above, we can see with just a million records, we start to run into some performance bottlenecks.</p>
<h2 id="heading-performance-bottlenecks">Performance Bottlenecks</h2>
<p>Let's think through what bottlenecks start to come into play after running through the examples above.</p>
<h3 id="heading-complex-queries">Complex Queries</h3>
<p>Highly normalized schemas often require complex queries with multiple joins, which can be slow and resource-intensive.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">DISTINCT</span>
    items.id,
    items.name,
    categories.name <span class="hljs-keyword">AS</span> category_name,
    suppliers.name <span class="hljs-keyword">AS</span> supplier_name,
    warehouses.name <span class="hljs-keyword">AS</span> warehouse_name
<span class="hljs-keyword">FROM</span>
    <span class="hljs-string">"items"</span>
    <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> <span class="hljs-string">"categories"</span> <span class="hljs-keyword">ON</span> <span class="hljs-string">"categories"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"category_id"</span>
    <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> <span class="hljs-string">"suppliers"</span> <span class="hljs-keyword">ON</span> <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"supplier_id"</span>
    <span class="hljs-keyword">INNER</span> <span class="hljs-keyword">JOIN</span> <span class="hljs-string">"warehouses"</span> <span class="hljs-keyword">ON</span> <span class="hljs-string">"warehouses"</span>.<span class="hljs-string">"id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"warehouse_id"</span>
    <span class="hljs-keyword">LEFT</span> <span class="hljs-keyword">OUTER</span> <span class="hljs-keyword">JOIN</span> <span class="hljs-string">"item_attributes"</span> <span class="hljs-keyword">ON</span> <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"item_id"</span> = <span class="hljs-string">"items"</span>.<span class="hljs-string">"id"</span>
<span class="hljs-keyword">WHERE</span> (items.supplier_id <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">IN</span>(
        <span class="hljs-keyword">SELECT</span>
            <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"id"</span> <span class="hljs-keyword">FROM</span> <span class="hljs-string">"suppliers"</span>
        <span class="hljs-keyword">WHERE</span>
            <span class="hljs-string">"suppliers"</span>.<span class="hljs-string">"name"</span> = <span class="hljs-string">'McDermott-Casper'</span>))
    <span class="hljs-keyword">AND</span>(items.id <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">IN</span>(
            <span class="hljs-keyword">SELECT</span>
                <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"item_id"</span> <span class="hljs-keyword">FROM</span> <span class="hljs-string">"item_attributes"</span>
            <span class="hljs-keyword">WHERE</span>
                <span class="hljs-string">"item_attributes"</span>.<span class="hljs-string">"attribute_name"</span> <span class="hljs-keyword">IN</span>(<span class="hljs-string">'enim'</span>, <span class="hljs-string">'modi'</span>)));
</code></pre>
<p>I wouldn't consider the above too complex, however, the conditions that execute subqueries can start to get complex when joining on joins. This happens a lot in large scale applications that have evolved over time. Again, normalization is great in an ideal world - but it is also important to understand what other complexities it introduces.</p>
<h3 id="heading-increased-io-operations"><strong>Increased I/O Operations</strong></h3>
<p>Each table lookup can lead to additional I/O operations, slowing down the overall query performance. When we start to talk through IO operations in the database, it's important to know, high level, why this is an important part of the puzzle. So let's dive into some issues that come up at scale.</p>
<p><strong>Read/Write:</strong> Each join that involves disk-based temporary tables or large data sets will increase the number of disk reads and writes. This can cause a significant I/O load, especially in applications where the behavior is quite active (jobs, high traffic, etc.).</p>
<p><strong>Buffer Pool Pressure:</strong> Joins can put pressure on the MySQL buffer pool, especially with larger data sets. When the buffer pool is full, MySQL has to <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/memory-use.html#:~:text=A%20buffer%20pool%20that%20is%20too%20small%20may%20cause%20excessive%20churning%20as%20pages%20are%20flushed%20from%20the%20buffer%20pool%20only%20to%20be%20required%20again%20a%20short%20time%20later.">evict pages</a> to make room for new data, causing additional disk I/O.</p>
<p><strong>Temporary Tables:</strong>  MySQL may create temporary tables to hold intermediate results during complex join operations. <a target="_blank" href="https://dev.mysql.com/blog-archive/how-to-force-temporary-tables-to-be-created-on-disk-directly/#:~:text=By%20default%2C%20MySQL%20creates%20in%2Dmemory%20temporary%20tables%20in%20the%20MEMORY%20engine.%20The%20maximum%20size%20for%20in%2Dmemory%20temporary%20tables%20is%20the%20minimum%20of%20the%20tmp_table_size%20and%20max_heap_table_size.%20If%20the%20result%20set%20gest%20bigger%20than%20this%20threshold%2C%20MySQL%20will%20overflow%20to%2Ddisk%20based%20temporary%20tables.">These temporary tables can be stored in memory or on disk, depending on their size</a>. Disk-based temporary tables increase I/O operations, leading to slower performance.</p>
<h3 id="heading-lock-contention"><strong>Lock Contention</strong></h3>
<p>In a highly concurrent environment, frequent access and updates across multiple tables can lead to lock contention and further degrade performance.</p>
<p><strong>Multiple Joins</strong></p>
<p>• <strong>Lock Types</strong>: MySQL uses different types of locks (e.g., <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/glossary.html#glos_shared_lock">shared</a>, <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/glossary.html#glos_exclusive_lock">exclusive</a>) depending on the operation. Complex queries with multiple joins can require various locks, leading to contention if different parts of the query need the same resources.</p>
<p>• <strong>Row-Level vs. Table-Level Locks</strong>: InnoDB uses <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/internal-locking.html#internal-row-level-locking">row-level locking</a>, which is generally more efficient than <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/internal-locking.html#internal-table-level-locking">table-level locking</a> used by MyISAM. However, even row-level locks can cause contention if multiple transactions try to modify the same rows simultaneously.</p>
<p><strong>Joins on Joins</strong></p>
<p>• <strong>Increased Lock Duration</strong>: Queries involving joins on joins often take longer to execute. The longer a transaction holds locks, the higher the chance of contention with other transactions.</p>
<p>• <strong>Lock Escalation</strong>: Although InnoDB uses row-level locking, high contention can sometimes cause lock escalation, where the database engine escalates to table-level locks to manage the contention, leading to broader performance issues. <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-locks-set.html#:~:text=If%20you%20have%20no%20indexes,scan%20more%20rows%20than%20necessary.">This is typically due to non-existent and/or lacking indexes</a>.</p>
<p><strong>Lock Waits and Deadlocks</strong></p>
<p>• <strong>Lock Waits</strong>: When a transaction needs a lock held by another transaction, it must wait, leading to increased query execution time and potential timeouts.</p>
<p>• <strong>Deadlocks</strong>: Complex queries with multiple joins increase the risk of deadlocks, where two or more transactions are waiting for each other’s locks, causing the <a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-deadlocks.html">database to automatically roll back</a> one of the transactions to resolve the deadlock, typically the "victim" is rolled back.</p>
<h2 id="heading-strategies-for-optimization">Strategies for Optimization</h2>
<p>To mitigate performance issues in highly normalized architectures, consider the following strategies:</p>
<h3 id="heading-denormalization">Denormalization</h3>
<p>The process for denormalizing data involves adding redundant data to tables to reduce the number of joins required. While this increases storage requirements and the risk of data anomalies, it can significantly improve read performance.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> i.id, i.name, i.category_name, i.supplier_name, i.warehouse_name, i.attribute_value
<span class="hljs-keyword">FROM</span> items_denormalized i
<span class="hljs-keyword">WHERE</span> i.id = ?
</code></pre>
<p>In this example, the <code>items_denormalized</code> table combines data from the <code>categories</code>, <code>suppliers</code>, <code>warehouses</code>, and <code>item_attributes</code> tables, eliminating the need for multiple joins.</p>
<h3 id="heading-indexing">Indexing</h3>
<p>Proper indexing can dramatically improve query performance. Ensure that all columns used in joins and WHERE clauses are indexed. Remember, an index is super important to prevent full table locks. Keep in mind, that even this will not help if temporary tables are created with your joins, which will NOT have indexes.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_items_id <span class="hljs-keyword">ON</span> items(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_categories_id <span class="hljs-keyword">ON</span> categories(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_suppliers_id <span class="hljs-keyword">ON</span> suppliers(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_warehouses_id <span class="hljs-keyword">ON</span> warehouses(<span class="hljs-keyword">id</span>);
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_item_attributes_item_id <span class="hljs-keyword">ON</span> item_attributes(item_id);
</code></pre>
<h3 id="heading-caching">Caching</h3>
<p>Implement caching mechanisms to store frequently accessed data in memory, reducing the need for repeated database queries. There are multiple strategies for implementing caching, which will be covered in a different post, but these strategies can range from utilizing summary tables, to integrating different technologies that can store results temporarily.</p>
<pre><code class="lang-ruby"><span class="hljs-comment"># Example using Ruby on Rails with Redis cache</span>
item = Rails.cache.fetch(<span class="hljs-string">"item_<span class="hljs-subst">#{id}</span>"</span>, <span class="hljs-symbol">expires_in:</span> <span class="hljs-number">12</span>.hours) <span class="hljs-keyword">do</span>
  Item.includes(<span class="hljs-symbol">:category</span>, <span class="hljs-symbol">:supplier</span>, <span class="hljs-symbol">:warehouse</span>, <span class="hljs-symbol">:item_attributes</span>).find(id)
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-query-optimization">Query Optimization</h3>
<p><a target="_blank" href="https://dev.mysql.com/blog-archive/mysql-explain-analyze/">Analyze</a> and optimize your queries to ensure they are as efficient as possible. Use tools like MySQL’s <code>EXPLAIN ANALYZE</code> statement to understand the execution plan and identify bottlenecks.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">EXPLAIN</span> <span class="hljs-keyword">SELECT</span> i.id, i.name, c.name <span class="hljs-keyword">AS</span> <span class="hljs-keyword">category</span>, s.name <span class="hljs-keyword">AS</span> supplier, w.name <span class="hljs-keyword">AS</span> warehouse, ia.attribute_value
<span class="hljs-keyword">FROM</span> items i
<span class="hljs-keyword">JOIN</span> categories c <span class="hljs-keyword">ON</span> i.category_id = c.id
<span class="hljs-keyword">JOIN</span> suppliers s <span class="hljs-keyword">ON</span> i.supplier_id = s.id
<span class="hljs-keyword">JOIN</span> warehouses w <span class="hljs-keyword">ON</span> i.warehouse_id = w.id
<span class="hljs-keyword">JOIN</span> item_attributes ia <span class="hljs-keyword">ON</span> i.id = ia.item_id
<span class="hljs-keyword">WHERE</span> i.id = <span class="hljs-number">1</span>;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Normalization is a powerful technique for maintaining data integrity, but it can lead to performance challenges in large-scale applications. Knowing the tradeoffs here can help you scale your application in the long term, considering denormalization as just another strategy to help scale. If denormalization is not favorable; consider reviewing indices (including composites), result caching and query optimization to improve performance. Thank you for reading and please reach out if you have any questions!</p>
<h1 id="heading-references">References</h1>
<p><a target="_blank" href="https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description">Microsoft 365 - Description of the database normalization basics</a></p>
<p><a target="_blank" href="https://blog.codinghorror.com/maybe-normalizing-isnt-normal/">Coding Horror - Maybe Normalizing Isn't Normal</a></p>
<p><a target="_blank" href="https://www.informit.com/articles/article.aspx?p=2755707&amp;seqNum=3">informIT - When You Can't Change a SQL Database Design</a></p>
<p><a target="_blank" href="https://blog.purestorage.com/purely-educational/denormalized-vs-normalized-data/">PureStorage - Denormalized vs. Normalized Data</a>.</p>
<p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-buffer-pool.html">MySQL - Buffer Pool</a></p>
<p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-disk-io.html">MySQL - InnoDB Disk I/O</a></p>
<p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/internal-temporary-tables.html">MySQL - Internal Temporary Table Use in MySQL</a></p>
<p><a target="_blank" href="https://dev.mysql.com/doc/refman/8.4/en/innodb-locks-set.html">MySQL - Locks Set by Different SQL Statements in InnoDB</a></p>
<p><a target="_blank" href="https://www.percona.com/blog/understanding-hash-joins-in-mysql-8/">Percona - Understanding Hash Joins in MySQL 8</a></p>
<p><a target="_blank" href="https://www.percona.com/blog/horizontal-scaling-in-mysql-sharding-followup/">Percona - Horizontal Scaling in MySQL – Sharding Followup</a></p>
<p><a target="_blank" href="https://planetscale.com/blog/how-to-scale-your-database-and-when-to-shard-mysql">PlanetScale - How to Scale your Database and when to Shard MySQL</a></p>
<p><a target="_blank" href="https://github.com/sujeet-agrahari/awesome-database-design">Awesome - Database Design</a></p>
<p><a target="_blank" href="https://github.com/shlomi-noach/awesome-mysql#readme">Awesome - MySQL</a></p>
]]></content:encoded></item><item><title><![CDATA[Chart.js + Turbo Stimulus in Rails 7]]></title><description><![CDATA[Integrate Chart.js with Turbo Stimulus in Rails 7 for lightweight, efficient data visualization in your application. Learn the setup in this guide.]]></description><link>https://alvincrespo.hashnode.dev/chartjs-turbo-stimulus-in-rails-7</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/chartjs-turbo-stimulus-in-rails-7</guid><category><![CDATA[chartjs]]></category><category><![CDATA[visualization]]></category><category><![CDATA[stimulus]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[npm]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 03 Jan 2022 18:53:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/kE8-rUKjtQU/upload/eead75eeed385015503bd6bef03ad493.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-background">Background</h2>
<p>Over the winter break I updated our gardening app, Jardim.io, to Rails 7. It was a breeze! However, we were still reliant on <a target="_blank" href="https://webpack.js.org/">webpack</a> because we had a <a target="_blank" href="https://reactjs.org/">React</a> application that utilized <a target="_blank" href="https://nivo.rocks/">nivo</a> for our charting solution.</p>
<p>Webpack and React are overly complex and difficult to maintain. We want our stack to be <a target="_blank" href="https://www.youtube.com/watch?v=PtxZvFnL2i0">lean and effective</a>, so we're migrating to <a target="_blank" href="https://github.com/evanw/esbuild">esbuild</a>.</p>
<p>So as part of this work, I needed to migrate to another solution. That's where <a target="_blank" href="https://www.chartjs.org/">Chart.js</a> comes in!</p>
<p>Why Chart.js?</p>
<ul>
<li><p>Fits our needs (simplicity)</p>
</li>
<li><p>Extensive <a target="_blank" href="https://github.com/chartjs/awesome">ecosystem</a></p>
</li>
<li><p>Code is easy to read and contribute</p>
</li>
</ul>
<hr />
<h2 id="heading-dependencies">Dependencies</h2>
<p>All we need to do is add <code>chart.js</code> as a dependency:</p>
<pre><code class="lang-bash">yarn add chart.js
</code></pre>
<p>If you're using NPM:</p>
<pre><code class="lang-bash">npm i chart.js
</code></pre>
<hr />
<h2 id="heading-the-data-template-view">The Data / Template / View</h2>
<p>In our app, Jardim.io, we are taking "biometric" data of plants and representing them in the chart.</p>
<p>Yes, we can create an API endpoint, get some JSON via AJAX and do a bunch of fancy stuff. But, I'm not going to do that. It adds a ton of complexity I really don't care about. What complexity? Well, authorization is one. I don't care about this right now, we are creating a traditional monolith - so we already know who is requesting what.</p>
<p>So what do we do? Drop that data in the markup itself!</p>
<h3 id="heading-embedding-data">Embedding Data</h3>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"metrics"</span> <span class="hljs-attr">data-metrics</span>=<span class="hljs-string">"&lt;%=</span></span></span><span class="ruby"> @metrics.to_json </span><span class="xml"><span class="hljs-tag"><span class="hljs-string">%&gt;"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<p>You can place this anywhere on your page. In fact, you may want to use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template">template</a> instead. Either way, the idea is to embed the data on to the page, and let JS pick it up and use it. Eliminating indirection with an API call and creating more maintenance for yourself and your team.</p>
<p>NOTE: <code>@metrics</code> is an instance variable created in the controller's action.</p>
<h3 id="heading-the-chart-elements">The Chart Element(s)</h3>
<pre><code class="lang-erb"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"chart-container"</span> <span class="hljs-attr">data-controller</span>=<span class="hljs-string">"chart"</span> <span class="hljs-attr">data-metric</span>=<span class="hljs-string">"&lt;%=</span></span></span><span class="ruby"> metric </span><span class="xml"><span class="hljs-tag"><span class="hljs-string">%&gt;"</span> <span class="hljs-attr">data-unit</span>=<span class="hljs-string">"&lt;%=</span></span></span><span class="ruby"> unit </span><span class="xml"><span class="hljs-tag"><span class="hljs-string">%&gt;"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">canvas</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"YOUR_ELEMENT_ID"</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"400"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"400"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">canvas</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
<p>This is what will be used to instantiate and style the chart. This is done through <code>data-controller</code> and is an API to Turbo Stimulus, for more information check out the documenation <a target="_blank" href="https://stimulus.hotwired.dev/reference/lifecycle-callbacks#targets">here</a>.</p>
<p>That's it for the template/view. Let's start writing some JavaScript.</p>
<hr />
<h2 id="heading-the-stimulus-controller">The Stimulus Controller</h2>
<p>Our chart will be instantiated by a "controller". If you're not familiar with Stimulus' controller class, read the docs <a target="_blank" href="https://stimulus.hotwired.dev/reference/controllers">here</a>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// app/packs/controllers/chart_controller.js</span>
<span class="hljs-keyword">import</span> { Controller } <span class="hljs-keyword">from</span> <span class="hljs-string">"@hotwired/stimulus"</span>;
<span class="hljs-keyword">import</span> Chart <span class="hljs-keyword">from</span> <span class="hljs-string">'chart.js/auto'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChartController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
  <span class="hljs-keyword">static</span> ELEMENT_ID = <span class="hljs-string">'YOUR_ELEMENT_ID'</span>;
  <span class="hljs-keyword">static</span> DEFAULT_OPTIONS = { <span class="hljs-attr">responsive</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">maintainAspectRatio</span>: <span class="hljs-literal">false</span> };

  connect() {
    <span class="hljs-built_in">this</span>.render();
  }

  render() {
    <span class="hljs-comment">// TODO</span>
  }
}
</code></pre>
<p>This is the basic scaffold of our controller. A couple of things to note here:</p>
<ul>
<li><p><code>ELEMENT_ID</code> is the id of your element, e.g. <code>&lt;div id="YOUR_ELEMENT_ID"&gt;</code></p>
</li>
<li><p><code>DEFAULT_OPTIONS</code> are the options to be passed to the instance of <code>Chart</code>. The options you see here allowed our chart to span the full width of it's container.</p>
</li>
<li><p><code>connect</code> is a Stimulus Controller specific API, read more about it <a target="_blank" href="https://stimulus.hotwired.dev/reference/lifecycle-callbacks#connection">here</a>.</p>
</li>
<li><p>We are importing all of Chart.js, if you want to customize the imports, which you should, check out the docs <a target="_blank" href="https://www.chartjs.org/docs/latest/getting-started/integration.html#bundlers-webpack-rollup-etc">here</a>.</p>
</li>
</ul>
<p>Alright, let's pseudo code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// app/packs/controllers/chart_controller.js</span>
<span class="hljs-keyword">import</span> { Controller } <span class="hljs-keyword">from</span> <span class="hljs-string">"@hotwired/stimulus"</span>;
<span class="hljs-keyword">import</span> Chart <span class="hljs-keyword">from</span> <span class="hljs-string">'chart.js/auto'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChartController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
  <span class="hljs-keyword">static</span> ELEMENT_ID = <span class="hljs-string">'YOUR_ELEMENT_ID'</span>;
  <span class="hljs-keyword">static</span> DEFAULT_OPTIONS = { <span class="hljs-attr">responsive</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">maintainAspectRatio</span>: <span class="hljs-literal">false</span> };

  connect() {
    <span class="hljs-built_in">this</span>.render();
  }

  render() {
    <span class="hljs-comment">// If the element exists, instantiate an instance</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">ele</span>() {
    <span class="hljs-comment">// retrieve the canvas element</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">metric</span>() {
    <span class="hljs-comment">// get the metric for the chart</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">unit</span>() {
    <span class="hljs-comment">// get the unit for the chart</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">metrics</span>() {
    <span class="hljs-comment">// get the metrics from the data embedded on the page</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">options</span>() {
    <span class="hljs-comment">// get default options, maybe merge it?</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">data</span>() {
    <span class="hljs-comment">// normalize the data for the chart</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">labels</span>() {
    <span class="hljs-comment">// generate labels for the chart</span>
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">datasets</span>() {
    <span class="hljs-comment">// get the datasets to be represented in the chart</span>
  }
}
</code></pre>
<p>These are all the methods we'll need.</p>
<h3 id="heading-the-render-method">The <code>render</code> method</h3>
<pre><code class="lang-js">  render() {
    <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.ele) <span class="hljs-keyword">return</span>;

    <span class="hljs-keyword">const</span> ctx = <span class="hljs-built_in">this</span>.ele.getContext(<span class="hljs-string">'2d'</span>);

    <span class="hljs-built_in">this</span>.graph = <span class="hljs-keyword">new</span> Chart(ctx, { <span class="hljs-attr">type</span>: <span class="hljs-string">'line'</span>, <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.data, <span class="hljs-attr">options</span>: <span class="hljs-built_in">this</span>.options });
  }
</code></pre>
<p>The render method handles two scenarios. One, if the element doesn't exist then don't render a chart. If the element exists, let's render the chart.</p>
<h3 id="heading-the-ele-getter-function">The <code>ele</code> getter function</h3>
<pre><code class="lang-js">  <span class="hljs-keyword">get</span> <span class="hljs-title">ele</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._ele = <span class="hljs-built_in">this</span>._ele || <span class="hljs-built_in">document</span>.getElementById(ChartController.ELEMENT_ID);
  }
</code></pre>
<p>This method, looks for the element with the id specified on the static class property <code>ELEMENT_ID</code>. This translates to:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'YOUR_ELEMENT_ID'</span>);
</code></pre>
<p>NOTE: We are also memoizing, or caching, <code>ele</code> through the use of:</p>
<pre><code class="lang-js"><span class="hljs-built_in">this</span>._ele = <span class="hljs-built_in">this</span>._ele || <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'YOUR_ELEMENT_ID'</span>);
</code></pre>
<p>Basically, the above will evaluate to <code>document.getElementById('YOUR_ELEMENT_ID');</code> the first time. All subsequent calls will return <code>this._ele</code> because it was already called.</p>
<p>If thats confusing, it's ok. Caching is always confusing.</p>
<h3 id="heading-the-metric-and-unit-getter-functions">The <code>metric</code> and <code>unit</code> getter functions</h3>
<h4 id="heading-context">Context</h4>
<p>Our application, in Jardim.io, allows measurements for a plant to be visualized. For example, a plants height, spread or number of flowers. The units for each can be different. For example, you might measure height in inches, centimeters, millimeters, etc...</p>
<p>So both <code>metric</code> and <code>unit</code> functions above are retrieving <strong>what</strong> we are representing.</p>
<pre><code class="lang-js">  <span class="hljs-keyword">get</span> <span class="hljs-title">metric</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._metric = <span class="hljs-built_in">this</span>._metric || <span class="hljs-built_in">this</span>.element.dataset.metric;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">unit</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._unit = <span class="hljs-built_in">this</span>._unit || <span class="hljs-built_in">this</span>.element.dataset.unit;
  }
</code></pre>
<p>Both these functions will look for the <code>metric</code> and <code>unit</code> dataset on the element that the class is instantiated on, e.g. <code>data-controller</code>.</p>
<h3 id="heading-the-metrics-getter-function">The <code>metrics</code> getter function</h3>
<pre><code class="lang-js">  <span class="hljs-keyword">get</span> <span class="hljs-title">metrics</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._metrics = <span class="hljs-built_in">this</span>._metrics || <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'[data-metrics-type]'</span>).dataset.metrics);
  }
</code></pre>
<p>This is the actual core of our code for retrieving the embedded data. We are leveraging <code>document.querySelector('[data-metrics-type]')</code> to find the element and then we tap into the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset">dataset</a> API tot retrieve the JSON based metrics.</p>
<h3 id="heading-the-options-getter-function">The <code>options</code> getter function</h3>
<pre><code class="lang-js">  <span class="hljs-keyword">get</span> <span class="hljs-title">options</span>() {
    <span class="hljs-keyword">return</span> ChartController.DEFAULT_OPTIONS;
  }
</code></pre>
<p>These are the options that will be used for the instance of <code>Chart</code>. For now, we're getting static options, but you can leverage this to override these options based on parameters on the element for the controller. Wow, thats a mouthful!</p>
<p>If you're looking for what options you can customize, check out the docs <a target="_blank" href="https://www.chartjs.org/docs/latest/configuration/">here</a>.</p>
<h3 id="heading-the-data-and-labels-getter-functions">The <code>data</code> and <code>labels</code> getter functions</h3>
<pre><code class="lang-js">  <span class="hljs-keyword">get</span> <span class="hljs-title">data</span>() {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">labels</span>: <span class="hljs-built_in">this</span>.labels, <span class="hljs-attr">datasets</span>: <span class="hljs-built_in">this</span>.datasets };
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">labels</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._labels = <span class="hljs-built_in">this</span>._labels || <span class="hljs-built_in">this</span>.metrics.map(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(m.updated_at).toDateString());
  }
</code></pre>
<p>These two getters are generating the data and labels for the chart. Note that I'm currently looping through the metrics and generating a date timestamp for the x-axis here. I'll talk about improvements we can make to this code in a later section.</p>
<h3 id="heading-the-dataset-getter-function">The <code>dataset</code> getter function</h3>
<pre><code class="lang-js">  <span class="hljs-keyword">get</span> <span class="hljs-title">datasets</span>() {
    <span class="hljs-keyword">return</span> [{
      <span class="hljs-attr">label</span>: <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.metric}</span> / <span class="hljs-subst">${<span class="hljs-built_in">this</span>.unit}</span>`</span>,
      <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.metrics.map(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> <span class="hljs-built_in">parseInt</span>(m.value, <span class="hljs-number">10</span>)),
      <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
      <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgb(75, 192, 192)'</span>,
      <span class="hljs-attr">tension</span>: <span class="hljs-number">0.1</span>
    }];
  }
</code></pre>
<p>This function generates the label, data and some configuration options for the chart. This is a Chart.js API, read more about it <a target="_blank" href="https://www.chartjs.org/docs/latest/general/data-structures.html">here</a>.</p>
<p>Ok, great! This is what our file looks like now:</p>
<pre><code class="lang-js"><span class="hljs-comment">// app/packs/controllers/chart_controller.js</span>
<span class="hljs-keyword">import</span> { Controller } <span class="hljs-keyword">from</span> <span class="hljs-string">"@hotwired/stimulus"</span>;
<span class="hljs-keyword">import</span> Chart <span class="hljs-keyword">from</span> <span class="hljs-string">'chart.js/auto'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChartController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span> </span>{
  <span class="hljs-keyword">static</span> ELEMENT_ID = <span class="hljs-string">'YOUR_ELEMENT_ID'</span>;
  <span class="hljs-keyword">static</span> DEFAULT_OPTIONS = { <span class="hljs-attr">responsive</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">maintainAspectRatio</span>: <span class="hljs-literal">false</span> };

  connect() {
    <span class="hljs-built_in">this</span>.render();
  }

  render() {
    <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">this</span>.ele) <span class="hljs-keyword">return</span>;

    <span class="hljs-keyword">const</span> ctx = <span class="hljs-built_in">this</span>.ele.getContext(<span class="hljs-string">'2d'</span>);

    <span class="hljs-built_in">this</span>.graph = <span class="hljs-keyword">new</span> Chart(ctx, { <span class="hljs-attr">type</span>: <span class="hljs-string">'line'</span>, <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.data, <span class="hljs-attr">options</span>: <span class="hljs-built_in">this</span>.options });
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">ele</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._ele = <span class="hljs-built_in">this</span>._ele || <span class="hljs-built_in">document</span>.getElementById(ChartController.ELEMENT_ID);
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">metric</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._metric = <span class="hljs-built_in">this</span>._metric || <span class="hljs-built_in">this</span>.element.dataset.metric;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">unit</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._unit = <span class="hljs-built_in">this</span>._unit || <span class="hljs-built_in">this</span>.element.dataset.unit;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">metrics</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._metrics = <span class="hljs-built_in">this</span>._metrics || <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'[data-metrics-type]'</span>).dataset.metrics);
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">options</span>() {
    <span class="hljs-keyword">return</span> ChartController.DEFAULT_OPTIONS;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">data</span>() {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">labels</span>: <span class="hljs-built_in">this</span>.labels, <span class="hljs-attr">datasets</span>: <span class="hljs-built_in">this</span>.datasets };
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">labels</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._labels = <span class="hljs-built_in">this</span>._labels || <span class="hljs-built_in">this</span>.metrics.map(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(m.updated_at).toDateString());
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">datasets</span>() {
    <span class="hljs-keyword">return</span> [{
      <span class="hljs-attr">label</span>: <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.metric}</span> / <span class="hljs-subst">${<span class="hljs-built_in">this</span>.unit}</span>`</span>,
      <span class="hljs-attr">data</span>: <span class="hljs-built_in">this</span>.metrics.map(<span class="hljs-function">(<span class="hljs-params">m</span>) =&gt;</span> <span class="hljs-built_in">parseInt</span>(m.value, <span class="hljs-number">10</span>)),
      <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
      <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgb(75, 192, 192)'</span>,
      <span class="hljs-attr">tension</span>: <span class="hljs-number">0.1</span>
    }];
  }
}
</code></pre>
<hr />
<h2 id="heading-the-result-retrospective">The Result + Retrospective</h2>
<p>We now have a very simple and lightweight controller we can use to instantiate instances of Chart.js. With data embedded on the page, all we do is retrieve it, normalize it to json and pass it as a dataset to our Chart instance. Now, we just need to style it - which I'll leave up to you.</p>
<p>This is my first pass migrating to Chart.js and I picked up a few things I would love to do in our next iteration, this includes:</p>
<ul>
<li><p>Normalizing the data on the backend a bit more</p>
<ul>
<li><p>Use date time formatting from Ruby/Rails (not JS)</p>
</li>
<li><p>Move metric and unit into the data itself (vs dataset)</p>
</li>
</ul>
</li>
<li><p>Allow for customization of options</p>
</li>
<li><p>Investigate a common utility for memoizing</p>
</li>
<li><p>Add error handling around null/undefined dataset or missing element</p>
</li>
</ul>
<p>When I do get a chance to tackle some of these items, I'll make sure to follow up from this post.</p>
<hr />
<h2 id="heading-overview">Overview</h2>
<p>Chart.js is an excellent open source library that helps you visualize data. Rails 7, specifically Turbo/Stimulus, allows us to easily implement it into our application for a seamless experience, enabling our customers with a fast solution while lightening our technology stack is a major win.</p>
<p>Hope you enjoyed! If you love what you read, let me know at <a target="_blank" href="https://twitter.com/alvincrespo">@alvincrespo</a>!</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="Chart.js">https://www.chartjs.org/</a></p>
</li>
<li><p><a target="_blank" href="Stimulus">https://stimulus.hotwired.dev/handbook/origin</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Thoughts on Technology Choices]]></title><description><![CDATA[Prioritize scalability, team, culture, and budget. Adapt technology for maximum leverage.]]></description><link>https://alvincrespo.hashnode.dev/thoughts-on-technology-choices</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/thoughts-on-technology-choices</guid><category><![CDATA[technology stack]]></category><category><![CDATA[technology trends]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[software design]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Wed, 14 Oct 2020 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/JG35CpZLfVs/upload/eb584b54205dfcd6909c1ac0f094a199.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-guiding-principle">Guiding Principle</h2>
<blockquote>
<p>A good tech stack is one that scales faster than the people required to maintain it.  </p>
<p>Yevgeniy Brikman, Hello, Startup - Chapter 5. Choosing a Tech Stack</p>
</blockquote>
<p>When considering a technology choice, I think about a few things:</p>
<ul>
<li><p>The product being built (market, scale, etc.)</p>
<ul>
<li><p>SAAS, B2B, etc.</p>
</li>
<li><p>Are we talking hundreds, thousands or millions of users?</p>
</li>
<li><p>Rural and/or Urban?</p>
</li>
</ul>
</li>
<li><p>Composition of the team</p>
<ul>
<li><p>What type of engineers are on the project?</p>
<ul>
<li><p>Full-Stack</p>
</li>
<li><p>Backend / Frontend</p>
</li>
<li><p>Seniority</p>
</li>
</ul>
</li>
<li><p>Does the team prefer a language? Framework?</p>
</li>
</ul>
</li>
<li><p>Company culture</p>
<ul>
<li><p>Get it done ASAP?</p>
</li>
<li><p>Get it done Right?</p>
</li>
</ul>
</li>
<li><p>Budget</p>
<ul>
<li><p>60k - 100k</p>
</li>
<li><p>100k +</p>
</li>
<li><p>1M +</p>
</li>
</ul>
</li>
</ul>
<p>At this point - I haven't thought about the technology itself. That's because - there is no such thing as the "right" technology. Context drives the decision. Anyone promising technology without the context needed to make these decisions is lying to you. Learning a new technology can be fun - but your focus should be on delivering value.</p>
<h2 id="heading-use-what-you-know">Use what you know</h2>
<blockquote>
<p>Quite simply, I don't try to learn about every new thing that comes out. There's a limited number of hours in the day and a limited amount of energy you can devote to any topic, so I choose not to learn about anything that I don't think will be immediately useful to me</p>
<p>Nicholas C. Zakas, Thoughts on JS Fatigue, Top of the Month Newsletter (August 4, 2020)</p>
</blockquote>
<p>Every successful company that we know of built the foundations of its technology based on the founding team's knowledge of what they knew at the time. They used what they knew:</p>
<ul>
<li><p>LinkedIn was built in Java because it's founders knew Java</p>
</li>
<li><p>Github founders were Ruby developers, so it was built in Ruby</p>
</li>
<li><p>Twitter was built on Rails because early employees knew Rails</p>
</li>
<li><p>Pinterest was built on Python because the founders knew Python</p>
</li>
</ul>
<p>This doesn't mean that you don't learn new technologies and methodologies - but that you focus on utilizing your strengths to deliver value while developing a mental model around how these technologies can be integrated. Nicholas C. Zakas writes his thoughts on this perfectly:</p>
<blockquote>
<p>The most important skill for a long career in software engineering is the ability to <strong>learn new things quickly</strong>. If you trust that you can learn new things quickly, then you don't need to stop and learn every new thing as it is released. You know that when you can learn about something right when you need it.  </p>
<p>Nicholas C. Zakas, Thoughts on JS Fatigue, Top of the Month Newsletter (August 4, 2020)</p>
</blockquote>
<h2 id="heading-evolving-a-technology-stack">Evolving a technology stack</h2>
<blockquote>
<p>The trick is not the initial choice of technology. The initial decision is guaran-fucking-teed to be wrong… eventually. The only question is how long it’s going to take to be wrong. The trick is recognizing when you hit that inflection point where you need to have the courage to just kill the thing rather than apply Band-Aid after Band-Aid after Band-Aid to it to keep it alive.</p>
<p>Having that discipline is super important. I think, by far and away, that’s more important than trying to read the zeitgeist and get into an infinite design analysis loop to figure out the best initial technology decision. Instead, make sure that you’re building yourself and your environment to adapt to change and you know when the time is right to rebuild.  </p>
<p>[ Scott 2014 ], Kevin Scott, SVP at LinkedIn, VP at AdMob, Director at Google. Hello, Startup - Chapter 5. Choosing a Tech Stack</p>
</blockquote>
<p>You will need to evolve your technology stack. It is inevitable. As you learn about the needs of your product's users - the more you'll need to evolve what was built. Needs change, so your technology will need to change with it. Many of the products we use have done this:</p>
<ul>
<li><p>Twitter migrated from Rails to Scala</p>
</li>
<li><p>Coursera went from PHP to Scala</p>
</li>
<li><p>HubSpot from .NET to Java</p>
</li>
</ul>
<p>When do we know our technology needs to evolve?</p>
<p>Symptoms that technology needs to evolve:</p>
<ul>
<li><p>Scaling people faster than technology</p>
</li>
<li><p>Features are taking longer to deliver</p>
</li>
<li><p>Releases seem to break existing functionality</p>
</li>
</ul>
<p>Ultimately, your technology choices should be driven by the leverage it affords you. Yevgeniy puts it this way:</p>
<blockquote>
<p>Your goal is to be able to scale your tech stack to more users, traffic, data, and code by throwing money or hardware, rather than manpower, at the problem. If every time your user base doubles, you can just pay for a few more servers and everything keeps working, you’re in good shape. On the other hand, if you have to double the size of your team, you might need a change.  </p>
<p>Yevgeniy Brikman, Hello, Startup - Chapter 5. Choosing a Tech Stack</p>
</blockquote>
<h2 id="heading-deciding-on-a-framework">Deciding on a framework</h2>
<p>The framework you choose should depend on the size of the community around it. Why?</p>
<ul>
<li><p>Hiring ability</p>
</li>
<li><p>Learning resources</p>
</li>
<li><p>Open source libraries</p>
</li>
</ul>
<p>This is not to be confused by popularity. A framework may be popular and have a small community of active users, while an unpopular framework might have a large community of active users. Again, your aim is to ensure that you can hire, ramp up engineers quickly and tap into open sources resources easily.</p>
<h2 id="heading-wrap-up">Wrap up</h2>
<p>Technology choices are driven by context. The context is gained by understanding the product, team, culture and budget. Ultimately, your decision will be wrong. Learning how to leverage the technology to scale correctly will give you the ability you need to evolve. Deciding on a technology should be based around the community surrounding it - giving you the ability to hire, learn quickly and utilize open source libraries.</p>
<p>Use what you know and understand it's leverage to give you the best results. Continue to learn new technologies, but understand when and why to use them.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="https://www.hello-startup.net/">Hello, Startup by Yevgeniy Brikman</a></p>
</li>
<li><p><a target="_blank" href="https://humanwhocodes.com/">Human Who Codes</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Integrating Google OAuth in Rails - Part 1]]></title><description><![CDATA[Step-by-step guide to integrating Google OAuth in Rails, focusing on setting up Google Developer Console for Calendar API.]]></description><link>https://alvincrespo.hashnode.dev/integrating-google-oauth-in-rails-part-1</link><guid isPermaLink="true">https://alvincrespo.hashnode.dev/integrating-google-oauth-in-rails-part-1</guid><category><![CDATA[oauth]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[google cloud]]></category><category><![CDATA[Google API]]></category><dc:creator><![CDATA[Alvin Crespo]]></dc:creator><pubDate>Mon, 07 Sep 2020 13:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/7GfRwb78YWs/upload/5b9622cc76b1881f62650509338d97aa.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever had to integrate OAuth? Integrate with Google? No?! Cool.</p>
<p>This series is focused on helping you integrate with Google APIs fairly quickly. I'm going to show you how to 1) create events for your users google calendar and 2) manage incoming/outgoing communication via Gmail right within your app.</p>
<p>For this first part, we'll be setting up our app in Google's developer console. So let's get started!</p>
<hr />

<p>You'll need to follow along at <a target="_blank" href="https://console.developers.google.com">console.developers.google.com</a>.</p>
<p>First, let's create a new project. You can name it anything, for my personal set up - I have 3 projects:</p>
<ul>
<li>Development (local)</li>
<li>Staging</li>
<li>Production</li>
</ul>
<p>I do this to separate out each environment. For the sake of this article, I'm just using the default name filled in by Google.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348839767/d95cb218-f47a-454f-aed4-339475e2d806.png" alt /></p>
<p>Once the project is created, you'll see the following dashboard:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348841184/04e28e15-8e5b-465b-ab36-b9b832e6ff2c.png" alt /></p>
<p>We need to enable the API's we'll be using. In this series, I'm adding Calendar and Gmail. Let me show you how can do this fairly easily for Google Calendar.</p>
<p>Click on "ENAABLE APIS AND SERVICES" button in the middle of top bar next to "APIs &amp; Services".</p>
<p>You'll be taken to the following page:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348842768/357543f1-9d8a-4f53-881c-61429e8610d6.png" alt /></p>
<p>In the search bar, type in "Calendar". This should give you the following results:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348844505/7265922c-9d60-49fe-8980-d4a37694ab4c.png" alt /></p>
<p>Click on the first result, "Google Calendar API". You should then be taken to:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348845996/6ec5a4c6-8b7a-47ff-b58f-4fa2e48619c6.png" alt /></p>
<p>Click on the blue "Enable" button. Once enabled, you'll be taken to:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348847601/f696a2c4-0d93-40af-9763-99ca6a893247.png" alt /></p>
<p>Here, you'll want to click on "Create Credentials" button at the top right of the content area.</p>
<p>This will take you to a wizard, where you'll fill in a few questions:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348849408/e384e324-c882-4042-ac99-a32f16c3762e.png" alt /></p>
<p>For the "Which API are you using?", select "Google Calendar API".</p>
<p>For the "Where will you be calling the API from?", select "Web server (e.g. nodejs, Tomcat)"</p>
<p>For "What data will you be accessing?", select "User data".</p>
<p>Your options should match:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348850910/3b99ec21-40ae-4666-ad58-261db78ac484.png" alt /></p>
<p>There should be a blue highlighted button, "What credetnials do I need?". Click that button.</p>
<p>You will receive a modal to "Set up OAuth consent screen":</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348852706/fac16329-b5c6-410c-9d65-d87a0db5ea66.png" alt /></p>
<p>Click on "Set up consent screen". This will open up a new tab:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348854276/efef94b1-b017-4af8-8812-43c10a449923.png" alt /></p>
<p>Select "External" for User Type and click "Create".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348855989/8feb31aa-8fd0-4df7-8a58-164f3c2ec3a0.png" alt /></p>
<p>You will then be taken to the "OAuth consent screen", where you will fill in details about your app.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348857541/39455569-9e7c-4b9f-afb8-efae19ac9ad4.png" alt /></p>
<p>For "Application Type", select "Public".</p>
<p>For "Application name", fill in the name for your app - in the screenshot below I use "My Awesome App".</p>
<p>Scroll to the bottom of the page and click "Save".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348858955/3bffd6cc-9a5d-4376-8df2-db3305fce5f2.png" alt /></p>
<p>Once the settings have been saved, go back to the first tab to set up credentials.</p>
<p>Now, we're going to create the Client ID.</p>
<p>Fill in the name for the client ID, I'm using "myoauth".</p>
<p>Then, click on "refresh".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348860504/3b719e37-dcb0-4efb-a0b9-19f8d7691bd0.png" alt /></p>
<p>Once refresh is completed, you'll see the "Create OAuth client ID" button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348862066/ed24f3dc-f19e-4264-88d1-5f4a8ef21bd8.png" alt /></p>
<p>This will create the credentials you'll use to authenticate.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348863817/23c8cb5f-8ba7-43be-84c2-64e106950762.png" alt /></p>
<p>Download these credentials and keep them safe. I tend to upload these to my personal 1Password account.</p>
<p>Finally, click on "Done".</p>
<p>You'll be taken to the Credentials dashboard.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722348865308/a2c77d27-d81e-4ebf-a87c-78aef4de3be1.png" alt /></p>
<p>Here you'll see the credentials you created.</p>
<hr />

<p>Congratulations! 🎆🎆🎆</p>
<p>You have successfully set up credentials for your integration with Google API's. This specific intro set up Calendar. You'll want to go in and set up Gmail next. I'll let you tackle that one on your own. Don't worry though, I'll be creating a separate post for Gmail API's - but that'll come later.</p>
<p>Either way, the next part is setting up your Rails app to integrate with Google Calendar.</p>
<p>Thanks for reading and definitely check back for the next part in the series.</p>
]]></content:encoded></item></channel></rss>