<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Keroles Massoud on Medium]]></title>
        <description><![CDATA[Stories by Keroles Massoud on Medium]]></description>
        <link>https://medium.com/@keroles-masoud?source=rss-d08b4b9e6570------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Rs9aDaqtimyYUhggsyIB1Q.jpeg</url>
            <title>Stories by Keroles Massoud on Medium</title>
            <link>https://medium.com/@keroles-masoud?source=rss-d08b4b9e6570------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:19:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@keroles-masoud/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Message Queues: Under the Hood, Failure Handling, and Scaling]]></title>
            <link>https://keroles-masoud.medium.com/message-queues-under-the-hood-failure-handling-and-scaling-f3875562c6c0?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3875562c6c0</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 03:35:38 GMT</pubDate>
            <atom:updated>2026-09-13T03:43:24.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello my software engineer friends!</p><p>Imagine you have an e-commerce application, a customer places an order, and the application needs to save the order, send an email, update the inventory, process the payment, and generate an invoice.</p><p>Everything is inside the same application, at first, this seems simple.</p><p>But what happens when sending the email takes 5 seconds?</p><p>Does the customer really need to wait 5 seconds just to see “Order placed successfully”?</p><p>What if the email service is temporarily unavailable?</p><p>What if thousands of customers place orders at the same time?</p><p>Do we keep adding more code, threads, and workers to handle the load?</p><p>This is where the idea of a Message Queue starts to become useful.</p><p>In this article, we’ll look at how Message Queues work, what happens when things fail, and how we handle delivery, duplicates, ordering, retries, and scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDjJlmrB1P9yplTQGU30Bg.jpeg" /><figcaption>Message Queue</figcaption></figure><h3>1. What Is a Message Queue?</h3><p>Let’s start with a simple example, imagine our monolithic application receives a new order.</p><p>After creating the order, we want to send a confirmation email.</p><p>Instead of sending the email immediately, the application can put a message into a <strong>Message Queue</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYG-c5g3uAct2cagT-gMXg.png" /></figure><p>The idea is simple:</p><ul><li><strong>Producer</strong> sends a message to the Message Queue.</li><li><strong>Message Queue</strong> stores the message until it can be processed.</li><li><strong>Consumer / Worker</strong> receives the message and processes it.</li><li>The <strong>Producer does not need to wait</strong> for the Consumer to finish.</li></ul><p>The Order Service can now create the order, publish the email task to the message queue, and continue its execution asynchronously without blocking.</p><h3>2. Why Do We Use a Message Queue?</h3><p>There are four common reasons to use a Message Queue.</p><h4>Asynchronous Processing</h4><p>Producers can dispatch messages and continue executing without waiting for consumers to process them. For example, upon creating an order, sending the confirmation email can be offloaded as a background task, allowing the system to return a response instantly.</p><h4>Decoupling</h4><p>Without a message queue the Producer is tightly coupled to the Consumer, requiring direct synchronous communication (e.g., Order Service → Email Service).</p><p>A message queue reduces direct coupling between the Producer and Consumer and decouples them in time. (Order Service → Message Queue ← Email Worker). The Order Service now only needs to publish the payload to the queue, completely abstracted from how or when the Email Worker processes it.</p><h4><strong>Reliability</strong></h4><p>If the Email Worker crashes during a direct call, the request fails. A message queue can help prevent this by acting as a secure buffer. If the consumer goes down, messages simply wait in the queue and are processed seamlessly once the service is restored.</p><ul><li><strong>Without a Queue:</strong> If the Email Worker is down, the direct request from the Order Service fails entirely.</li><li><strong>With a Queue:</strong> The queue acts as a buffer. The Order Service sends the message to the queue, where it waits safely. When the Email Worker comes back online, it picks up the message and processes it can allow the message to remain available for later processing, depending on the queue’s durability and configuration.</li></ul><h4>Handling Bursty Traffic</h4><p>If traffic suddenly jumps from 100 to 5,000 requests per minute, direct communication can instantly overload downstream services. A message queue prevents this by absorbing the temporary spike, letting workers process the messages gradually at their own pace.</p><ul><li><strong>Without a Queue:</strong> A sudden spike from 100 to 5,000 requests per minute directly hammers the downstream service, risking an overload or crash.</li><li><strong>With a Queue:</strong> The queue acts as a shock absorber. It ingests the 5,000 requests instantly, while your workers process them sequentially at a safe speed.</li></ul><p>At first, this sounds simple. But once we introduce a queue, several interesting questions appear.</p><p>What happens if the worker crashes?</p><p>What happens if the same message is delivered twice?</p><p>Can a message be lost?</p><p>And what happens when the number of messages suddenly increases?</p><p>We will answer these questions step by step.</p><h3>3. What Happens When a Consumer Crashes?</h3><p>Let’s say we have this message “Send confirmation email for Order #123”</p><p>But while processing the message, the Worker crashes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a3TKXlC-3BSLUWd5PBDGg.png" /></figure><p>Now the Message Queue needs to know:</p><p><strong>Was the message successfully processed or not?</strong></p><p>This is where <strong>Acknowledgement (ACK)</strong> comes in.</p><p><strong>The Acknowledgement (ACK) Lifeline</strong> How does a message queue know a task is actually finished? It relies on an Acknowledgement (ACK). Once a Consumer successfully processes a message, it sends an ACK back to the queue, essentially saying, “I’m done, you don’t need to deliver this again.”</p><p><strong>The Crash Scenario</strong> But what if the worker completes the job, but crashes <em>before</em> it can send the ACK?</p><p>From the queue’s perspective, the task failed. To ensure no data is lost, Depending on the Message Queue, an unacknowledged message may be redelivered.</p><p><strong>The Duplicate Processing Trap</strong> While redelivery prevents data loss, it introduces a dangerous new problem: <strong>duplicate processing.</strong></p><p>This brings us to a critical challenge in distributed systems: <em>How do we safely handle messages that get delivered more than once?</em></p><h3>4. What If the Same Message Is Processed Twice?</h3><p>As we’ve seen, a Consumer can crash <em>after</em> processing a task but <em>before</em> sending the ACK. This introduces a dangerous side effect: message redelivery.</p><p>Imagine a payment worker handling an order. It successfully charges the customer’s credit card, but crashes a millisecond before sending the ACK. Because the Message Queue never received confirmation, it assumes the task failed. To prevent data loss, the queue redelivers the message to the next available worker, which blindly charges the customer a second time.</p><p>Because many messaging systems can redeliver unacknowledged messages, consumers should be designed to safely handle duplicate deliveries.</p><p>This brings us to a crucial backend concept: <strong>Idempotency</strong>. <em>(If you want a deeper dive into how to solve this specific problem, I explored the mechanics in my previous article: </em><a href="https://www.linkedin.com/pulse/what-customer-clicks-order-twice-keroles-masoud--jy6be"><em>What Happens if a Customer Clicks Order Twice?</em></a><em>).</em></p><h3>5. Message Delivery Guarantees</h3><p>Message Queues generally provide different delivery guarantees.</p><p>The three common models are:</p><ul><li><strong>At-most-once</strong></li><li><strong>At-least-once</strong></li><li><strong>Exactly-once</strong></li></ul><h4>5.1 At-Most-Once</h4><p>With <strong>at-most-once</strong>, the message is delivered<strong> zero or one time.</strong></p><p>The Consumer acknowledges the message before processing it.</p><p>This means the message should not be processed twice, but there is a risk of losing it.</p><p>For example, the Consumer receives the message, acknowledges it, and then crashes before processing it.</p><p>The queue now considers the message completed and will not redeliver it.</p><p>So:</p><blockquote><strong><em>At-most-once favors avoiding duplicates, even if some messages may be lost.</em></strong></blockquote><h4>5.2 At-Least-Once</h4><p>With <strong>at-least-once</strong>, the Consumer processes the message first and acknowledges it after successful processing.</p><p>This reduces the chance of losing a message. However, there is a catch.</p><p>The Consumer might successfully process the message and then crash before sending the ACK.</p><p>The queue does not know that processing actually happened, so it may deliver the same message again.</p><p>So:</p><blockquote><strong><em>At-least-once favors not losing messages, but duplicates are possible.</em></strong></blockquote><p>This is why <strong>idempotency is very important</strong> when using at-least-once delivery.</p><h4>5.3 Exactly-Once</h4><p>Exactly-once sounds like the perfect solution:</p><blockquote><strong><em>The message will be processed exactly one time.</em></strong></blockquote><p>But in reality, achieving this is incredibly difficult because we must distinguish between two separate events:</p><ol><li>Was the message <em>delivered</em> exactly once?</li><li>Was the business operation (like a payment or database update) <em>performed</em> exactly once?</li></ol><p>Even if a queue guarantees a message is delivered only once, the Consumer can still crash mid-process, requiring a retry that executes the operation a second time. Exactly-once is not simply about delivering a message once. The real challenge is making sure the business side effect also happens once.</p><p>A message may be delivered once by the broker, but the database update, payment, or external API call can still fail or be repeated.</p><p>Most systems rely on a more practical approach: <strong>At-least-once delivery + Idempotent processing = Effectively-once processing.</strong></p><h3>6. What If Message Processing Keeps Failing?</h3><p>Sometimes a message cannot be processed successfully.</p><p>For example, a message asks a worker to create an invoice, but the required data is invalid or a downstream service keeps returning an error.</p><p>A common approach is to <strong>retry</strong> the message.</p><p>For example, we might try processing it three times. If all attempts fail, continuously retrying the same message is probably not useful.</p><p>This is where a <strong>Dead Letter Queue (DLQ)</strong> can help.</p><h4>The Dead Letter Queue (DLQ) Lifecycle</h4><p>When a message fails due to invalid data or service errors, the Consumer will try again. But retrying a “poison message” forever will eventually break your system. To fix this, failed messages are routed to a Dead Letter Queue (<strong>DLQ</strong>).</p><p>The typical lifecycle looks like this:</p><ol><li><strong>Process:</strong> The Consumer attempts to handle the message.</li><li><strong>Retry:</strong> If it fails, retry up to a maximum limit (e.g., 3 times).</li><li><strong>Isolate:</strong> Once the limit is reached, move the message to the DLQ.</li><li><strong>Investigate:</strong> Developers analyze the DLQ to find out why the message failed.</li><li><strong>Reprocess:</strong> Once the underlying issue is fixed, the message is sent back through the system.</li></ol><blockquote><strong>Don’t let one bad message keep failing forever.</strong></blockquote><h3>7. How Do We Handle Increased Throughput?</h3><p>Now imagine that our application starts receiving much more traffic.</p><p>One Consumer might be able to process 100 messages per second, but suddenly we need to process 1,000 messages per second.</p><p>What happens when one Consumer is no longer enough?</p><p>One common solution is to run <strong>multiple Consumers or Workers</strong>.</p><p>Instead of having one worker process everything, several workers can process messages in parallel.</p><p>For example, one worker might process one message while another worker processes a different message at the same time.</p><p>This increases throughput because we are doing more work concurrently.</p><h4>Consumer Groups</h4><p>In some messaging systems, Consumers are organized into <strong>consumer groups</strong>.</p><p>A group allows multiple Consumers to share the work of processing messages.</p><p>This means we can add more Consumers when we need more processing capacity.</p><p>However, simply adding Consumers does not always solve every problem.</p><p>If the system needs very high throughput, we may also need <strong>partitioning</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*U6zVQv59fZDlpvoFo11frQ.png" /><figcaption>Consumer Groups</figcaption></figure><h4>Partitioning</h4><p>Partitioning divides a stream of messages into multiple partitions.</p><p>Each partition can be processed independently, which allows different Consumers to work in parallel.</p><p>For example, instead of having one large stream of messages, we could have several partitions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*se0X_njQ948GREofcC2oyw.png" /><figcaption>Message Queue Partitioning</figcaption></figure><p>This allows the system to process more messages at the same time.</p><p>But now we have another question:</p><p><strong>If multiple Consumers are processing messages in parallel, what happens to message ordering?</strong></p><h3>8. What About Message Ordering?</h3><p>Suppose a customer performs three actions:</p><ol><li>Create an order</li><li>Pay for the order</li><li>Cancel the order</li></ol><p>The order matters.</p><p>We don’t want the Consumer to process “<strong>Cancel Order</strong>” before “<strong>Create Order</strong>”.</p><p>But when we introduce parallel processing, messages can be handled by different Consumers.</p><p>So how can we keep related messages in the correct order while still processing unrelated messages in parallel?</p><p>A common solution is to use a <strong>partition key</strong>.</p><p>For example, we could use customer_id or order_id as the key.</p><p>Messages with the same key are sent to the same partition.</p><p>So if we use order_id =123</p><p>for all messages related to Order #123, they can stay in the same partition and be processed in order.</p><p>At the same time, messages for other orders can go to different partitions and be processed in parallel.</p><p>The important idea is:</p><blockquote><strong><em>Keep related messages together, while allowing unrelated messages to be processed in parallel.</em></strong></blockquote><p>The exact ordering guarantees depend on the Message Queue technology and its configuration, so “partitioning” does not automatically mean that every message in the entire system is globally ordered.</p><h3>9. What Happens If the Message Queue Goes Down?</h3><p>So far, we have talked about what happens when a <strong>Consumer</strong> fails.</p><p>But what if the <strong>Message Queue itself</strong> fails?</p><p>This is a different problem.</p><p>If the queue is unavailable, Producers may not be able to publish new messages, and Consumers may not be able to receive existing ones.</p><p>For an important system, we don’t want one broker or one machine to become a <strong>single point of failure</strong>.</p><p>One common solution is <strong>replication</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86Zlid1jbKuFj4ewlRJ2Bg.png" /><figcaption>Message Queue replication</figcaption></figure><p>Instead of keeping the messaging system on only one broker, we can run multiple broker nodes and replicate data between them.</p><p>If one broker fails, another node can continue serving the system, depending on how the Message Queue technology is configured.</p><p>Another important concept is <strong>durability</strong>.</p><p>A durable message is stored in a way that allows it to survive certain failures, such as a broker restart. This helps prevent messages from disappearing just because a broker was restarted.</p><p>So, when we talk about making a Message Queue reliable, several concepts work together:</p><ul><li><strong>Multiple broker nodes</strong> reduce dependence on a single machine.</li><li><strong>Replication</strong> keeps copies of messaging data across nodes.</li><li><strong>Durable messages</strong> help messages survive broker restarts and certain failures.</li><li><strong>High availability</strong> allows the system to continue operating when part of the infrastructure fails.</li></ul><p>The goal is simple:</p><blockquote><strong><em>A Message Queue should not become the single point of failure in the system.</em></strong></blockquote><p>But this leads to another question.</p><p>What happens when the number of messages becomes too large for our current Message Queue infrastructure?</p><h3>10. How Do We Scale the Message Queue?</h3><p>We already saw how to scale <strong>Consumers</strong> by adding more workers.</p><p>But sometimes the problem is not the Consumers.</p><p>The Message Queue itself may become the bottleneck.</p><p>For example, imagine we have thousands or millions of messages flowing through the system. A single broker may not have enough CPU, memory, network capacity, or storage to handle the workload.</p><p>At that point, we need to scale the messaging infrastructure.</p><p>One approach is <strong>horizontal scaling</strong>: instead of relying on one powerful broker, we add more broker nodes.</p><p>We can also use <strong>partitioning or sharding</strong> to distribute messages across different parts of the system.</p><p>This allows different brokers or nodes to handle different portions of the workload.</p><p>Replication can also be used for availability, so a failure in one node does not necessarily bring down the entire messaging system.</p><p>This gives us two different scaling ideas:</p><p><strong>Consumer scaling</strong></p><blockquote><em>Add more workers to process more messages in parallel.</em></blockquote><p><strong>Message Queue scaling</strong></p><blockquote><em>Add more broker capacity and distribute messages across partitions or nodes.</em></blockquote><p>The important thing is that these solve different problems.</p><p>Adding more Consumers helps when <strong>message processing</strong> is too slow.</p><p>Scaling the Message Queue helps when the <strong>messaging infrastructure itself</strong> cannot handle the workload.</p><p>A well-designed system usually needs both: enough Consumers to process the messages and enough Message Queue capacity to move and store them reliably.</p><h3>Conclusion</h3><p>A Message Queue looks simple at first:</p><blockquote><strong><em>Producer → Message Queue → Consumer</em></strong></blockquote><p>But once we start thinking about real systems, many questions appear.</p><p>What happens when a Consumer crashes?</p><p>What if the same message is delivered twice?</p><p>How do we handle retries and failed messages?</p><p>What delivery guarantee do we need?</p><p>How do we process thousands of messages at the same time?</p><p>How do we preserve ordering?</p><p>What happens if the Message Queue itself fails?</p><p>And how do we scale the messaging infrastructure?</p><p>Understanding these problems is more important than simply knowing how to publish and consume a message.</p><p>A Message Queue is not just a component for moving messages.</p><p>It is a tool for building systems that can <strong>process work asynchronously, handle failures, absorb traffic spikes, and scale</strong>.</p><p>And like any other tool, it should be used when the problem actually requires it.</p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3875562c6c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Microservices: A Practical Guide to JWT]]></title>
            <link>https://keroles-masoud.medium.com/authentication-in-microservices-a-practical-guide-to-jwt-0079b9e4a984?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/0079b9e4a984</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 17:07:43 GMT</pubDate>
            <atom:updated>2026-09-07T15:55:17.787Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello my software engineer friends!</p><p>Today, I want to ask you a simple question:</p><p><strong>When a request reaches your microservice, how do you know who is calling you?</strong></p><p>In a monolithic application, authentication can feel relatively simple, You have one application, one session, one database, and one place where most security decisions happen.</p><p>Then you move to microservices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pNF0nNqgDKDAI_L5KKGeIg.jpeg" /></figure><p>Now the question becomes more complicated.</p><p>Who authenticates the user?</p><p>Who validates it?</p><p>Should every microservice call the authentication service?</p><p>What happens if the token expires while the request is being processed?</p><p>What happens if the signing key changes?</p><p>What happens if one service receives the request after the token has already expired?</p><p>These questions are where authentication becomes an <strong>architectural concern</strong>, not just middleware configuration.</p><p>In this article, we will focus specifically on <strong>JWT-based authentication in microservices</strong>.</p><p>The goal is to understand <strong>how it works, where it works well, and where its trade-offs appear</strong>.</p><h3>1- Authentication vs Authorization</h3><p>Before discussing microservices, we need to separate two concepts that are often mixed together.</p><h4>Authentication</h4><p><strong><em>Who are you?</em></strong></p><pre>Username: keroles<br>Password: ********</pre><p>If the credentials are valid, the system knows the<strong> identity of the caller</strong>.</p><h4>Authorization</h4><p><strong><em>What are you allowed to do?</em></strong></p><pre>User: Keroles<br><br>Can:<br>    Read Orders       <br>    Create Orders     <br>    Delete Orders     <br>    Refund Payment    </pre><h3>2- Why Authentication Becomes Harder in Microservices</h3><p>Imagine a monolithic application.</p><p>You might have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*LgkBhM1DqhekvyM4BgzpMg.png" /></figure><p>Everything exists inside the same application.</p><p>let’s split it and services are independently deployed also y may even be written in different languages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*QZTzxzmsaKi-B6sZMp2egA.png" /></figure><p><strong>We don’t want every service to implement its own login system.</strong></p><pre>User Service<br>    -&gt; login<br>    -&gt; password validation<br>    -&gt; token generation<br><br>Order Service<br>    -&gt; login<br>    -&gt; password validation<br>    -&gt; token generation<br><br>Payment Service<br>    -&gt; login<br>    -&gt; password validation<br>    -&gt; token generation</pre><p>This approach duplicates security logic across multiple services.</p><p><strong>It also creates additional problems:</strong></p><ul><li>Different password implementations</li><li>Different token formats</li><li>Different security configurations</li><li>Difficult security updates</li><li>Duplicated user credentials</li><li>More points of failure</li></ul><p>A better approach is to centralize authentication and let individual services verify the caller’s identity and make their own authorization decisions.</p><h3>3- Authentication Service</h3><p>A common approach in microservices is to use a dedicated Authentication Service or Identity Provider.</p><p>The Authorization Server handles authentication. After the user successfully logs in, it issues an access token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*tJWe5zyjrG5VZ6BAuHvVng.png" /></figure><p><strong>The microservices don&#39;t need to handle the user&#39;s password.</strong></p><p>Instead:</p><ol><li>The user authenticates with the Identity Provider.</li><li>The Identity Provider issues an access token.</li><li>The client sends the token with requests.</li><li>Microservices validate the token.</li><li>The service can identify the caller.</li></ol><p>This separates authentication from the business services.</p><h4>3.1- What Is a Token?</h4><p>After successful authentication, the client receives an access token then client sends it with subsequent requests. For example, when calling the Order Service:</p><pre>Client → Order Service <br>            Authorization: Bearer &lt;token&gt;</pre><p>The Order Service needs to verify the token and determine who the caller is.</p><p>What that user is allowed to do is a separate authorization decision</p><p>There are several ways to validate a token. One of the most common approaches is <strong>JWT (JSON Web Token)</strong>.</p><h3>4- JWT: A Token the Service Can Validate</h3><p>A JSON Web Token (JWT) is a compact token containing claims.</p><p>Conceptually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxW23GMtcqE2quXc7tG7pw.avif" /></figure><p>The signature allows the service to verify that the token was issued by a trusted authority and has not been modified.</p><p>The important idea is that the service can validate the token locally, It doesn’t necessarily need to call the authentication server for every request.</p><h3>5- Why JWT Works Well With Microservices</h3><p>One of the main advantages of JWT is that it can support stateless token validation.</p><p>The service can validate the token’s signature, issuer, audience, expiration, and required identity claims without making a network call to another service for every request.</p><p><strong>without making a network call to another service for every request.</strong></p><p>This can provide:</p><ul><li>Lower latency</li><li>Less network communication</li><li>Better availability</li><li>Less coupling</li><li>Easier horizontal scaling</li></ul><p>But this also introduces important trade-offs:</p><h4>5.1- JWT Is Not Encryption</h4><p>One common misunderstanding is thinking that a JWT is encrypted. <strong>It is not necessarily encrypted.</strong></p><p>A normal signed JWT can usually be decoded, so anyone who has the token may be able to read its payload.</p><p>The signature is used to <strong>protect the token from being modified</strong>, not to hide its contents.</p><p>So remember:</p><ul><li><strong>Encoding</strong> : Can be decoded</li><li><strong>Signing</strong> : Detects modification</li><li><strong>Encryption</strong> : Protects the data from being read</li></ul><p>Therefore, don’t put sensitive information inside a normal JWT just because it is encoded or signed.</p><h3>6- JWT Validation</h3><p>Now let’s look at what happens when a request reaches a service.</p><p>Suppose the client sends:</p><pre>GET /orders/123<br>Authorization: Bearer &lt;jwt&gt;</pre><h4>Step 1: Extract the Token</h4><p>The service extracts the token from the request.</p><h4>Step 2: Verify the Signature</h4><p>The service verifies the JWT signature using the appropriate verification key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*rO8qjjrPrXFprdXq_4yBqA.png" /></figure><h4>Step 3: Verify the Issuer</h4><p>The service verifies that the token was issued by the expected Identity Provider.</p><pre>iss = trusted-identity-provider</pre><h4>Step 4: Verify the Audience</h4><p>The service verifies that the token is intended for the service or API.</p><pre>aud = order-service</pre><h4>Step 5: Verify Expiration</h4><p>The service checks whether the token has expired.</p><p><em>exp &gt; current_time</em></p><p>If the token is expired:</p><pre>401 Unauthorized</pre><h4>Step 6: Extract the Identity</h4><p>Finally, the service can extract information such as:</p><pre>{<br>   &quot;sub&quot;: &quot;123&quot;,<br>   &quot;username&quot;: &quot;keroles&quot;,<br>   &quot;role&quot;: &quot;admin&quot;<br>}</pre><p>The sub claim can represent the authenticated user.</p><p>The service now knows:</p><pre>Request<br>   ↓<br>Valid Token<br>   ↓<br>Authenticated Identity<br>   ↓<br>User ID = 123</pre><p>At this point, <strong>authentication has been established</strong>.</p><p>What the user is allowed to do is a separate authorization decision.</p><h3>7. JWT Edge Cases</h3><p>JWT authentication with distributed systems introduce several edge cases.</p><h4>7.1 What Happens If JWT Expires During Request Processing?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*ujaJWzAWvQJkKkfS4p0p0w.png" /></figure><p>Should the request fail because the JWT expired at 10:00:00?</p><p><strong>Normally, no.</strong></p><p>The service validates the JWT when it accepts the request.</p><p>Once the request has successfully passed authentication, the service normally doesn’t continuously revalidate the JWT during the same request.</p><p>So:</p><pre>JWT valid when request accepted<br>        ↓<br>Request continues<br>        ↓<br>JWT expires during processing<br>        ↓<br>Request normally continues</pre><p>The expiration time prevents the token from being accepted after it has expired.</p><p>It doesn’t normally mean that an already-accepted request must be terminated the moment the clock reaches exp.</p><h4>7.2- What Happens If JWT Expires Between Microservices?</h4><p>The correct approach depends on your trust boundaries and architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*EBVus7ir2xXNS6Ty204jfA.png" /></figure><p>The correct approach depends on your trust boundaries and architecture.</p><p>The important lesson is:</p><blockquote><strong><em>Don’t assume that a user’s JWT will remain valid throughout an arbitrarily long distributed workflow.</em></strong></blockquote><h4>7.3- What Happens If the User Logs Out?</h4><p>This is one of the important trade-offs of stateless JWT authentication.</p><p>If the JWT is still cryptographically valid and hasn’t expired, a service may still accept it.</p><p>Why?</p><p>Because local JWT validation may only check:</p><pre>Signature<br>Issuer<br>Audience<br>Expiration</pre><p>It doesn’t automatically know that the user clicked “Logout”.</p><p>This creates the <strong>token revocation problem</strong>.</p><p>Without an additional revocation mechanism, the token may remain usable until it expires.</p><p>Possible strategies include:</p><ul><li>Short-lived access tokens</li><li>Token revocation</li><li>Token introspection</li><li>Denylists for specific high-risk situations</li><li>Refresh-token rotation</li><li>Centralized session management</li></ul><p>Each option introduces different trade-offs.</p><h4>7.4- What Happens If the Signing Key Changes?</h4><p>JWT validation depends on the signing key. When the authentication service rotates its signing key, microservices need a way to obtain the corresponding verification key.</p><p>A common solution is to provide a <strong>public key endpoint</strong> that microservices can use to get and cache the current keys.</p><p>During rotation, both the <strong>old and new public keys</strong> may need to be available for a short time so existing tokens can still be validated.</p><p>The important point is:</p><p><strong>Key rotation must be planned carefully, otherwise valid JWTs may suddenly be rejected.</strong></p><h4>7.5- Clock Skew Between Services</h4><p>JWT expiration depends on time, but servers in a distributed system may have slightly different clocks.</p><p>For example, the Authentication Service may consider a token valid while a microservice thinks it has already expired.</p><p>This is called <strong>clock skew</strong>.</p><p>To avoid problems, servers should keep their clocks synchronized. JWT libraries can also allow a small time difference, such as 30 seconds.</p><p>The important point is:</p><p><strong>Clock-skew tolerance should be small and should not allow expired tokens for too long.</strong></p><h4>7.6- What If Someone Modifies the JWT?</h4><p>Suppose an attacker changes:</p><pre>From: <br>    {<br>      &quot;sub&quot;: &quot;123&quot;,<br>      &quot;role&quot;: &quot;user&quot;<br>    }<br><br>To:<br><br>    {<br>      &quot;sub&quot;: &quot;123&quot;,<br>      &quot;role&quot;: &quot;admin&quot;<br>    }</pre><p>The payload has changed and original signature no longer matches.</p><p>This is why the service must validate the signature.</p><p><strong>Never trust JWT claims before validating the token.</strong></p><h3>8- Practical JWT Checklist</h3><p>When implementing JWT authentication in a microservice, ask:</p><h4>Token</h4><ul><li>Where is the token issued?</li><li>How long does it live?</li><li>What claims does it contain?</li><li>Is it signed?</li><li>Which algorithm is used?</li></ul><h4>Validation</h4><ul><li>Is the signature verified?</li><li>Is the issuer verified?</li><li>Is the audience verified?</li><li>Is expiration verified?</li><li>Are required claims validated?</li><li>Are acceptable algorithms explicitly configured?</li></ul><h4>Keys</h4><ul><li>How are public keys distributed?</li><li>How are keys cached?</li><li>How does key rotation work?</li><li>What happens when a key is removed?</li></ul><h4>Expiration</h4><ul><li>What happens when the token expires?</li><li>What happens if it expires between services?</li><li>What happens with long-running operations?</li><li>How are refresh tokens handled?</li></ul><h4>Revocation</h4><ul><li>What happens when a user logs out?</li><li>What happens if a token is compromised?</li><li>Can tokens be revoked?</li><li>How quickly does revocation take effect?</li></ul><h4>Architecture</h4><ul><li>Does the Gateway validate the token?</li><li>Do individual services validate it too?</li><li>How is identity propagated internally?</li><li>How are service-to-service requests authenticated?</li></ul><h3>9. The Big Picture</h3><p>JWT authentication in microservices can be summarized like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*QJkVgsaXZ7JggRioXQwpNQ.png" /></figure><p>The important idea is that the Authentication Service <strong>establishes the identity</strong>, while microservices have the responsibility to <strong>verify that identity before trusting the request</strong>.</p><p>JWT makes this possible without requiring every microservice to contact the Authentication Service for every request.</p><p>But that convenience comes with trade-offs around:</p><ul><li>Token expiration</li><li>Revocation</li><li>Key rotation</li><li>Clock skew</li><li>Distributed requests</li><li>Long-running operations</li><li>Service-to-service authentication</li></ul><h3>Conclusion</h3><p>JWT authentication looks simple when you look at a single request. The interesting part starts when that request crosses multiple services.</p><p>Tokens expire, keys change, services can fail, and users may log out.</p><p>That’s why authentication is more than just creating and validating a JWT.</p><p>The key idea is:</p><blockquote><strong><em>JWT is just a tool for carrying identity. It is not the whole authentication architecture.</em></strong></blockquote><p>Once you understand this, authentication becomes much easier to reason about. You can make better decisions about how your services communicate, how tokens are handled, and how to keep your system secure as it grows.</p><p><strong>The goal isn’t to build a complicated authentication system. It’s to build one that is simple enough to understand, secure enough to trust, and reliable enough to grow with your system.</strong></p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0079b9e4a984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Caching Bad or Beneficial?]]></title>
            <link>https://keroles-masoud.medium.com/is-caching-bad-or-beneficial-76083450c03c?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/76083450c03c</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 17:17:43 GMT</pubDate>
            <atom:updated>2026-08-30T17:17:43.087Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello my software engineer friends!</p><p>Today, I want to ask you a simple question: Is caching bad, or is it beneficial for improving application performance?</p><p>Caching is one of the most common techniques used to make software systems faster. From CPU caches and operating system page caches to database buffer pools, CDNs, and application-level caches such as Redis, caching exists at almost every layer of modern software systems.</p><p>However, caching is not free. It can introduce new challenges around data consistency, memory management, invalidation, cache stampedes, stale data, and system design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7C0NnyHG_dHWYYknc0LSQ.jpeg" /><figcaption>Is Caching Bad or Beneficial?</figcaption></figure><p>In this article, we will look at both sides of caching. We will first understand why caching is so useful, then explore the problems it can introduce, and finally discuss when those problems actually matter and how to design caching properly.</p><p>The goal is not to convince you to use caching everywhere or to avoid it completely. The goal is to understand the trade-offs so you can make better architectural decisions.</p><h3>1. What Is Caching?</h3><p>Before discussing whether caching is good or bad, we need to understand what it actually does.</p><p>At a high level, caching means storing data that is expensive or slow to retrieve in a location that allows us to access it faster the next time we need it.</p><p>A simplified example is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xcMjdYifOa-1Gg98Azc1Q.png" /></figure><p>Instead of querying the database every time, the application can reuse data that has already been retrieved.</p><p>The complexity appears when we start asking questions about how that cached data should be managed.</p><h3>2. Why Do We Use Caching?</h3><p>The primary reason for caching is performance.</p><p>A cache can reduce latency because accessing cached data is usually much faster than accessing the original data source.</p><pre>              Application <br>                  |<br>                  v<br>                Redis<br>                  |<br>                  v <br>               Database</pre><p>If the requested data is already in Redis, the application can avoid a database query.</p><p>Caching can also reduce the load on downstream systems :</p><pre>100,000 requests<br>       |<br>       v<br>Cache<br>       |<br>       +---- 99,000 cache hits<br>       |<br>       +---- 1,000 database queries</pre><p>This can significantly reduce database load and allow the system to handle more traffic.</p><h3>3. The Benefits of Caching</h3><p>Caching can provide several important benefits.</p><h4>3.1 Lower Latency</h4><p>Cached data can usually be accessed much faster than data retrieved from a database or remote service.</p><h4>3.2 Reduced Database Load</h4><p>Frequently requested data does not need to be fetched from the database repeatedly.</p><h4>3.3 Higher Throughput</h4><p>By reducing expensive operations, the application can process more requests with the same infrastructure.</p><h4>3.4 Reduced Infrastructure Costs</h4><p>If caching significantly reduces database traffic, you may need fewer database resources or fewer application instances.</p><h4>3.5 Better Scalability</h4><p>Caching can help systems handle large numbers of read requests without putting all the pressure on the underlying data source.</p><h3>4. Caching Is Everywhere</h3><p>Caching is not limited to Redis or Memcached.</p><p>Modern computers and distributed systems use caching at many different levels.</p><p>For example:</p><pre>        CPU<br>         |<br>         +-- L1 Cache<br>         |<br>         +-- L2 Cache<br>         |<br>         +-- L3 Cache<br>         |<br>         v<br>        RAM<br>         |<br>         v<br>        OS Page Cache<br>         |<br>         v<br>        Database Buffer Pool<br>         |<br>         v<br>        Application Cache<br>         |<br>         v<br>        CDN</pre><p>Even when developers do not explicitly think about caching, they are already using systems that depend heavily on it.</p><p>This is important because caching itself is not a bad design.</p><p>The real question is how we use it.</p><h3>5. The Problems Caching Can Introduce</h3><p>Caching provides performance benefits, but it also introduces additional design considerations.</p><p>Some of the most common problems include:</p><ol><li>Eviction</li><li>Cache invalidation</li><li>Stale data</li><li>Cache stampede</li><li>Cache warm-up</li><li>Cache consistency</li><li>Memory management</li><li>Cache key design</li></ol><p>However, there is an important point to understand.</p><p>Not every caching system has all of these problems, most of these problems are conditional.</p><p>They depend on the characteristics of the data, the workload, the cache capacity, and the consistency requirements.</p><h4>5.1 Eviction</h4><p>A cache usually has limited capacity, suppose we have:</p><pre>Working Set = 100 GB<br>Cache       = 10 GB</pre><p>We cannot keep all the data in memory, the cache needs an eviction strategy like:</p><ol><li>LRU</li><li>LFU</li><li>FIFO</li><li>TTL</li></ol><p>But if the entire working set fits inside the cache, eviction may not be an important concern.</p><h4>5.2 Cache Invalidation</h4><p>Cache invalidation becomes important when the underlying data changes.</p><p>Suppose we have:</p><pre>Database:<br>user.name = &quot;Keroles&quot;<br><br>Cache:<br>user.name = &quot;Keroles&quot;<br><br>Now the database changes:<br>user.name = &quot;Kero&quot;<br><br>We now have:<br>Database = Kero<br>Cache    = Keroles</pre><p>The cache contains stale data, We therefore need a strategy for handling changes.</p><p>This is where cache invalidation becomes one of the more difficult parts of caching.</p><h4>5.3 Do We Always Need Invalidation?</h4><p>No, if the data is immutable, invalidation may not be necessary.</p><p>A common example is static assets, now we do not need to immediately invalidate the old key.</p><p>We simply start requesting the new key.</p><p>This approach effectively changes a correctness problem into a performance problem.</p><p>The old object can eventually disappear through normal cache expiration or eviction.</p><h4>5.4 TTL and Acceptable Staleness</h4><p>Another approach is to accept that cached data may be slightly stale.</p><p>For example:</p><pre>TTL = 60 seconds</pre><p>The application accepts that the cached value can be up to 60 seconds old.</p><p>This can make the caching architecture much simpler.</p><p>The important question becomes:</p><blockquote><em>How much staleness can the application tolerate?</em></blockquote><p>If one minute of stale data is acceptable, TTL can be a simple and effective solution.</p><p>If stale data is unacceptable, caching becomes significantly more complicated.</p><h4>5.5 Cache Stampede</h4><p>Imagine that we have a very popular key:<strong> <em>product:123</em></strong></p><p>Suppose it receives thousands of requests per second, now imagine that the key expires.</p><p>Many requests may see a cache miss at approximately the same time:</p><pre>              Cache Miss<br>                   |<br>                   v<br>         +---------+---------+<br>         |         |         |<br>         v         v         v<br>      Request   Request   Request<br>         |         |         |<br>         +---------+---------+<br>                   |<br>                   v<br>               Database</pre><p>Instead of one request rebuilding the cache, many requests may hit the database simultaneously.</p><p>This can create<strong> </strong>a <strong>sudden load spike</strong>.</p><p>However, cache stampede is not a problem for every cache.</p><p>It becomes particularly important when you have a hot key, high request volume, expiration, and expensive cache regeneration.</p><h4>5.6 Cache Warm-Up</h4><p>When an application starts, the cache may initially be empty.</p><p>This is known as a cold cache.</p><pre>   Application Restart<br>          |<br>          v<br>     Empty Cache<br>          |<br>          v<br>    Cache Misses<br>          |<br>          v<br>       Database</pre><p>The question is whether the underlying system can handle the temporary increase in traffic.</p><p>If the database can handle the load, cache warm-up may simply cause temporary performance degradation.</p><p>If the database cannot handle the load, the cache may become critical to system availability.</p><p>This is why cache warm-up should be considered based on the actual workload rather than treated as a problem in every system.</p><h3>6. The Difference Between Optimization and Dependency</h3><p>A crucial rule in system design is that a cache should speed up your application, not be required for it to run.</p><ul><li><strong>The Good (Cache as an Optimization):</strong> The database is your single source of truth. If the cache gets wiped out, the system simply fetches the data directly from the database to rebuild it. The application might run slower temporarily, but it continues to work seamlessly.</li><li><strong>The Bad (Cache as a Dependency):</strong> The cache acts as the source of truth. If the cache fails or empties, the application breaks entirely because it relies on the cache to function.</li></ul><p><strong>The Ultimate Test:</strong> Always ask yourself, <em>“Can my system survive if the cache is completely empty?”</em></p><p>If the answer is no, your cache has become a dangerous dependency, and you should rethink your system’s architecture.</p><h3>7. How Should We Think About Caching?</h3><p>Better question is:</p><p><strong>A What problem am I solving with caching, and what trade-offs am I willing to accept?</strong></p><p>Before introducing a cache, consider:</p><ul><li>Why am I caching it?</li><li>How frequently is it accessed?</li><li>How frequently does it change?</li><li>How much stale data is acceptable?</li><li>What happens when the cache is empty?</li><li>How large is the working set?</li><li>What happens when the cache becomes full?</li></ul><p>These questions help determine whether caching is actually appropriate.</p><h3>8. Conclusion</h3><p>Caching isn’t inherently “good” or “bad” it’s a trade-off. You accept extra complexity and memory usage in exchange for faster speeds and less strain on your servers.</p><ul><li><strong>Context is Key:</strong> Caching challenges (like hitting memory limits, keeping data fresh, or handling traffic spikes) are real, but they only matter when your specific system actually faces those scenarios.</li><li><strong>Keep it Disposable:</strong> The biggest mistake is letting your cache become the main source of truth. If a cache fails, your app should simply slow down, not crash entirely.</li><li><strong>The Ultimate Goal:</strong> Don’t avoid caching. Use it when the performance benefits are worth the added complexity, and always design your system so that a cache failure is a speed bump, not a roadblock.</li><li>A well-designed cache should normally be something you can lose and recover from.</li></ul><p>The goal is therefore not to avoid caching.</p><p>The goal is to understand when caching provides enough value to justify its complexity, and to design it so that cache failures degrade performance rather than destroy correctness or availability.</p><h3>References &amp; Resources</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching?utm_source=chatgpt.com">https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching</a></p><p><a href="https://redis.io/docs/latest/develop/use-cases/cache-aside/?utm_source=chatgpt.com">https://redis.io/docs/latest/develop/use-cases/cache-aside/</a></p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76083450c03c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Transactions: When One Transaction Becomes a Problem]]></title>
            <link>https://keroles-masoud.medium.com/distributed-transactions-when-one-transaction-becomes-a-problem-bf228aaf6f8f?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf228aaf6f8f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 14:19:18 GMT</pubDate>
            <atom:updated>2026-08-25T14:19:18.147Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello my software engineer friends!</p><p>Imagine you have a system for booking tours, hotels, and cars all in one seamless vacation package. It’s fantastic and saves the user a lot of money. But what if the customer pays for the trip, only for the hotel or car booking to fail right after? You’ve charged their credit card, but now they have nowhere to stay when they land. That’s a real problem.</p><p>Today, we’ll break down the core mechanics behind this exact challenge: Distributed Transactions. We’ll cover the problems they create, traditional solutions like 2PC, and their built-in shortcomings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfP2mlaGBRAGB5NpGRkDpQ.jpeg" /></figure><h3><strong><em>The Core Problem: Database per Service vs. Distributed Atomicity</em></strong></h3><p>In a modern microservices architecture, we follow the <strong>Database per Service</strong> pattern to keep teams autonomous and systems loosely coupled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*N65Pf_XzE2V3toQSwQfiEw.png" /></figure><p>When a user books a package:</p><ol><li><strong>Tour Service</strong> creates a booking in <strong>Tour DB</strong>.</li><li><strong>Hotel Service</strong> reserves a room in <strong>Hotel DB</strong>.</li><li><strong>Payment Service</strong> processes the payment and records the payment state in <strong>Payment DB</strong>.</li></ol><p>In a single database, if all three operations are part of the same local transaction, <strong>ACID</strong> guarantees that if step 3 fails, steps 1 and 2 can be rolled back as well. But across separate databases over a network:</p><ul><li><strong>Atomicity is lost:</strong> You can no longer wrap network calls across distinct databases in a single local database transaction.</li><li><strong>Partial failures happen:</strong> A network timeout between services leaves data in an inconsistent state across systems.</li><li><strong>Global isolation is not guaranteed:</strong> Each service can maintain local transaction isolation, but there is no single isolation boundary across all databases. Other services may observe intermediate states while the overall business operation is still in progress.</li></ul><h3>First, What Exactly Is a Distributed Transaction?</h3><p>Before discussing 2PC, it’s important to distinguish a <strong>local transaction</strong> from a <strong>distributed transaction</strong>.</p><p>A local transaction operates within a single transactional resource, such as one database:</p><pre>                      Application <br>                            │ <br>                            ▼ <br>                         Database<br>                            │<br>                            └── BEGIN<br>                                UPDATE<br>                                INSERT<br>                                COMMIT / ROLLBACK</pre><p>The database can provide ACID guarantees because it controls the entire transaction.</p><p>A <strong>distributed transaction</strong> extends this idea across multiple independent transactional resources:</p><pre>                          Distributed Transaction <br>                                  │<br>                   ┌──────────────┼──────────────┐<br>                   ▼              ▼              ▼<br>                 Tour DB       Hotel DB       Payment DB</pre><p>Now imagine:</p><ol><li>Tour DB successfully creates the booking.</li><li>Hotel DB successfully reserves the room.</li><li>Payment DB fails.</li></ol><p>The system has performed part of the business operation, but not all of it.</p><p>The challenge is no longer simply:</p><blockquote><strong><em>“How do I make this database transaction atomic?”</em></strong></blockquote><p>It becomes:</p><blockquote><strong><em>“How do I make multiple independent resources behave as if they were one atomic transaction?”</em></strong></blockquote><p>That is the problem distributed transaction protocols such as <strong>Two-Phase Commit (2PC)</strong> attempt to solve.</p><h3><strong>One Solution: Two-Phase Commit (2PC)</strong></h3><p>To coordinate atomic commits across multiple independent transactional resources, several distributed transaction protocols exist. One classic protocol-level solution is <strong>Two-Phase Commit (2PC)</strong>.</p><p><strong>Core Components of 2PC</strong></p><p>To make 2PC work, the system relies on two main roles:</p><ul><li><strong>Transaction Coordinator (Manager):</strong> The central master node that manages the lifecycle of the global transaction. It collects votes from all services and makes the final decision to commit or abort.</li><li><strong>Participants (Resource Managers):</strong> The transactional resources involved in the global transaction, such as Tour DB, Hotel DB, and Payment DB. Each participant executes its local transaction and votes on whether it is prepared to commit.</li></ul><h3><strong>How 2PC Solves the Problem</strong></h3><p>2PC solves the partial commit problem by replacing independent commits with a <strong>two-phase protocol</strong>, enforcing <strong>Atomicity</strong> (“all-or-nothing”) across the participating resources.</p><p>Instead of allowing each participant to commit independently, participants first prepare their local transactions. The global transaction is committed only after every participant confirms that it is ready to commit.</p><ul><li><strong>Phase 1 (Prepare): </strong>The Coordinator sends a PREPARE request to all Participants. Each participant performs its local work and prepares the transaction for commit, ensuring it can safely commit later. It then votes <strong>Yes</strong> or <strong>No</strong>.</li><li><strong>Phase 2 (Commit / Abort):</strong> If any participant votes <strong>No</strong>, the Coordinator decides to abort. If all participants vote <strong>Yes</strong>, it decides to commit. Failures and timeouts require recovery protocols because the coordinator may be uncertain about a participant’s state.</li></ul><p><em>If all participating resources support 2PC, the global transaction can guarantee that either all participants commit or all abort.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EI3sxYOwfUM6PXsraqRyXg.png" /><figcaption>2PC Components</figcaption></figure><h3>The Shortcomings of 2PC</h3><p>While 2PC provides <strong><em>strong atomicity guarantees</em></strong>, it introduces severe operational drawbacks:</p><ul><li><strong>Coordinator Failure &amp; Blocking:</strong> If the Coordinator crashes after participants have voted <strong>Yes</strong> but before they learn the final decision, participants may remain in an uncertain state and block while waiting for recovery or the coordinator’s decision.</li><li><strong>Blocking &amp; Increased Latency:</strong> Participants may need to keep transactional resources locked or otherwise unavailable while waiting for the coordinator’s final decision. Because the transaction remains open across network communication, long delays can consume database connections and other resources.</li><li><strong>Coordination Overhead:</strong> Every participant must communicate with the Coordinator during multiple phases. As the number of participants increases, the coordination overhead and number of possible failure scenarios also increase.</li><li><strong>Limited Applicability:</strong> 2PC requires participating resources to support the protocol. This becomes especially problematic when a workflow involves external services, such as payment providers, that do not participate in your application’s 2PC transaction.</li></ul><h3>Is 2PC the Best Solution?</h3><p>2PC provides strong atomicity guarantees across participating transactional resources, but that guarantee comes with a cost: coordination overhead, increased latency, and the possibility of blocking when failures occur.</p><p>These trade-offs make 2PC a poor fit for many modern, highly available microservice architectures, especially when the workflow involves external services that cannot participate in the protocol.</p><p>This is where the <strong>Saga pattern</strong> takes a different approach.</p><p>Instead of trying to make multiple services behave like one global ACID transaction, a Saga breaks the business operation into a sequence of <strong>local transactions</strong>. If a later step fails, the system executes <strong>compensating transactions</strong> to undo the business effects of previously completed steps.</p><p>We’ll explore the <strong>Saga pattern</strong> in detail in the next article, including how it handles failures in distributed workflows without requiring a global distributed transaction.</p><h3>Final Thought</h3><p>Distributed transactions highlight one of the fundamental challenges of distributed systems:</p><blockquote><strong><em>When one business operation spans multiple independent systems, achieving atomicity is no longer a simple database problem.</em></strong></blockquote><p>2PC provides one answer: coordinate every participant and make them commit or abort together.</p><p>But that coordination comes with significant costs And that leads us to the next question:</p><blockquote><strong><em>Can we achieve reliable business consistency without forcing multiple services to behave like one database?</em></strong></blockquote><p>In the next article, we’ll explore how the <strong>Saga pattern</strong> handles failures across distributed services without requiring a global distributed transaction.</p><h3>References &amp; Resources</h3><ul><li><a href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol"><em>Two-Phase Commit — Wikipedia</em></a></li><li><a href="https://martin.kleppmann.com/2015/07/02/transactions-at-work.html">Distributed Transactions — Martin Kleppmann</a></li><li><a href="https://microservices.io/patterns/data/database-per-service.html">Database per Service — Microservices.io</a></li></ul><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf228aaf6f8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Databases Actually Use Your Index?]]></title>
            <link>https://keroles-masoud.medium.com/do-databases-actually-use-this-index-03f986f960d7?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f986f960d7</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database-indexing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 16:53:39 GMT</pubDate>
            <atom:updated>2026-06-26T16:56:42.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hello, my software engineering friends.</p><p>When discussing database query performance, the first optimization that usually comes to mind is adding an index. After all, indexes are designed to speed up data retrieval by allowing the database to perform targeted lookups instead of scanning every row in a table.</p><p>But here’s an important question:</p><p><strong>Does the database always use the index you’ve created?</strong></p><p>Surprisingly, the answer is <strong>no</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbnIPF8X-b4P7VYLNxt7tw.png" /><figcaption>Do Databases Actually Use Your Index?</figcaption></figure><p>Many developers assume that simply creating an index guarantees faster queries. In reality, the database optimizer decides whether an index is beneficial for a particular query. Sometimes, the way a query is written prevents the optimizer from using the index efficiently or from using it at all.</p><p>This is where <strong>SARGability</strong> comes in.</p><p>In this article, we’ll explore what makes a query SARGable, why some queries ignore existing indexes, and how small changes to your SQL can dramatically improve performance without adding new hardware or creating additional indexes.</p><h3>What Happens When You Execute a Query?</h3><p>Before discussing SARGability, let’s first understand what happens inside the database when we execute a query.</p><p>Suppose we have the following table:</p><pre>users <br>--------------------------------<br>|id | name | email | created_at |<br>--------------------------------</pre><p>Now imagine we execute the following query:</p><pre>SELECT * FROM users WHERE created_at = &#39;2025-01-01&#39;;</pre><p>If the created_at column has an index, the database optimizer has two possible execution strategies:</p><ol><li><strong>Use the index</strong> to quickly locate the matching rows.</li><li><strong>Ignore the index</strong> and scan every row in the table.</li></ol><p>Naturally, we expect the database to choose the first option because indexes are designed to make lookups much faster.</p><p>But databases don’t blindly use every available index.</p><p>Instead the <strong>Query Optimizer</strong> analyzes the query and estimates the cost of each execution plan. It chooses the plan with the lowest estimated cost.</p><p>This means that simply creating an index does <strong>not</strong> guarantee that the database will use it.</p><p>The optimizer may decide that a full table scan is actually cheaper than using the index.</p><p>This raises an important question:</p><blockquote><strong><em>What makes the optimizer ignore an existing index?</em></strong></blockquote><p>One of the biggest reasons is whether the search condition is <strong>SARGable</strong>.</p><h3>What Does SARGable Mean?</h3><p><strong>SARGable</strong> stands for <strong>Search ARGument Able</strong>.</p><p>A query is considered SARGable when the database can efficiently use an index to narrow down the rows it needs to read.</p><p>Think of it like looking for a word in a dictionary.A dictionary is already sorted alphabetically.</p><p>If someone asks you to find the word: <strong>“Database”</strong> you can immediately jump to the correct section. This is exactly how an index works.<br>Now imagine someone asks:</p><blockquote><em>“Find every word where the first three letters, after converting them to uppercase, equal </em><strong><em>‘DAT’.</em></strong><em>”</em></blockquote><p>You can no longer use the dictionary’s ordering directly.<br>Instead, you must examine every word one by one.<br>That’s exactly what happens when a <strong>query becomes non-SARGable.</strong></p><h3>A SARGable Query</h3><p>Suppose we have an index on created_at.</p><p>This query is SARGable:</p><pre>SELECT * <br>FROM users <br>WHERE created_at &gt;= &#39;2025-01-01&#39; <br>  AND created_at &lt; &#39;2026-01-01&#39;;</pre><p>The optimizer can navigate directly through the index because the indexed column appears by itself in the comparison.</p><p>This usually results in an <strong>Index Seek</strong>, where only the relevant portion of the index is accessed.</p><h3>A Non-SARGable Query</h3><p>Now consider this query:</p><pre>SELECT * FROM users WHERE YEAR(created_at) = 2025;</pre><p>Although an index exists on created_at, the database cannot use it efficiently.</p><p>Why?</p><p>Because the YEAR() function must first be applied to every row before the comparison can be made.</p><p>The indexed values are no longer being compared directly.</p><p>Instead of searching the index, the database often ends up scanning the entire table (or the entire index), evaluating YEAR(created_at) row by row.</p><p>This small change dramatically increases the amount of work the database must perform.</p><h3>The Golden Rule</h3><p>A simple rule to remember is:</p><blockquote><strong><em>Never apply functions, calculations, or expressions to an indexed column if you expect the database to perform an Index Seek.</em></strong></blockquote><p>Instead, rewrite the query so the indexed column appears directly in the predicate.</p><p>Compare these two queries:</p><p><strong>Non-SARGable</strong> or <strong>SARGable</strong></p><p>Both queries return the same results.<br>However, the second query allows the optimizer to fully leverage the index.<br>In large tables containing millions of rows, this difference can reduce execution time from several seconds to just a few milliseconds.</p><h3>Conclusion</h3><p>Creating an index is only the first step toward better query performance. An index is valuable <strong>only if the database optimizer can actually use it</strong>.</p><p>Throughout this article, we’ve seen that the way a query is written has a significant impact on whether an index can be leveraged efficiently. Applying functions, performing calculations, or wrapping indexed columns in expressions can prevent the optimizer from performing an <strong>Index Seek</strong>, often forcing it to scan far more data than necessary.</p><p>The key takeaway is simple:</p><blockquote><strong><em>Don’t just create indexes , write queries that allow the database to use them.</em></strong></blockquote><p>Whenever you’re optimizing SQL, don’t assume your index is being used. Verify it by examining the execution plan, and if you see a full table scan where you expected an index seek, ask yourself one question:</p><p><strong>“Is my query SARGable?”</strong></p><p>In many cases, a small rewrite of the WHERE clause can produce dramatic performance improvements without adding new indexes or changing your database schema.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f986f960d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Doing This in PostgreSQL: 5 Common Anti-Patterns Killing Your Performance]]></title>
            <link>https://keroles-masoud.medium.com/stop-doing-this-in-postgresql-5-common-anti-patterns-killing-your-performance-82b973c5cdb6?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/82b973c5cdb6</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 12:00:11 GMT</pubDate>
            <atom:updated>2026-06-07T12:00:11.812Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me start with a question:</p><p>As backend developers, do we really need to understand how a database works internally, or is it enough to interact with it through SQL queries and an ORM?</p><p>For many of us, the database is just another service. We create tables, add indexes, write queries, and move on. As long as the application works, what’s happening inside the database engine feels like someone else’s concern.</p><p>Until it isn’t.</p><p>In 2016, <strong>Uber</strong> Engineering published a controversial article explaining why they migrated from PostgreSQL to MySQL. The announcement triggered heated debates across the engineering community. But regardless of which side of the argument you supported, the story revealed an important lesson: database internals matter.</p><p>One of the challenges Uber faced was <strong>write amplification</strong>. What looked like a simple UPDATE operation could generate significantly more work behind the scenes. At massive scale, millions of these seemingly harmless operations translated into enormous disk I/O costs, increased storage pressure, and performance bottlenecks that couldn’t be solved by simply throwing more hardware at the problem.</p><p>Most applications will never operate at Uber’s scale. However, the underlying lesson applies to everyone: if you treat <strong>PostgreSQL as a black box</strong>, you can accidentally build performance problems into your system long before traffic becomes massive.</p><p>The good news is that many of these issues are well known and well documented by the PostgreSQL team itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGKP9tQ6tMizUlD13hy55w.png" /><figcaption>PostgreSql Common Anti-Patterns Killing Your Performance</figcaption></figure><p>In this article, we’ll explore five of the most common PostgreSQL mistakes highlighted in the official PostgreSQL “Don’t Do This” guide. These are the kinds of design decisions that seem harmless during development but can quietly evolve into serious performance, scalability, and maintenance problems as your application grows.</p><p>Let’s dive in before one of these time bombs finds its way into your production database.</p><h3>1. The ID Trap: Why BIGINT is the Only Choice</h3><p>While Uber struggled with write amplification, companies like <strong>Sentry</strong> and <strong>Canva</strong> faced a different, more binary disaster: <strong>Integer Exhaustion.</strong></p><p>In both cases, their core tables hit the <strong>2,147,483,647</strong> limit of a 32-bit SERIAL column. The result? Total write paralysis. The database simply refused to accept new rows.</p><h4>The Wiki Truth: SERIAL is a Legacy Macro</h4><p>The Wiki warns that SERIAL isn&#39;t a true data type it’s a macro that creates a non-standard sequence. It’s hard to manage, risky at scale, and non-compliant with modern SQL standards.</p><p><strong>The Fix:</strong> Modern Postgres (v10+) introduced GENERATED ALWAYS AS IDENTITY. It’s cleaner, safer, and when paired with BIGINT, it ensures you won&#39;t hit a wall for another 9 quintillion years.</p><pre>-- DON&#39;T: Legacy, 2.1B limit, non-standard ownership<br>id SERIAL PRIMARY KEY<br><br>-- DO: SQL-standard, safe for 9 quintillion rows<br>id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY</pre><h3>2. The Subquery Silent Killer: NOT IN vs. NOT EXISTS</h3><p>This anti-pattern is a favorite for causing <strong>“unexplained”</strong> CPU spikes. You want to find users who haven’t made a purchase, so you write a quick WHERE user_id NOT IN (SELECT user_id FROM sales).</p><p>The problem? <strong>Three-valued logic.</strong> If your sales table contains even a single NULL user_id, the NOT IN clause returns exactly zero results. To handle this logical edge case, the PostgreSQL query planner often abandons efficient index scans and falls back to a massive <strong>Sequential Scan</strong>.</p><h4>The Fix: NOT EXISTS</h4><p>NOT EXISTS handles NULLs naturally and allows the planner to use a &quot;Hash Anti-Join,&quot; keeping your queries in the millisecond range even with millions of rows.</p><pre>-- DON&#39;T: Risks slow sequential scans and logical bugs with NULLs<br>SELECT * FROM users <br>WHERE id NOT IN (SELECT user_id FROM sales);<br><br>-- DO: Allows for efficient Anti-Joins<br>SELECT u.* FROM users u<br>WHERE NOT EXISTS (<br>    SELECT 1 FROM sales s WHERE s.user_id = u.id<br>);</pre><h3>3. The Data Type Deception: CHAR(n) is Never Faster</h3><p>A common myth among developers is that CHAR(50) is faster than TEXT because it has a &quot;fixed&quot; size. They assume the database can calculate the exact byte offset of the next row.</p><p>In PostgreSQL, this is false. All variable-length types (CHAR, VARCHAR, TEXT) use the exact same storage mechanism (varlena). In fact, CHAR(n) is <strong>slower</strong> because it pads every string with trailing spaces, increasing storage bloat and wasting CPU cycles stripping those spaces during every comparison.</p><h4>The Fix: Just Use TEXT</h4><p>Unless you specifically need the database to reject strings longer than N characters (for which VARCHAR(N) or a CHECK constraint is fine), use TEXT. It’s clean, flexible, and efficient.</p><pre>-- DON&#39;T: Assuming fixed-length CHAR is faster<br>CREATE TABLE products (<br>sku CHAR(20)<br>);<br><br>INSERT INTO products (sku) VALUES (&#39;ABC123&#39;);<br><br>-- PostgreSQL actually stores:<br>-- &#39;ABC123              &#39;<br><br>SELECT LENGTH(sku) FROM products;<br>-- Returns 6 (trailing spaces are ignored)<br><br>-- DO: Use TEXT unless you need a length restriction<br>CREATE TABLE products (<br>  sku TEXT<br>);<br><br>-- If you need validation:<br>CREATE TABLE products (<br>  sku TEXT CHECK (LENGTH(sku) &lt;= 20)<br>);</pre><h3>4. The Temporal Trap: TIMESTAMP vs. TIMESTAMPTZ</h3><p>Engineering teams often say, <em>“We store everything in UTC in the app, so we don’t need timezones in the DB.”</em></p><p>This works until you need to run a report at the database level — like tracking “Daily Active Users in London.” If your database doesn’t store the zone offset, it can’t accurately calculate intervals or day boundaries across different regions. You end up with “logical drift” where your reporting data doesn’t match your application logic.</p><h4>The Fix: TIMESTAMPTZ</h4><p>Always use TIMESTAMPTZ. It stores the time in UTC internally but handles the timezone math automatically. It is the only safe choice for data that spans timezones.</p><pre>-- DON&#39;T: Stores a date/time with no timezone information<br>-- PostgreSQL has no way to know.<br>CREATE TABLE user_logins (<br>  login_at TIMESTAMP<br>);<br><br><br>-- DO: Store timezone-aware timestamps<br>-- PostgreSQL stores the moment in UTC internally<br>-- and can convert it safely for any timezone.<br><br>CREATE TABLE user_logins (<br>  login_at TIMESTAMPTZ<br>);<br><br>INSERT INTO user_logins (login_at)<br>VALUES (&#39;2026-03-29 01:30:00+00&#39;);<br><br><br></pre><h3>5. The “Lazy” Query: SELECT * and the Death of Index-Only Scans</h3><p>We know SELECT * is bad for network bandwidth, but for high-scale teams like <strong>Figma</strong>, the real damage is to <strong>I/O Efficiency.</strong></p><p>PostgreSQL has a powerful optimization called an <strong>Index-Only Scan</strong>. If your query only asks for columns that are already in an index, Postgres can skip reading the actual table (the “heap”) entirely. SELECT * breaks this optimization. It forces the database to fetch every single column from the disk, even if an index already had the 3 values you actually needed.</p><h4>The Fix: Selective Projection</h4><p>By simply listing the columns you need, you allow PostgreSQL to stay entirely within the index, often cutting your I/O requirements by 10x.</p><pre>-- DON&#39;T: Forces expensive disk reads (Heap Fetches)<br>SELECT * FROM files WHERE owner_id = 123;<br><br>-- DO: Enables ultra-fast Index-Only Scans<br>SELECT id, name, created_at FROM files WHERE owner_id = 123;</pre><p>PostgreSQL is extraordinarily powerful, but like any sophisticated tool, it rewards careful use and punishes carelessness. These anti-patterns have been identified through years of collective experience — each one represents real production issues that have bitten real developers.</p><h3>References &amp; Resources</h3><p><a href="https://wiki.postgresql.org/wiki/Don%27t_Do_This"><strong>https://wiki.postgresql.org/wiki/Don%27t_Do_This</strong></a></p><p><a href="https://www.uber.com/us/en/blog/postgres-to-mysql-migration/"><strong>https://www.uber.com/us/en/blog/postgres-to-mysql-migration/</strong></a></p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82b973c5cdb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why My 12 Million Row Table Was Slow: An Optimization Journey]]></title>
            <link>https://keroles-masoud.medium.com/why-my-12-million-row-table-was-slow-an-optimization-journey-898a3b12cb67?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/898a3b12cb67</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 17:13:37 GMT</pubDate>
            <atom:updated>2026-06-03T15:50:19.009Z</atom:updated>
            <content:encoded><![CDATA[<p>Management recently tasked me with generating a report on “bouncing users” from our legacy website activity. We are running a PHP/Laravel project, and we needed to analyze the data before migrating everything to a new infrastructure.</p><p>The system contains around <strong>12 million rows</strong> in the user_activity table. My job was to filter and aggregate records for users who visited only one page or stayed for less than 10 seconds.</p><p>At first, I ran the task using standard Laravel features. It worked fine in the local environment, but once I tested against the full 12-million-row production dataset, the process ground to a halt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAg_YuWZLN844jZbMIRhfQ.jpeg" /></figure><p>Instead of telling management we’d need a 3~4 days, I decided to measure where the bottlenecks actually were.</p><h3><strong>Before Any Optimization</strong></h3><pre>// The naive Laravel approach<br>UserActivity::query()<br>    -&gt;orderBy(&#39;created_at&#39;, &#39;asc&#39;)<br>    -&gt;chunk(500, function ($records) {<br>        foreach ($records as $record) {<br>            if ($this-&gt;isBounce($record)) {<br>                $this-&gt;addToReport($record);<br>            }<br>        }<br>    });</pre><p>The result? Roughly <strong>40 records per second</strong>. At that speed, processing 12 million rows would take over <strong>69 hours</strong>. I didn’t have three days; I had a few hours.</p><h3>Optimization Steps:</h3><h4>Step 1: No More Sorting</h4><p>The first major bottleneck was orderBy(&#39;created_at&#39;). While chronological order sounds nice, these logs are already stored sequentially by ID. Sorting 12 million rows without a specific composite index is a massive CPU and memory sink.</p><p>I swapped it to use the primary key:</p><pre>-&gt;orderBy(&#39;created_at&#39;, &#39;asc&#39;) // remove this <br>-&gt;orderBy(&#39;id&#39;, &#39;asc&#39;)        // Much faster</pre><p><strong>Result</strong>: Throughput jumped to <strong>750 records per second</strong>. A huge improvement, but still too slow for 12 million rows.</p><h4>Step 2: Ditch the ORM Hydration</h4><p>Eloquent is an amazing ORM, but “hydrating” 12 million records into heavy Model objects is extremely expensive. For a report like this, we don’t need Model features like relationships or accessors. I switched to Laravel’s Query Builder to get raw stdClass objects.</p><pre>// Switching from Models to Raw Query Builder<br>DB::table(&#39;user_activity&#39;)<br>    -&gt;orderBy(&#39;id&#39;)<br>    -&gt;chunk(1000, function ($rows) {<br>        foreach ($rows as $row) {<br>            // $row is a simple object, not an Eloquent Model<br>            if ($row-&gt;duration &lt; 10) {<br>                $this-&gt;stats[&#39;bounces&#39;]++;<br>            }<br>        }<br>    });</pre><p><strong>Result</strong>: Throughput reached <strong>2,100 records per second</strong>.</p><h4>Step 3: Offset vs. Cursors</h4><p>Standard chunk() in Laravel uses LIMIT and OFFSET. As the script progresses, the OFFSET becomes massive. The database has to scan millions of rows just to skip them and find the next batch.</p><p>I replaced chunk() with a manual cursor using the last processed ID:</p><pre>$lastId = 0;<br><br>while (true) {<br>    $rows = DB::table(&#39;user_activity&#39;)<br>        -&gt;where(&#39;id&#39;, &#39;&gt;&#39;, $lastId)<br>        -&gt;limit(2000)<br>        -&gt;get();<br><br>    if ($rows-&gt;isEmpty()) break;<br><br>    foreach ($rows as $row) {<br>        $this-&gt;process($row);<br>        $lastId = $row-&gt;id;      // Track the cursor<br>    }<br>}</pre><p><strong>Result</strong>: Steady performance at <strong>4,800 records per second</strong>, regardless of how far into the dataset we were.</p><blockquote><strong>Laravel Pro-Tip:</strong> You can achieve this exact same behavior natively using Laravel’s chunkById() method, which automatically handles the ID tracking for you!</blockquote><h4>Step 4: The Final Boss Explicit Transactions</h4><p>The biggest hidden bottleneck in most Laravel projects isn’t PHP it’s the Disk I/O. By default, every database change is an implicit commit, forcing the database to call fsync() to ensure the data is written to disk. 12 million updates = 12 million disk syncs.</p><p>I wrapped the entire loop in an explicit transaction to batch the commits.</p><pre>DB::transaction(function () {<br>    $lastId = 0;<br>    while ($rows = $this-&gt;fetchBatch($lastId)) {<br>        foreach ($rows as $row) {<br>            $this-&gt;saveBouncingUser($row);<br>            $lastId = $row-&gt;id;<br>        }<br>    }<br>});</pre><p>By reducing the frequency of disk synchronization, the database can process data much faster.</p><p><strong>Final Result</strong>: A blazing <strong>19,500 records per second</strong>.</p><h3>The Ultimate Scoreboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*blL5z6bg1VFBZwb-xk8kHA.png" /><figcaption>Scoreboard</figcaption></figure><h3>Conclusion</h3><p>By mapping out our bottlenecks, we transformed a 3-day nightmare into a task that finishes in <strong>just over 10 minutes </strong>all within a standard Laravel environment without installing any heavy data infra.</p><p>The lessons for any developer are:</p><ol><li><strong>Ditch the ORM</strong> for mass data processing.</li><li><strong>Avoid OFFSET</strong> in large tables; use cursors.</li><li><strong>Use Transactions</strong> to minimize Disk I/O overhead.</li></ol><p>Now management has their report, our server didn’t crash, and the application is running more efficiently than ever.</p><p>How are you handling large-scale reporting tasks in your projects? Let me know in the comments below</p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898a3b12cb67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Record vs Entity: How My Thinking Changed from Laravel to Spring Boot]]></title>
            <link>https://keroles-masoud.medium.com/active-record-vs-entity-how-my-thinking-changed-from-laravel-to-spring-boot-c09ef0624e9d?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09ef0624e9d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 09:49:38 GMT</pubDate>
            <atom:updated>2026-02-09T09:49:38.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello my software engineer friends Today I want to share part of my programming journey — not through frameworks, but through <strong>how my way of thinking evolved</strong>.</p><p>I started my backend career with <strong>Laravel</strong>, where everything felt fast, productive, and intuitive. Later, I moved to <strong>Node.js</strong> (NestJS) and eventually to <strong>Spring Boot</strong>, and that’s when I realized something important:</p><p>One of the biggest shifts I experienced was moving from <strong>Active Record models</strong> to <strong>Entity-based (Data Mapper) models</strong>. At first, it felt uncomfortable and unnecessary. Over time, it became one of the most valuable lessons in my backend journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMGiIEZqBP1cPeuxCi1lAw.png" /><figcaption>Active Record VS Entity</figcaption></figure><h3>Active Record in Laravel</h3><p>In Laravel, models follow the <strong>Active Record</strong> pattern.<br>This means the model represents <strong>both the data and the behavior that persists it</strong>.</p><p>A simple example(Active Record):</p><pre>class User extends Model<br>{<br>    // The model &quot;knows&quot; how to save itself<br>    protected $fillable = [&#39;name&#39;, &#39;email&#39;];<br>}<br><br>// Usage:<br>$user = new User();<br>$user-&gt;name = &quot;John&quot;;<br>$user-&gt;save(); // Active Record style</pre><p>In this world, the User model is a &quot;One-Stop Shop.&quot; It:</p><ul><li><strong>Queries itself:</strong> User::all()</li><li><strong>Persists itself:</strong> $user-&gt;save()</li><li><strong>Handles its own logic:</strong> often containing custom methods like $user-&gt;isAdmin()</li></ul><h4>Why Active Record Feels So Good at First</h4><ul><li>When I first started my journey, this felt amazing. I wasn’t fighting the framework; I was building. Laravel makes you productive immediately because:</li><li><strong>Speed is King:</strong> You can go from composer create-project to a working API in minutes.</li><li><strong>Zero “Red Tape”:</strong> You don’t have to think about repositories, persistence layers, or complex architecture , you think about <strong>shipping features</strong>.</li><li><strong>Code Readability:</strong> The code looks like English. It’s elegant and approachable.</li></ul><p><strong>Honestly? That’s a huge win.</strong> For a lot of projects, this is all the architecture you will ever need. It wasn’t until my projects grew in complexity that I started to see where the cracks begin to show.</p><h3>The Shift to Entity-Based Design (Node.js &amp; Spring Boot)</h3><p>As my journey took me into the worlds of <strong>NestJS</strong> and <strong>Spring Boot</strong>, I hit a wall. The “Smart Models” I loved in Laravel were gone. In their place was a more decoupled duo: <strong>Entities and Repositories</strong>.</p><h3>The TypeORM Approach (NestJS/Node.js)</h3><p>In NestJS, you stop asking the object to save itself. Instead, you describe the data and let a “Manager” handle the rest.</p><pre>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  name: string;<br>}<br><br>// Usage in a Service:<br>// Instead of user.save(), we use:<br>await this.userRepository.save(user);</pre><h4>The “Final Boss”: Spring Boot &amp; JPA</h4><p>Spring Boot takes this separation even further. The Entity becomes a pure <strong>POJO</strong> (Plain Old Java Object) it’s essentially a “dumb” container for data.</p><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br>    // Getters and Setters only<br>}<br><br>// The Persistence Logic (The &quot;How&quot;)<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    // Logic is completely abstracted away<br>}</pre><h3>The Major Realization</h3><p>This shift was more than just adding more files; it was a change in philosophy. I noticed three major differences:</p><ol><li><strong>Passive vs. Active:</strong> The User entity no longer &quot;knows&quot; about the database. It’s just a blueprint of the business concept.</li><li><strong>The Repository as a Gatekeeper:</strong> Persistence is handled by a repository. If I want to change how users are saved (moving from MySQL to a Mock for testing), I only change the repository, not the model.</li><li><strong>Domain Focus:</strong> Entities began to represent <strong>real business concepts</strong>, not just database rows.</li></ol><p>Initially, this felt like “over-engineering.” Why write more code for the same result? But as my projects grew, I realized that <strong>Repositories are implementation details</strong>, and keeping them separate from the <strong>Domain (Entities)</strong> is what allows a codebase to scale without turning into spaghetti.</p><h3>Active Record Pros and Cons from Experience</h3><p>Active Record is compact, convenient, and ready to go immediately.</p><h4><strong>Pros:</strong></h4><ul><li><strong>Developer Velocity:</strong> You can build a prototype in hours. The syntax is incredibly intuitive ($user-&gt;save()).</li><li><strong>Low Cognitive Load:</strong> You don’t have to jump between five different files (Service, Repository, Entity, DTO) just to update a single column.</li><li><strong>Readable:</strong> For simple CRUD applications, the code reads like a sentence.</li></ul><h4><strong>Cons:</strong></h4><ul><li><strong>The “Fat Model” Problem:</strong> Over time your models become cluttered with business logic, validation, and database hooks.</li><li><strong>Testing Hurdles:</strong> Because the model is tied to the database, writing “pure” unit tests is difficult. You often end up writing integration tests that require a database connection, which slows down your CI/CD pipeline.</li></ul><h3>Entity-Based / Data Mapper Pros and Cons from Experience</h3><p>The Data Mapper pattern is like a “Professional Workshop.” Everything has its own drawer, and the tools never touch the raw materials until they have to.</p><h4><strong>Pros:</strong></h4><ul><li><strong>Strict Separation of Concerns:</strong> Your User entity is just data. It doesn&#39;t care if it&#39;s being saved to PostgreSQL, MongoDB, or an in-memory array.</li><li><strong>Superior Testability:</strong> You can test your business logic in isolation by mocking the Repository interface. This makes for a very robust and fast test suite.</li><li><strong>Maintainability at Scale:</strong> In large teams, this structure prevents developers from taking “shortcuts” that lead to messy codebases.</li></ul><h4><strong>Cons:</strong></h4><ul><li><strong>Boilerplate Fatigue:</strong> You’ll find yourself writing a lot of “glue code.” Creating a new table requires an Entity, a Repository, and often a Service layer.</li><li><strong>Steep Learning Curve:</strong> For juniors, the abstraction layers can be confusing. “Why do I need a Repository just to find a user by ID?” is a common frustration.</li></ul><h3>Conclusion: The Right Tool for the Right Journey</h3><p>Looking back at my path from <strong>Laravel</strong> to <strong>NestJS</strong> and <strong>Spring Boot</strong>, I’ve realized that the debate between Active Record and Entity-based design isn’t about which one is “better” it’s about <strong>trade-offs</strong>.</p><ul><li><strong>Active Record (Laravel)</strong> taught me the value of <strong>velocity</strong>. It showed me that when you need to validate an idea and ship a product quickly, reducing friction is the most important thing you can do.</li><li><strong>Entity-Based Design (NestJS/Spring Boot)</strong> taught me the value of <strong>architecture</strong>. It showed me how to build systems that are resilient to change, easy to test, and structured enough to survive years of scaling.</li></ul><h4>My Rule of Thumb</h4><p>If you are asking yourself which one to choose for your next project, here is my takeaway from the trenches:</p><ol><li><strong>Choose Active Record</strong> if you are a small team, building an MVP, or working on a project where the database schema and the business logic are almost identical.</li><li><strong>Choose Entity-Based (Data Mapper)</strong> if you are working in a large-scale enterprise environment, where business rules are complex, and you need the flexibility to mock your database for high-coverage unit testing.</li></ol><p>My journey across these three ecosystems made me a more versatile engineer. I no longer see “boilerplate” as a nuisance or “magic methods” as a shortcut. Instead, I see them as architectural choices that serve a specific purpose.</p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09ef0624e9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Silent Debt: A Systematic Guide to Refactoring Legacy Code]]></title>
            <link>https://keroles-masoud.medium.com/the-silent-debt-a-systematic-guide-to-refactoring-legacy-code-dc50059205df?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc50059205df</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[legacy]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[technical-debt]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 22:40:39 GMT</pubDate>
            <atom:updated>2026-02-03T22:46:11.129Z</atom:updated>
            <content:encoded><![CDATA[<p>We, as software engineers, are always told that we might disagree with the business, but we operate on the principle that technology serves the business. This sometimes leads us to write incorrect code and neglect regular code maintenance. Failing to ensure the code is well-written and thoroughly tested results, over time, in poor-quality code that is difficult to maintain and read. This isn’t just an aesthetic problem; it’s a silent erosion of our ability to innovate, respond to market changes, and ultimately, serve the business effectively. This is the story of how our submitOrder function became the poster child for this very dilemma, and our journey to reclaim it</p><p>Every developer knows the internal struggle: <strong>Do I add one more line to the mess to meet a deadline, or do I stop the bleeding and rebuild it the right way?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcFKi85PbwrqAQ0j5wHBZA.png" /><figcaption>Refactoring Legacy Code Fork</figcaption></figure><h3>The Refactoring Crossroads</h3><p>As a new developer joining an existing project, my first major task was to modify the submitOrder function. To the business, it was just another ticket. To me, it was a horror story.</p><p>The function was a <strong>“God-Controller”</strong>: hundreds of lines of raw SQL, business rules, and validation logic mashed together. Every time I asked why a line existed, the answer was: <em>“It’s been there for years; don’t touch it or the whole system might break.”</em></p><p>I realized then that to be a responsible engineer, I had to stop being a “patch-fixer” and become a “refactorer.” We couldn’t build a skyscraper on a swamp; we needed a solid foundation.</p><h3>The Turning Point: From a “Ticking Time Bomb” to a Strategy</h3><p>Coming in as the new developer, I quickly realized that my most important responsibility wasn’t writing new code it was managing risk. So I sat down with my manager and laid out the reality. I didn’t describe the code as merely “ugly” or “messy.” I explained that we were sitting on a ticking time bomb.</p><h4>The Hard Conversation</h4><p>I told my manager: <em>“</em><strong><em>We aren’t just adding a feature; we are taking out a high-interest loan.</em></strong><em>”</em></p><p>I shifted the conversation from code aesthetics to business risk. I highlighted that the lack of separation of concerns meant a small bug in a discount calculation could accidentally crash the entire checkout flow. In legacy code, ‘fast’ is an illusion — eventually, the debt collectors come calling in the form of production outages.</p><p>The issue wasn’t code aesthetics. It was the absence of:</p><ul><li>Separation of concerns</li><li>Explicit domain boundaries</li><li>Testable units</li><li>Confidence in behavioral consistency</li></ul><p>Left untouched, the system would eventually reach a point where change became more dangerous than stagnation.</p><h3>The Proposed Two-Track Strategy: Isolating Risk While Refactoring</h3><p>To move forward without jeopardizing production stability, I proposed a Two-Track Strategy designed to minimize risk while enabling structural change.</p><p><strong>Track A: Production Stability</strong><br> The existing submitOrder implementation remains untouched and continues serving live traffic. No refactors, no optimizations, no behavior changes. This preserves known behavior and eliminates regression risk for current users.</p><p><strong>Track B: Parallel V2 Architecture</strong><br> In parallel, we rebuild the same functionality behind a V2 API using a layered architecture.</p><h3>The Final Business Decision</h3><p>At that point, the conversation shifted. I wasn’t asking for “cleanup time” anymore, I was proposing a form of insurance. The manager agreed to the refactor on one condition: the new implementation had to produce the exact same results as the old one.</p><p>By framing refactoring as a way to protect the business from its own legacy debt, I turned a purely technical concern into a strategic decision and that made all the difference.</p><h3>The Execution: A Disciplined Path to Clean Code</h3><p>Refactoring a “God-Controller” requires more than just moving code around; it requires a systematic approach to ensure that business logic is preserved while the architecture is transformed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsYj9D026CVtFA97MNmqUw.png" /><figcaption>Refactor Strategy</figcaption></figure><h4>Step 1: Establishing the Golden Standard</h4><p>Before changing a single line, I treated the legacy code as a “Black Box.” I wrote high-level <strong>Feature Tests</strong> that recorded not just the API response, but the exact state of the database. If the legacy code created five rows across three tables, my refactor had to do the exact same. This “snapshot” became my insurance policy against regressions.</p><h4>Step 2: Breaking the Monolith (Strangler Pattern)</h4><p>I dismantled the monolith wire by wire using a layered architecture:</p><ul><li><strong>DTOs:</strong> To sanitize input before it ever touched our business logic.</li><li><strong>Service Layer:</strong> To house the “Company Brain” rules for taxes, inventory, and logic.</li><li><strong>Repositories:</strong> To bury the raw SQL, making the database an implementation detail rather than a controller responsibility.”</li></ul><h4>Step 3: The Mirror Test</h4><p>We deployed /api/v2/submit-order in a shadow environment. We ran identical payloads through V1 and V2 and compared the results bit-for-bit. When I could show the manager a dashboard showing that V2 was producing 100% identical results to V1 but with 50% less cognitive load the decision to switch was easy. We didn&#39;t just guess it worked; we proved it.&quot;</p><h3>The Results: Beyond the Code</h3><p>When we finally flipped the switch and routed traffic to the refactored submitOrder function, the transition was silent. No 3:00 AM alerts, no corrupted database entries, and no panicked Slack messages from the support team.</p><p>But the real victory wasn’t just a lack of bugs. The real wins were:</p><ul><li><strong>Velocity</strong>: Two weeks later, when the business asked to add a new “Buy Now, Pay Later” option, it took two days instead of two weeks.</li><li><strong>Onboarding</strong>: The next developer who joins the project won’t have to spend a month “learning the mess.” They can read the OrderService and understand the business in an hour.</li><li><strong>Trust</strong>: By delivering a refactor that didn’t break the world, I earned the “Engineering Trust” necessary to tackle the next legacy piece of the puzzle.</li></ul><h3>Conclusion: Engineering is Stewardship</h3><p>We often treat “Business” and “Engineering” as two opposing forces. We think the business wants speed and we want quality. But this project taught me that <strong>Quality IS Speed</strong>. Poor code is a high-interest loan. You might get the feature out today, but the interest payments in the form of bugs, slow development, and developer burnout will eventually bankrupt the project.</p><p>As software engineers, we are the stewards of the company’s most valuable asset. Our job isn’t just to say “yes” to every deadline; it’s to ensure that when the business is ready to grow, the technology is ready to support it. Refactoring the submitOrder function wasn&#39;t about making the code look pretty it was about ensuring the heart of our application could keep beating for years to come.</p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc50059205df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Code Worked Until It Hit #100 : Why Tests Matter More Than You Think]]></title>
            <link>https://keroles-masoud.medium.com/my-code-worked-until-it-hit-100-why-tests-matter-more-than-you-think-e951b581ecd7?source=rss-d08b4b9e6570------2</link>
            <guid isPermaLink="false">https://medium.com/p/e951b581ecd7</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Keroles Massoud]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 11:48:58 GMT</pubDate>
            <atom:updated>2026-01-29T11:52:46.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>My Code Worked Until It Hit #100 : Why Tests Matter More Than You Think</h3><p>At some point in every developer’s career, there comes a moment when your confidence in a system quietly disappears.</p><p>The code still runs. Servers are up. Users are active.</p><p>But deep down something feels fragile.</p><p>That’s when you realize:<br><strong>“It works” does not mean “it’s safe.”</strong></p><p>This article is about one of those moments: a production issue, a legacy system, and a painful reminder of why testing isn’t optional it’s survival.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dttJVhpXZYxQTq9-y_nAA.png" /></figure><h3><strong><em>Why This Became a Production Problem</em></strong></h3><p>It was a Tuesday morning. A small production dashboard alert blinked but this one was different. It wasn’t red. It wasn’t even loud. It was quiet. Too quiet. That’s when I saw it: <strong>code that ‘worked’ but was secretly broken.</strong></p><p>As programmers, we often inherit legacy systems written months or even years ago. Sometimes by other developers. And sometimes by our past selves 😅.</p><p>I’m currently working on modifying an old system, and one of my main tasks is fixing a series of unexpected production issues. At first glance, everything looked fine. The code had been running in production for a long time. No syntax errors. No crashes. Nothing obviously broken.</p><p>But then the strange things started happening:</p><ul><li>Incorrect results</li><li>Edge cases behaving unpredictably</li><li>Logic that no longer made sense</li></ul><p>So I did what any developer would do. I opened the code and started reading it line by line. I followed the execution flow, analyzed the conditions, and traced how data moved through the system.</p><p>The deeper I went, the clearer the real problem became.</p><p><strong>There were no tests.<br>No unit tests.<br>No integration tests.<br>No safety net at all.</strong></p><p>Every change felt risky. Fixing one issue could easily introduce another. Even the smallest refactor came with the fear of breaking something in a completely unrelated part of the system.</p><p>That moment reminded me of something we often ignore when deadlines are tight and pressure is high:</p><p><strong>Testing is not optional.</strong><br><strong>Testing is what protects your code and your system.</strong></p><h3>“It Works” Is Not the Same as “It’s Correct”</h3><p>I was working on a legacy system where we generate sequential codes for different entities: <strong>orders, offers, wallets, refunds, and users.</strong></p><p>The logic was centralized in a helper function. Clean. Reusable. Transaction-safe. Even used database locking to avoid race conditions.</p><p>Or so I thought.</p><p>Here’s the<strong> old function</strong> that had been running happily in production:</p><pre>function generate_sequence_code(string $type, string $prefix = &#39;&#39;): string<br>{<br>    $date = now()-&gt;format(&#39;ymd&#39;);<br>    $like = $prefix . $date . &#39;%&#39;;<br><br>    $map = [<br>        &#39;order&#39; =&gt; [&#39;table&#39; =&gt; &#39;service_orders&#39;, &#39;column&#39; =&gt; &#39;order_num&#39;],<br>        &#39;offer&#39; =&gt; [&#39;table&#39; =&gt; &#39;offers&#39;, &#39;column&#39; =&gt; &#39;slug&#39;],<br>        &#39;wallet&#39; =&gt; [&#39;table&#39; =&gt; &#39;wallet&#39;, &#39;column&#39; =&gt; &#39;process_code&#39;],<br>        &#39;refund&#39; =&gt; [&#39;table&#39; =&gt; &#39;refund_requests&#39;, &#39;column&#39; =&gt; &#39;request_number&#39;],<br>        &#39;lead&#39; =&gt; [&#39;table&#39; =&gt; &#39;complains&#39;, &#39;column&#39; =&gt; &#39;slug&#39;],<br>        &#39;user&#39; =&gt; [&#39;table&#39; =&gt; &#39;app_users&#39;, &#39;column&#39; =&gt; &#39;slug&#39;],<br>    ];<br><br>    if (!isset($map[$type])) {<br>        throw new InvalidArgumentException(&quot;Unknown sequence type: {$type}&quot;);<br>    }<br><br>    $table  = $map[$type][&#39;table&#39;];<br>    $column = $map[$type][&#39;column&#39;];<br><br>    return DB::transaction(function () use ($table, $column, $like, $prefix, $date) {<br>        $lastCode = DB::table($table)<br>            -&gt;where($column, &#39;like&#39;, $like)<br>            -&gt;lockForUpdate()<br>            -&gt;max($column);<br><br>        $next = 1;<br><br>        if ($lastCode) {<br>            $lastNumber = intval(substr($lastCode, -2));<br>            $next = $lastNumber + 1;<br>        }<br><br>        return $prefix . $date . str_pad($next, 2, &#39;0&#39;, STR_PAD_LEFT);<br>    });<br>}<br></pre><p>It worked… until it didn’t.</p><h3>Why I Didn’t Trust My Slug Generator Until Sequence #100</h3><p>We all know the story. You write a “simple” utility function. It passes your manual tests in your local environment. You ship it.</p><p>It’s just a string generator, right? What could go wrong?</p><p>In my case, the sequence generator worked perfectly until it hit its 100th record of the day.</p><p>I decided to finally write automated tests. Not because it was broken, but because I wanted <strong>confidence before touching it</strong>.</p><p>And that’s when I discovered the problem:</p><pre>Sequence 99 → ORD24010199  -&gt; ok<br>Sequence 100 → ORD240101100 -&gt; ERR<br>Sequence 101 → ORD24010101 -&gt; ERR</pre><p>The function assumed the sequence part was always two digits (substr($lastCode, -2)). At 100+, it silently started generating duplicate IDs. The system didn’t crash it just quietly corrupted data.</p><p>A single unit test that iterated 101 times exposed the flaw instantly. What could have been a 2:00 AM production emergency became a 10-minute refactor.</p><h3>The Refactor: Accuracy over Assumptions</h3><p>The new version is more surgical. Instead of guessing where the number is, we calculate it based on the prefix and the date string length.</p><pre>function generate_sequence_code(string $type, string $prefix = &#39;&#39;): string<br>{<br>    $date = now()-&gt;format(&#39;ymd&#39;);<br>    $like = $prefix . $date . &#39;%&#39;;<br><br>    $map = [<br>        &#39;order&#39;  =&gt; [&#39;table&#39; =&gt; &#39;service_orders&#39;, &#39;column&#39; =&gt; &#39;order_num&#39;],<br>        &#39;offer&#39;  =&gt; [&#39;table&#39; =&gt; &#39;offers&#39;, &#39;column&#39; =&gt; &#39;slug&#39;],<br>        &#39;wallet&#39; =&gt; [&#39;table&#39; =&gt; &#39;wallet&#39;, &#39;column&#39; =&gt; &#39;process_code&#39;],<br>        &#39;refund&#39; =&gt; [&#39;table&#39; =&gt; &#39;refund_requests&#39;, &#39;column&#39; =&gt; &#39;request_number&#39;],<br>        &#39;lead&#39;   =&gt; [&#39;table&#39; =&gt; &#39;complains&#39;, &#39;column&#39; =&gt; &#39;slug&#39;],<br>        &#39;user&#39;   =&gt; [&#39;table&#39; =&gt; &#39;app_users&#39;, &#39;column&#39; =&gt; &#39;slug&#39;],<br>    ];<br><br>    if (!isset($map[$type])) {<br>        throw new InvalidArgumentException(&quot;Unknown sequence type: {$type}&quot;);<br>    }<br><br>    $table  = $map[$type][&#39;table&#39;];<br>    $column = $map[$type][&#39;column&#39;];<br><br>    return DB::transaction(function () use ($table, $column, $like, $prefix, $date) {<br><br>        $lastCode = DB::table($table)<br>            -&gt;where($column, &#39;like&#39;, $like)<br>            -&gt;lockForUpdate()<br>            -&gt;orderByDesc($column)<br>            -&gt;value($column);<br><br>        $next = 1;<br><br>        if ($lastCode) {<br>            $withoutPrefix = substr($lastCode, strlen($prefix));<br>            $sequencePart  = substr($withoutPrefix, 6); // after yymmdd<br>            $next = ((int) $sequencePart) + 1;<br>        }<br><br>        return $prefix . $date . str_pad($next, 2, &#39;0&#39;, STR_PAD_LEFT);<br>    });<br>}</pre><h4>Why this is better:</h4><ol><li><strong>Dynamic Offsets:</strong> It doesn’t matter how long your prefix is; we calculate the starting point of the sequence dynamically.</li><li><strong>Reliable Sorting:</strong> We switched from max() to orderByDesc()-&gt;value(), which is often more predictable with indexed string columns.</li><li><strong>Concurrency Safety:</strong> We kept the lockForUpdate(), because testing isn&#39;t just about the math, it&#39;s about surviving 50 people hitting that function at the exact same microsecond.</li></ol><h3>Why Testing Actually Matters</h3><p>When we talk about testing, developers often think of it as an extra chore a “tax” we pay on our time. But my experience with this sequence bug reminded me that testing isn’t about the code you’re writing <em>today, </em>it’s about the reality of tomorrow.</p><h4>1. Confidence to Refactor</h4><p>Without tests, old code becomes “haunted.” You see a line like substr($lastCode, -2) and you think, <em>&quot;That looks suspicious,&quot;</em> but you’re too afraid to change it because you don&#39;t know what else might break. A good test suite acts as a safety net, giving you the courage to clean up technical debt without the fear of a production meltdown.</p><h4>2. Identifying “Silent” Failures</h4><p>The scariest bugs aren’t the ones that throw a 500 Internal Server Error. The scariest bugs are the ones that work &quot;wrongly&quot; but quietly. In my case, the system was happy to generate duplicate IDs. There were no error logs, no red flags, just corrupted data slowly piling up in the database. Automated tests catch logic flaws that a human manual test will almost always overlook.</p><h4>3. Edge Cases Are Where Your Users Live</h4><p>As developers, we often test the “Happy Path” (sequences 1, 2, 3…). But “Edge Cases” like sequence #100, leap years, or empty strings, are exactly where real-world users eventually land. Testing forces you to think like a pessimist: <em>“What happens when this hits a thousand? What happens if two people click this at once?”</em></p><h4>4. Documentation for the Next Person</h4><p>A test is the most honest form of documentation. It tells the next developer (who might be you six months from now): <em>“This is how this function is supposed to behave.”</em> It explains the <strong>intent</strong> behind the code better than a comment ever could.</p><h3>The Final Lesson</h3><p>If there is one thing this refactor taught me, it’s this: <strong>Working code is not the same as proven code.</strong> We often treat production like a final exam, but production is not a test environment. By the time your code hits the real world, the “hope” that it works should already be replaced by data.</p><h3>Let’s be honest:</h3><ul><li><strong>Edge cases are not optional:</strong> They are inevitable. Sequence #100 is coming, whether you’re ready for it or not.</li><li><strong>Confidence is earned, not felt:</strong> Real confidence comes from a green checkmark in your CI/CD pipeline, not from “feeling” like the logic is solid.</li><li><strong>Fear is a signal:</strong> If you are maintaining legacy code and you’re nervous about touching a specific function — <strong>listen to that fear.</strong> It is a signal that your code is undocumented and unprotected.</li></ul><p><strong>Write the tests.</strong><br>They don’t slow you down. They save you from moving backward.</p><p><strong>Because hope never guarantees correctness tests do.</strong></p><p>— <br><strong>Keroles Masoud<br></strong>Backend Engineer</p><p><strong>GitHub:</strong> <a href="https://github.com/boiar">https://github.com/boiar</a><br><strong>LinkedIn:</strong> <a href="https://www.linkedin.com/in/keroles-masoud">https://www.linkedin.com/in/keroles-masoud</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e951b581ecd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>