<?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 Ahmad Ammar Musyaffa on Medium]]></title>
        <description><![CDATA[Stories by Ahmad Ammar Musyaffa on Medium]]></description>
        <link>https://medium.com/@ammarmusyaffa?source=rss-7f7079ab82a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lqB7hUzMxH2sWNHwTIog6g.png</url>
            <title>Stories by Ahmad Ammar Musyaffa on Medium</title>
            <link>https://medium.com/@ammarmusyaffa?source=rss-7f7079ab82a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 13:21:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ammarmusyaffa/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[The Hidden Cost of Trusting Client-Side Payloads]]></title>
            <link>https://medium.com/@ammarmusyaffa/the-hidden-cost-of-trusting-client-side-payloads-057fc8649e09?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/057fc8649e09</guid>
            <category><![CDATA[payment-security]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[app-security]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 11:38:34 GMT</pubDate>
            <atom:updated>2026-09-26T11:38:34.555Z</atom:updated>
            <content:encoded><![CDATA[<p>A field guide to why “never trust the client” hits hardest in payment integrations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tddRNIOGXnnDphtV91ktnQ.png" /></figure><p>Picture the first time you wire up a payment gateway. The docs are clean, the sandbox works on the first try, and the flow feels almost too simple: user clicks “Subscribe,” frontend builds a JSON payload, backend forwards it to the gateway, money moves. You ship it.</p><pre>POST /api/subscribe<br>{<br>  &quot;userId&quot;: &quot;u_8827&quot;,<br>  &quot;planName&quot;: &quot;premium&quot;,<br>  &quot;amount&quot;: 35000<br>}</pre><p>It works. QA signs off and nobody thinks twice because functionally, nothing is wrong. The subscription gets created, the gateway charges the card, the receipt looks correct. The bug isn’t in the happy path, it’s in the fact that this payload assumes the client is telling the truth.</p><h3>The Exploit Is Embarrassingly Simple</h3><p>Open dev tools, go to the Network tab, find the subscribe request, right-click, “Copy as cURL.” Now you have this:</p><pre>curl -X POST https://api.my-simple-app.com/api/subscribe \<br>  -H &quot;Authorization: Bearer &lt;valid-user-token&gt;&quot; \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;userId&quot;:&quot;u_8827&quot;,&quot;planName&quot;:&quot;premium&quot;,&quot;amount&quot;:35000}&#39;</pre><p>Nothing stops anyone from editing one field before hitting send:</p><pre>-d &#39;{&quot;userId&quot;:&quot;u_8827&quot;,&quot;planName&quot;:&quot;premium&quot;,&quot;amount&quot;:1}&#39;</pre><p>If your backend’s only job is to relay amount to the payment gateway and record planName in the database, this request succeeds. The user is now a &quot;premium&quot; subscriber who paid 100 rupiah instead of 35,000. Multiply that by however many users find the same trick — this isn&#39;t a hypothetical rounding error, it&#39;s a direct revenue leak, and it&#39;s the kind of bug that doesn&#39;t show up in a stack trace. It shows up three weeks later in a finance report that doesn&#39;t reconcile, and by then you&#39;re doing archaeology on transaction logs instead of fixing a five-line validation gap.</p><h3>The Root Cause: Your Client Is Not a Source of Truth</h3><p>The deeper problem isn’t “we forgot to validate amount.&quot; It&#39;s a design decision made earlier which is letting the client describe <em>business facts</em> instead of <em>business intent</em>.</p><p>There’s a useful line to draw here:</p><ul><li><strong>Intent: </strong>what the user wants to do. <em>“I want to subscribe to the premium plan.”</em></li><li><strong>Fact: </strong>what that actually means in business terms. <em>Premium costs 35,000 IDR/month, lasts 30 days, unlocks features X and Y.</em></li></ul><p>The client should only ever be allowed to express intent. Facts belong to the server, because the server is the only party with the authority and the incentive to keep them correct. The moment amount travels from client to server as a plain field, you&#39;ve quietly promoted the client to co-author of your pricing model.</p><p>The same logic applies to userId, and honestly, this one is worse. If userId comes from the request body instead of the authenticated session, you&#39;re not just risking a wrong price, you&#39;re risking <strong>IDOR</strong> (Insecure Direct Object Reference). Nothing stops a malicious actor from swapping userId and creating or modifying subscriptions that belong to someone else entirely. A tampered amount costs you money. A tampered userId costs you a user&#39;s trust, and potentially a compliance headache.</p><h3>The Fix: Move the Payload’s Center of Gravity to the Server</h3><p>The fix isn’t more validation rules bolted onto the existing payload, it’s shrinking the payload until the client can’t lie about anything that matters.</p><pre>POST /api/subscribe<br>{<br>  &quot;planId&quot;: &quot;plan_premium_monthly&quot;<br>}</pre><p>That’s it. No amount, no planName, no userId. The client states <em>which plan it wants</em>; everything else is resolved server-side from data the client never touches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*bXYoxH4C27vThVBW8ZA2QQ.png" /></figure><p>Three things changed, and each one closes a specific hole:</p><ol><li><strong>userId</strong> now comes from the verified JWT/session on the server, never from the body. A user can only ever transact as themselves.</li><li><strong>amount and </strong><strong>planName</strong> are looked up from a plans table the client has no write access to. There&#39;s no field left to tamper with because there&#39;s no field carrying that data.</li><li><strong>The order record stores a price snapshot</strong> taken at creation time, not a live reference to the plans table. If you bump Premium from 35,000 to 40,000 next quarter, last month&#39;s invoices shouldn&#39;t silently reprice themselves. This is a detail that&#39;s easy to skip and annoying to fix retroactively once your finance team notices historical orders don&#39;t match current plan prices.</li><li>This is the Single Source of Truth principle applied narrowly: for any data that determines money changing hands, there is exactly one place allowed to define it, and it’s not the browser.</li></ol><h3>The Second Trap: Trusting the Callback, Not the Webhook</h3><p>Fixing the request payload closes the front door. Most teams then walk straight through the back door which is trusting the <em>confirmation</em> the same way they trusted the <em>request</em>.</p><p>A common pattern after redirecting from a payment gateway looks like this:</p><pre>https://my-simple-app.com/payment/success?orderId=ord_991&amp;status=success</pre><p>And the corresponding frontend code:</p><pre>if (query.status === &quot;success&quot;) {<br>  markOrderAsPaid(query.orderId); // don&#39;t do this<br>}</pre><p>This is the same mistake wearing a different hat. status=success is just a query parameter, anyone can construct that URL and hit it directly, whether or not any money actually moved. Client-side redirects are a UX signal, not a payment confirmation.</p><p>The only trustworthy confirmation is the gateway’s <strong>server-to-server webhook</strong>, verified with a <strong>signature check.</strong></p><pre>app.post(&#39;/webhooks/payment&#39;, (req, res) =&gt; {<br>  const signature = req.headers[&#39;x-gateway-signature&#39;];<br>  const expected = computeHmac(req.rawBody, WEBHOOK_SECRET);<br><br>  if (!timingSafeEqual(signature, expected)) {<br>    return res.status(401).send(&#39;invalid signature&#39;);<br>  }<br><br>  const { orderId, amount, status } = req.body;<br>  const order = db.orders.findById(orderId);<br><br>  // Reconcile: the amount the gateway confirms must match<br>  // what you recorded when the order was created.<br>  if (order.amount !== amount) {<br>    flagForManualReview(order);<br>    return res.status(200).send(&#39;ok&#39;); // ack, but don&#39;t mark as paid<br>  }<br><br>  if (status === &#39;success&#39;) markOrderAsPaid(orderId);<br>  res.status(200).send(&#39;ok&#39;);<br>});</pre><p>Two details worth calling out, since they’re easy to skip once the signature check is in place and everything “looks secure”:</p><ul><li><strong>Idempotency.</strong> Gateways retry webhooks. If your handler isn’t idempotent, a retried webhook can double-fulfill an order and granting two months of access for one payment, or worse, double-crediting a wallet. Key your processing on the gateway’s event ID, not just the order ID.</li><li><strong>Amount reconciliation.</strong> Verifying the signature proves the webhook came from the gateway. It doesn’t prove the amount matches what you expected. Always compare the webhook’s amount against your stored order snapshot before marking anything as paid, this is the same &quot;don&#39;t trust it just because it arrived&quot; instinct, applied to server-to-server traffic instead of client traffic.</li></ul><h3>Takeaways</h3><ul><li>Client payloads should express <strong>intent</strong> (planId), never <strong>facts</strong> (amount, planName, price).</li><li>userId is derived from the authenticated session/token, it should never be a field the client can set.</li><li>Snapshot prices at transaction time, don’t let historical orders drift when your pricing changes later.</li><li>A redirect query string is a UX hint, not payment confirmation. Only a signature-verified webhook can mark an order as paid.</li><li>Reconcile the amount in the webhook against the amount you recorded when the order was created, a valid signature doesn’t guarantee a matching amount.</li><li>Make webhook handlers idempotent like with gateways retry and retries shouldn’t double-fulfill anything.</li><li>As a general rule for any third-party integration, not just payments: the client requests, the server decides.</li></ul><p>The pattern underneath all of this is the same sentence, applied twice: the backend is the only party allowed to define what something costs, and the only party allowed to confirm that it was paid.</p><p>Special thanks to <a href="https://www.instagram.com/danny_cahyo/"><strong>Danny Dwi Cahyono</strong></a>, whose short-form breakdown on this topic sparked the idea for this piece.</p><h3>References</h3><ol><li><strong>Danny Dwi Cahyono: </strong>Instagram Reel (original inspiration for this article’s framing)<br> <a href="https://www.instagram.com/p/DdoE1WlTbcR/">https://www.instagram.com/p/DdoE1WlTbcR/</a></li><li><strong>Stripe Docs: </strong><em>Verify webhook signatures</em><br> <a href="https://docs.stripe.com/webhooks/signature">https://docs.stripe.com/webhooks/signature</a><br> Implementation reference for HMAC signature verification — technical basis for the “Second Trap” section.</li><li><strong>Stripe Docs: </strong><em>Idempotent requests</em><br> <a href="https://docs.stripe.com/idempotency">https://docs.stripe.com/idempotency</a><br> Source for the idempotency key concept covered in the additional best-practices section (preventing double-fulfillment when a webhook is retried).</li><li><strong>Midtrans Docs: </strong><em>Handle Notifications</em><br> <a href="https://docs.midtrans.com/reference/handle-notifications">https://docs.midtrans.com/reference/handle-notifications</a><br> Given the article’s IDR pricing example and Indonesian market context, this is the most regionally relevant reference — covers the SHA512 signature key, idempotent notification handling, and why a redirect URL&#39;s status parameter can&#39;t be trusted on its own.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=057fc8649e09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GET Was Too Small and POST Was Too Vague, until HTTP Added QUERY]]></title>
            <link>https://medium.com/@ammarmusyaffa/get-was-too-small-and-post-was-too-vague-until-http-added-query-afd17f037ef1?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd17f037ef1</guid>
            <category><![CDATA[http-methods]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[http-query-method]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 11:21:14 GMT</pubDate>
            <atom:updated>2026-09-20T11:21:14.279Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical look at RFC (Request for Comments) 10008 and what it changes for API design</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUMpWpIGp2gEYX3o6-QmQQ.png" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/http-query-method-closing-decades-old-gap-web-api-robert-nkfac">Robert Joseph Kalapurackal</a></figcaption></figure><p>Maybe we have probably seen a URL like this one.</p><pre>GET /products?category=laptop&amp;price_min=500&amp;price_max=1500&amp;brand=a&amp;brand=b&amp;brand=c&amp;sort=-rating&amp;fields=id,name,price&amp;page=3 HTTP/1.1<br>Host: api.example.com</pre><p>It works fine on day one. Then product asks for more filters. Then nested conditions. Soon the query string is a wall of text that nobody can read and some proxy along the way may refuse to forward.</p><h3>Why neither GET nor POST feels right</h3><p>GET is a safe and idempotent method with robust caching support. Its weakness is that everything must fit in the URL. The RFC points out that size limits are often unknown because a request can pass through many uncoordinated systems. The HTTP spec only recommends supporting at least 8000 octets. URLs also get logged more often than request bodies and they end up in bookmarks.</p><p>So many teams switch to POST and put the filters in a JSON body. Here is what that often looks like.</p><pre>POST /products/search HTTP/1.1<br>Host: api.example.com<br>Content-Type: application/json<br>Accept: application/json<br><br>{<br>  &quot;category&quot;: &quot;laptop&quot;,<br>  &quot;price&quot;: { &quot;min&quot;: 500, &quot;max&quot;: 1500 },<br>  &quot;brands&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  &quot;sort&quot;: &quot;-rating&quot;,<br>  &quot;fields&quot;: [&quot;id&quot;, &quot;name&quot;, &quot;price&quot;],<br>  &quot;page&quot;: 3<br>}</pre><p>The size problem is gone. The /search suffix even hints at what the request does. But that hint is only a naming habit. Nothing in the method itself tells a client or a proxy that the operation only reads data.</p><p>That has real consequences. A client cannot safely retry after a dropped connection because for all it knows the request might have created an order. A cache cannot treat the call as a read either. The RFC notes that a cached POST response can only serve future GET or HEAD requests and never another POST.</p><p>Some teams go one step further and add an Idempotency-Key header to the POST request.</p><pre>POST /products/search HTTP/1.1<br>Host: api.example.com<br>Content-Type: application/json<br>Idempotency-Key: &quot;8e03978e-40d5-43e8-bc93-6894a57f9324&quot;</pre><p>The client generates a unique value for each logical request and the server remembers it. If the client retries with the same key the server can return the stored result instead of processing the request again. That makes retries safe. It also brings its own costs.</p><ul><li><strong>The server must keep state.</strong> It has to store every key and the outcome that goes with it. It also needs an expiry policy. The IETF draft says a key must not be reused with a different payload so the server needs a way to detect that too.</li><li><strong>The client must do extra work.</strong> Every call needs a fresh key. The same key must be reused on a retry and never on a different payload. A bug in either direction gives you duplicate work or a stale answer.</li><li><strong>It was designed for writes.</strong> The draft describes the header as a way to make non-idempotent methods such as POST or PATCH fault-tolerant. Adding it to a read-only search means building machinery to fake what QUERY states natively.</li><li><strong>Nothing else improves.</strong> The method is still POST. Proxies and caches still cannot tell that the request only reads data.</li><li><strong>It is not settled.</strong> The latest version available when this article was researched was an Internet-Draft from October 2025. Check its current status before you rely on it in a public API contract.</li></ul><p>So the key fixes retries and nothing more. You still end up choosing between a URL that is too small and a method that says too little.</p><p>In June 2026 the IETF published RFC 10008 and gave this problem an official answer. It is a new HTTP method called <strong>QUERY</strong><em>.</em></p><h3>What QUERY looks like</h3><p>Here is the same search as a QUERY request. The body is identical. Only the method changes and the path no longer needs a /search suffix.</p><pre>QUERY /products HTTP/1.1<br>Host: api.example.com<br>Content-Type: application/json<br>Accept: application/json<br><br>{<br>  &quot;category&quot;: &quot;laptop&quot;,<br>  &quot;price&quot;: { &quot;min&quot;: 500, &quot;max&quot;: 1500 },<br>  &quot;brands&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;],<br>  &quot;sort&quot;: &quot;-rating&quot;,<br>  &quot;fields&quot;: [&quot;id&quot;, &quot;name&quot;, &quot;price&quot;],<br>  &quot;page&quot;: 3<br>}</pre><p>POST tells the server to do something with this body. QUERY tells the server to look something up with it. That single word makes the request safe and idempotent just like GET. The RFC defines it as asking the target resource to process the enclosed content and return the result without changing the state of that resource.</p><p>In practice this gives a name to something teams have done with POST for years. Once it has a name the rest of the HTTP stack can understand what those requests mean.</p><h3>What you get for free</h3><p>Three things follow from the safe and idempotent guarantee.</p><ul><li><strong>Automatic retries.</strong> A client or proxy can repeat a QUERY after a connection failure without worrying about duplicate side effects.</li><li><strong>Caching.</strong> Responses to QUERY are cacheable. The cache key must include the request body. Caches may also normalize the body first to ignore differences that do not matter. The RFC admits this makes caching more complex than it is for GET.</li><li><strong>Strict content typing.</strong> A server must reject a request whose Content-Type is missing or does not match the body. It is not allowed to sniff the content and guess. Use 415 when the format is unsupported and 422 when the body is valid but the query cannot be processed. A SQL query that names a table that does not exist is a good example.</li></ul><h3>Two headers worth knowing</h3><p>The first is Accept-Query. It lets a resource announce which query formats it understands.</p><pre>Accept-Query: &quot;application/jsonpath&quot;, application/sql;charset=&quot;UTF-8&quot;</pre><p>Clients can use this to discover formats without trial and error.</p><p>The second is the pair of Location and Content-Location. A server can return a URI for the stored query in Location. A GET on that URI repeats the query without resending the body. Content-Location points to the result of the query that was just performed.</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Content-Location: /products/stored-results/17<br>Location: /products/stored-queries/42</pre><p>The RFC says these URIs might be temporary. If a later request fails the client should fall back to the original QUERY and body. Treat them as a shortcut and never as a guarantee.</p><h3>Trade-offs and common mistakes</h3><p><strong>Do not replace every GET.</strong> The RFC itself says that very short queries are better off using GET. A lookup by id has no reason to change.</p><p><strong>Do not hide writes behind QUERY.</strong> The method is safe. If an operation changes state it belongs to POST or PUT or PATCH.</p><p><strong>Expect ecosystem gaps.</strong> QUERY is brand new. Firewalls and API gateways and frameworks often ship rules built around a fixed list of methods. Some may reject QUERY or treat it differently than you expect. This is a reasoned expectation and not a tested result. Verify each layer between your client and your server before you commit.</p><p><strong>Remember CORS.</strong> Browsers send a preflight request for QUERY because it is not a CORS-safelisted method. Your server has to answer that preflight correctly.</p><p><strong>Watch sensitive data.</strong> QUERY keeps secrets out of URLs and that helps with logging. If your server creates a Location URI for a query that contains sensitive content the URI should not include those sensitive parts.</p><h3>Key takeaways</h3><ul><li>Use QUERY when a read-only request has a large or structured or sensitive input.</li><li>Keep GET for simple lookups.</li><li>Always send a correct Content-Type.</li><li>Advertise formats with Accept-Query and offer Location for repeat calls.</li><li>Audit gateways and caches and CORS handling before rollout.</li></ul><h3>References</h3><ul><li>RFC 10008: The HTTP QUERY Method (June 2026): <a href="https://datatracker.ietf.org/doc/rfc10008/">https://datatracker.ietf.org/doc/rfc10008/</a></li><li>HTTP Finally Gets a Method It’s Needed for Decades (Medium, June 2026): <a href="https://medium.com/@anmjawad007/http-finally-gets-a-method-its-needed-for-decades-meet-query-bb1b77def9a3">https://medium.com/@anmjawad007/http-finally-gets-a-method-its-needed-for-decades-meet-query-bb1b77def9a3</a></li><li>RFC 10008 and the attack surface still catching up (July 2026): <a href="https://hivesecurity.gitlab.io/blog/http-query-method-rfc-10008-attack-surface/">https://hivesecurity.gitlab.io/blog/http-query-method-rfc-10008-attack-surface/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd17f037ef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL vs NoSQL: Pick the Right One, Not the Popular One]]></title>
            <link>https://medium.com/@ammarmusyaffa/sql-vs-nosql-pick-the-right-one-not-the-popular-one-ee59ae14787a?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee59ae14787a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[sql-and-nosql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-management-sys]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 01:12:02 GMT</pubDate>
            <atom:updated>2026-07-28T01:12:02.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTyvZ_aE6iWWgIm1LfN7RA.jpeg" /><figcaption>Source: <a href="https://www.youtube.com/watch?v=t0GlGbtMTio">Web Dev Simplified</a></figcaption></figure><p>Every new project eventually hits the same question, <em>“Should we use PostgreSQL or MongoDB?”</em></p><p>What’s frustrating isn’t the question, it’s the reasoning behind the answer. More often than not, it’s something like <em>“MongoDB is more modern”</em> or <em>“SQL is battle-tested.”</em> Both statements aren’t wrong, but they’re just missing the point.</p><p>Database choice isn’t about trends. It’s about understanding what your data actually needs from a database.</p><h3>Relational Databases: Structure Is the Feature</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*aOgPS9tvgwxh0VjR1ObStA.jpeg" /><figcaption>Source: <a href="https://www.bairesdev.com/blog/what-is-sql-server/">Baires Dev</a></figcaption></figure><p>PostgreSQL and MySQL store data in tables which is rows, columns, and foreign keys. Relationships between entities are explicit and enforced.</p><p>But the most important thing about relational databases isn’t the SQL. It’s <strong>ACID guarantees</strong>.</p><ul><li><strong>Atomicity</strong>: a transaction either succeeds completely or fails completely.</li><li><strong>Consistency</strong>: data always transitions to a valid state according to defined constraints.</li><li><strong>Isolation</strong>: concurrent transactions don’t interfere with each other.</li><li><strong>Durability</strong>: committed data doesn’t disappear.</li></ul><p>Consider a money transfer. User A sends $50 to User B. Two steps: debit A, credit B. If the server dies between those two steps, what happens? With ACID guarantees, the answer is rollback. Without it, you have $50 that vanished and a very angry user filing a support ticket.</p><p>Relational databases also win on <strong>query flexibility</strong>. Five-table JOINs, aggregates, and complex filters, all of it without touching your data structure. The rigid schema feels like a constraint until you realize it’s actually a contract (bad data can’t sneak in).</p><p><strong>Use SQL when:</strong></p><ul><li>You’re handling financial transactions (payments, transfers, ledgers)</li><li>Your data has complex relationships (e-commerce: user → order → product → inventory).</li><li>You need ad-hoc reporting and analytics.</li><li>Your business logic is strict and data integrity is non-negotiable.</li></ul><h3>Non-Relational Databases: Scale Is the Bet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*BL0S0g_MXXqPWLb3MhdcXQ.png" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/nosql-databases-empowering-modern-data-management-jagarlapoodi/">Jagarlapoodi</a></figcaption></figure><p>NoSQL is not a single thing. It’s an umbrella term covering four distinct models, each with different trade-offs.</p><h4>Document Store (MongoDB)</h4><p>MongoDB stores data as JSON documents (BSON internally). No rigid schema, each document can have its own shape.</p><pre>{<br>  &quot;_id&quot;: &quot;user_123&quot;,<br>  &quot;name&quot;: &quot;Thom Haye&quot;,<br>  &quot;preferences&quot;: {<br>    &quot;theme&quot;: &quot;dark&quot;,<br>    &quot;notifications&quot;: [&quot;email&quot;, &quot;push&quot;]<br>  },<br>  &quot;addresses&quot;: [<br>    { &quot;type&quot;: &quot;home&quot;, &quot;city&quot;: &quot;Bandung&quot; },<br>    { &quot;type&quot;: &quot;office&quot;, &quot;city&quot;: &quot;Cianjur&quot; }<br>  ]<br>}</pre><p>Naturally nested data doesn’t need to be normalized. One read, you get everything.</p><p>But don’t be fooled. MongoDB supports multi-document transactions now, but its sweet spot is still single-document operations. If you constantly need to JOIN across collections, you’re fighting the grain and you’ll lose.</p><p><strong>Use MongoDB for:</strong> CMS platforms, product catalogs with variable attributes, user profiles, apps where the schema is still evolving.</p><h4>Key-Value Store (Redis)</h4><p>Redis stores key-value pairs in memory. Latency in the sub-millisecond range.</p><pre>SET session:abc123 &#39;{&quot;user_id&quot;: 42, &quot;role&quot;: &quot;admin&quot;}&#39; EX 3600<br>GET session:abc123</pre><p>Redis is not your primary database. Redis is the layer <em>between</em> your application and your primary database. Session management, rate limiting, caching expensive queries, and real-time leaderboards. That’s theRedis territory.</p><p>One mistake I’ve seen too many times: storing important data in Redis without configuring persistence properly, then watching it disappear after a server restart. Redis <em>can</em> be configured for durability, but it’s in-memory by default. Know this before you commit data you can’t afford to lose.</p><p><strong>Use Redis for:</strong> caching, session store, pub/sub messaging, rate limiting, real-time counters and leaderboards.</p><h4>Wide-Column Store (Cassandra)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*biuxJMqt65nxVBL4HPMwMw.jpeg" /><figcaption>Source: <a href="https://www.researchgate.net/figure/Cassandra-column-row-and-column-family-structure_fig3_356074165">International Journal of Data Science and Analytics</a></figcaption></figure><p>Cassandra is engineered for one thing: <strong>massive write throughput at distributed scale</strong>.</p><p>It has eventual consistency by default, data written to one node isn’t immediately visible on others. This is an intentional trade-off to achieve availability and partition tolerance (CAP theorem).</p><p>Netflix uses Cassandra for storing the viewing history of hundreds of millions of users. Ride-hailing platforms use it for GPS traces. The pattern is the same: <strong>write heavy, read by known partition key</strong>.</p><p>Query Cassandra against patterns that don’t align with its partition key and you’ll have a bad time. Schema design in Cassandra starts with access patterns, not data structure.</p><p><strong>Use Cassandra for:</strong> time-series data, event logs, IoT sensor streams, any workload requiring high write throughput across many nodes.</p><h3>Decision Framework</h3><p>Here’s what the decision flow actually looks like in the practice:</p><p><strong>1. Does your data have complex relationships you’ll need to query flexibly?</strong> Use Relational (e.g. PostgreSQL/MySQL).</p><p><strong>2. Do you need ACID transactions across multiple different entities?</strong> Use Relational (there’s no safe alternative here).</p><p><strong>3. Do you need a cache or session store with ultra-low latency?</strong> Use Redis</p><p><strong>4. Is your data naturally nested and is the schema still changing?</strong> Use MongoDB</p><p><strong>5. Are you writing millions of events per second from distributed sources?</strong> Use Cassandra</p><p><strong>6. Not sure yet?</strong> Start with PostgreSQL. It’s extensible, battle-tested, and supports JSONB if you need semi-structured flexibility down the road.</p><h3>The Part Most People Miss</h3><p>Most serious production systems don’t run on a single database.</p><p>A typical e-commerce backend usually uses PostgreSQL for orders and inventory, Redis for cart sessions and caching, and Elasticsearch for product search. That’s not over-engineering. That’s matching the right tool to the right job.</p><p>The real problem happens when teams pick a database based on hype, then discover in production that the trade-offs don’t fit their actual workload. In 2013, MongoDB was everywhere because “no schema.” A lot of those teams ended up migrating back to PostgreSQL once they realized their data was deeply relational all along.</p><p>Technology is never neutral. Every database encodes assumptions about how your data will be accessed. Understand those assumptions before you commit, because migrating away is a project in itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee59ae14787a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big O Notation, The Language of Algorithm Efficiency]]></title>
            <link>https://medium.com/@ammarmusyaffa/big-o-notation-the-language-of-algorithm-efficiency-191b43bb4954?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/191b43bb4954</guid>
            <category><![CDATA[complexity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[time-complexity]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 10:25:25 GMT</pubDate>
            <atom:updated>2026-07-05T10:25:25.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*hrI4rGhw5US8juZGy8YzqQ.jpeg" /><figcaption>Source: <a href="https://socs.binus.ac.id/2025/10/06/kompleksitas-algoritma-seni-mengukur-efisiensi-sebuah-solusi/">Binus University</a></figcaption></figure><p>Every piece of software runs on borrowed resources which is time and memory. Big O notation is the tool programmers use to describe how those resources scale as input grows. It is not a stopwatch measurement. It is a mathematical shorthand for growth rate, and mastering it separates casual coders from engineers who build systems that survive real traffic.</p><h3>What Big O Actually Measures</h3><p>Big O notation describes the upper bound of an algorithm’s resource consumption as input size increases. The letter “n” typically represents input size, while the notation itself like O(1), O(n), O(n²), and so on, represents the shape of the growth curve rather than an exact number of operations.</p><p>Two algorithms solving the same problem might take wildly different amounts of real time on a given machine due to hardware, compiler optimizations, or background processes. Big O ignores those variables entirely. It asks a single question like as input size doubles, triples, or grows a thousandfold, how does the workload respond?</p><p>This abstraction matters because software rarely operates at a fixed scale. A search function tested on ten records might feel instantaneous, yet the same logic applied to ten million records could grind a server to a halt. Big O predicts that outcome before the code is ever deployed.</p><h3>The Common Complexity Classes</h3><p>A handful of complexity classes appear again and again in everyday programming. Recognizing them by shape, rather than memorizing formulas, builds intuition faster than rote learning.</p><h4>O(1) Constant Time</h4><p>An operation that takes the same amount of time regardless of input size. Accessing an array element by index or checking a hash map for a key both fall into this category. No matter how large the dataset becomes, the operation cost stays flat.</p><pre>// JavaScript: constant time array access<br>function getFirstElement(arr) {<br>  return arr[0]; // always one step, regardless of arr.length<br>}<br><br>console.log(getFirstElement([1, 2, 3, 4, 5])); // 1</pre><p>This function simply reaches into the array at a fixed position, so the engine performs exactly one operation whether the array holds five items or five million. Growth in input size never touches the execution cost.</p><pre># Python: constant time dictionary lookup<br>def get_value(data, key):<br>    return data.get(key)  # always one step, regardless of dict size<br><br>sample = {&quot;id&quot;: 101, &quot;name&quot;: &quot;Ammar&quot;}<br>print(get_value(sample, &quot;name&quot;))  # Ammar</pre><p>A dictionary lookup relies on hashing rather than scanning, so Python jumps directly to the stored value instead of walking through every key. Adding thousands of extra entries to the dictionary would not slow this lookup down in any meaningful way.</p><h4>O(log n) Logaritmic Time</h4><p>Growth slows dramatically as input increases. Binary search is the textbook example which is each step eliminates half the remaining possibilities. Searching a sorted list of one billion items might take only thirty comparisons instead of a billion.</p><pre>// JavaScript: merge sort<br>function mergeSort(arr) {<br>  if (arr.length &lt;= 1) return arr;<br><br>  const mid = Math.floor(arr.length / 2);<br>  const left = mergeSort(arr.slice(0, mid));<br>  const right = mergeSort(arr.slice(mid));<br><br>  return merge(left, right);<br>}<br><br>function merge(left, right) {<br>  const result = [];<br>  let i = 0, j = 0;<br><br>  while (i &lt; left.length &amp;&amp; j &lt; right.length) {<br>    if (left[i] &lt;= right[j]) result.push(left[i++]);<br>    else result.push(right[j++]);<br>  }<br>  return result.concat(left.slice(i)).concat(right.slice(j));<br>}<br><br>console.log(mergeSort([8, 3, 7, 4, 1, 9])); // [1, 3, 4, 7, 8, 9]</pre><p>Each pass through the loop cuts the search space in half by comparing the middle element against the target. Because the array must already be sorted, this halving pattern lets the function skip enormous portions of data instead of checking every value.</p><pre># Python: binary search<br>def binary_search(sorted_list, target):<br>    low, high = 0, len(sorted_list) - 1<br><br>    while low &lt;= high:<br>        mid = (low + high) // 2<br>        if sorted_list[mid] == target:<br>            return mid<br>        elif sorted_list[mid] &lt; target:<br>            low = mid + 1<br>        else:<br>            high = mid - 1<br>    return -1<br><br>print(binary_search([1, 3, 5, 7, 9, 11], 7))  # 3</pre><p>The logic mirrors the JavaScript version step for step like low and high boundaries shrink toward each other until the target is found or the boundaries cross. Thirty iterations at most would be enough to search through a billion sorted items using this exact approach.</p><h4>O(n) Linear Time</h4><p>Cost grows proportionally with input. A single loop through an array, checking every element once, and produces linear time. Doubling the input roughly doubles the work required.</p><pre>// JavaScript: linear search<br>function linearSearch(arr, target) {<br>  for (let i = 0; i &lt; arr.length; i++) {<br>    if (arr[i] === target) return i;<br>  }<br>  return -1;<br>}<br><br>console.log(linearSearch([4, 2, 9, 6, 1], 6)); // 3</pre><p>Unlike binary search, this function makes no assumption about ordering, so it has to inspect elements one by one until a match appears. Worst case arrives when the target sits at the very end or is missing entirely, forcing the loop to visit every single element.</p><pre># Python: linear search<br>def linear_search(items, target):<br>    for index, value in enumerate(items):<br>        if value == target:<br>            return index<br>    return -1<br><br>print(linear_search([4, 2, 9, 6, 1], 6))  # 3</pre><p>The enumerate function walks through the list in order while tracking both index and value, which keeps the code readable without changing its underlying cost. Doubling the list length would roughly double the number of comparisons performed on average.</p><h4>O(n log n) Linearithmic Time</h4><p>A common signature of efficient sorting algorithms such as merge sort and quicksort. Each element gets touched roughly log n times rather than once or n times, striking a balance between speed and thoroughness.</p><pre>// JavaScript: merge sort<br>function mergeSort(arr) {<br>  if (arr.length &lt;= 1) return arr;<br><br>  const mid = Math.floor(arr.length / 2);<br>  const left = mergeSort(arr.slice(0, mid));<br>  const right = mergeSort(arr.slice(mid));<br><br>  return merge(left, right);<br>}<br><br>function merge(left, right) {<br>  const result = [];<br>  let i = 0, j = 0;<br><br>  while (i &lt; left.length &amp;&amp; j &lt; right.length) {<br>    if (left[i] &lt;= right[j]) result.push(left[i++]);<br>    else result.push(right[j++]);<br>  }<br>  return result.concat(left.slice(i)).concat(right.slice(j));<br>}<br><br>console.log(mergeSort([8, 3, 7, 4, 1, 9])); // [1, 3, 4, 7, 8, 9]</pre><p>The array keeps splitting in half until each piece holds a single element, producing a tree of depth log n, and merging those pieces back together costs n operations at every level of that tree. Multiplying those two factors together is exactly where the n log n label comes from.</p><pre># Python: merge sort<br>def merge_sort(items):<br>    if len(items) &lt;= 1:<br>        return items<br><br>    mid = len(items) // 2<br>    left = merge_sort(items[:mid])<br>    right = merge_sort(items[mid:])<br><br>    return merge(left, right)<br><br>def merge(left, right):<br>    result = []<br>    i = j = 0<br><br>    while i &lt; len(left) and j &lt; len(right):<br>        if left[i] &lt;= right[j]:<br>            result.append(left[i])<br>            i += 1<br>        else:<br>            result.append(right[j])<br>            j += 1<br>    result.extend(left[i:])<br>    result.extend(right[j:])<br>    return result<br><br>print(merge_sort([8, 3, 7, 4, 1, 9]))  # [1, 3, 4, 7, 8, 9]</pre><p>The recursive split-and-merge structure stays identical to the JavaScript version, with the merge helper doing the actual comparison work once both halves come back sorted. This pattern explains why merge sort remains a reliable choice even for very large datasets.</p><h4>O(n²) Quadratic Time</h4><p>Nested loops over the same dataset produce this pattern, often seen in simple sorting methods like bubble sort or naive duplicate-checking. Performance degrades quickly as datasets grow, since doubling the input quadruples the workload.</p><pre>// JavaScript: bubble sort<br>function bubbleSort(arr) {<br>  const result = [...arr];<br>  for (let i = 0; i &lt; result.length; i++) {<br>    for (let j = 0; j &lt; result.length - i - 1; j++) {<br>      if (result[j] &gt; result[j + 1]) {<br>        [result[j], result[j + 1]] = [result[j + 1], result[j]];<br>      }<br>    }<br>  }<br>  return result;<br>}<br><br>console.log(bubbleSort([5, 1, 4, 2, 8])); // [1, 2, 4, 5, 8]</pre><p>The outer loop and inner loop both scale with array length, meaning every pass compares nearly every pair of neighboring elements before the array becomes fully sorted. A list ten times larger would require roughly one hundred times more comparisons.</p><pre># Python: bubble sort<br>def bubble_sort(items):<br>    result = items.copy()<br>    n = len(result)<br><br>    for i in range(n):<br>        for j in range(0, n - i - 1):<br>            if result[j] &gt; result[j + 1]:<br>                result[j], result[j + 1] = result[j + 1], result[j]<br>    return result<br><br>print(bubble_sort([5, 1, 4, 2, 8]))  # [1, 2, 4, 5, 8]</pre><p>Swapping happens whenever a pair sits in the wrong order, and the largest unsorted value effectively bubbles toward its correct position with each full pass. Its simplicity makes it easy to read, though the nested loops make it a poor choice for anything beyond small datasets.</p><h3>Why Worst Case Dominates the Conversation</h3><p>Big O typically describes worst-case behavior rather than average or best-case performance, and that choice is deliberate. Software engineering demands predictability under pressure, not just favorable conditions.</p><p>Consider a hash map lookup, generally O(1) on average. Under a poorly designed hashing scheme, however, collisions could degrade performance to O(n) in the worst case. A system relying solely on average-case assumptions risks catastrophic slowdowns precisely when traffic spikes and reliability matters most.</p><p>This is why interviews, system design reviews, and performance audits lean heavily on worst-case analysis. Planning for the worst scenario, rather than hoping for the best, is a defining trait of resilient engineering.</p><h3>Space Complexity Deserves Equal Attention</h3><p>Time complexity gets most of the spotlight, but memory usage follows the same notation and often creates its own bottlenecks. Space complexity measures how much additional memory an algorithm requires relative to input size.</p><p>A recursive function that creates a new data structure at every call step might run acceptably fast while quietly consuming enormous memory. Iterative solutions frequently trade a small speed penalty for dramatically reduced memory footprint, an especially important tradeoff for embedded systems or mobile applications operating under strict hardware constraints.</p><p>Balancing time against space is rarely about choosing one metric as universally superior. Context, hardware, and business priorities decide which tradeoff makes sense for a given project.</p><h3>Common Misconceptions Worth Correcting</h3><p>A frequent misunderstanding treats Big O as a precise performance guarantee rather than a growth-rate description. Two O(n) algorithms could differ substantially in raw speed due to constant factors the notation deliberately ignores. Big O answers “how does this scale,” not “which one runs faster on this machine today.”</p><p>Another misconception assumes lower complexity always wins in practice. For small input sizes, an O(n²) algorithm with minimal overhead might actually outperform an O(n log n) algorithm burdened by heavier constant costs. Complexity analysis shines brightest at scale, and small datasets sometimes reward simplicity over theoretical elegance.</p><p>A third mistake ignores amortized complexity. Dynamic arrays, for instance, occasionally require expensive resizing operations, yet the average cost per insertion remains low across many operations. Judging performance from a single worst-case event rather than the amortized pattern paints a misleading picture.</p><h3>Applying Big O in Real Development Work</h3><p>Complexity analysis becomes genuinely useful once it moves beyond theory and into daily decision-making. A few practical habits make that transition smoother.</p><p>Before writing a loop within a loop, pausing to ask whether a hash map or a smarter data structure could flatten nested logic into something closer to linear time often prevents future headaches. Profiling tools can then confirm whether theoretical improvements translate into measurable gains on real hardware.</p><p>Reading library and framework documentation with complexity in mind also pays dividends. Many standard library functions document their time and space complexity explicitly, and understanding those figures prevents accidental misuse of otherwise excellent tools.</p><p>Finally, complexity awareness should scale with the actual problem at hand. A script processing a few dozen records rarely needs the same scrutiny as a service processing millions of transactions per minute. Applying rigorous complexity analysis appropriately, rather than universally, keeps development both efficient and pragmatic.</p><p>Big O notation is less about mathematical purity and more about disciplined thinking. It forces a shift from “does this work” toward “does this still work when the input grows a hundredfold.” That shift in perspective, once internalized, quietly shapes better architecture, smarter data structure choices, and software capable of surviving growth rather than collapsing under it.</p><p>Mastering complexity analysis will not eliminate every performance bug, but it builds the instinct to spot trouble before it reaches production, which is often the difference between a minor optimization and a full-blown outage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=191b43bb4954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Connection Pooling: Hidden Performance Booster Behind Scalable Applications]]></title>
            <link>https://medium.com/@ammarmusyaffa/the-power-of-connection-pooling-hidden-performance-booster-behind-scalable-applications-47ea9247e71a?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/47ea9247e71a</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[database-connection-pool]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 13:34:25 GMT</pubDate>
            <atom:updated>2026-06-02T13:34:25.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mmmsv4re_0GDXObjGRLBQ.png" /><figcaption>Source: <a href="https://www.clearpeaks.com/database-connection-pooling-a-guide-to-tuning-performance-optimisation/">Clearpeaks</a></figcaption></figure><p>Modern applications often perform exceptionally well during development and early deployment stages. Response times remain low, database queries execute quickly, and infrastructure utilization appears healthy.</p><p>As traffic grows, however, a different reality begins to emerge. Requests become slower, latency becomes less predictable, and database servers start approaching their connection limits. In many cases, engineering teams initially focus on query optimization, caching strategies, or infrastructure upgrades. While these areas are important, the root cause is frequently hidden elsewhere: database connection management.</p><p>One of the most overlooked scalability bottlenecks in backend systems is the cost associated with creating and managing database connections. This is precisely the problem that connection pooling was designed to solve.</p><h3>Understanding What Happens During a Database Request</h3><p>From a high-level perspective, interacting with a database appears simple. An application sends a query, the database processes it, and the results are returned.</p><p>Behind the scenes, however, several operations must occur before a single query can be executed.</p><p>A typical database interaction involves:</p><ul><li>Establishing a network connection.</li><li>Authenticating credentials.</li><li>Creating a database session.</li><li>Allocating memory and internal resources.</li><li>Executing the query.</li><li>Returning results.</li><li>Releasing resources and terminating the session.</li></ul><p>Although these operations occur within milliseconds, they are not free. Every connection requires CPU cycles, memory allocation, network communication, and database resources.</p><p>For systems handling a small number of requests, this overhead may be negligible. Under high concurrency, however, the cumulative cost becomes increasingly significant.</p><h3>Why Connection Creation Becomes a Scalability Problem</h3><p>Database connections are expensive resources.</p><p>In low-traffic environments, opening and closing connections for every request rarely causes noticeable performance issues. The database has sufficient capacity, and the overhead remains relatively small compared to overall request processing time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*UMZi1Bgj8MZ9i3RkIP4g8w.png" /><figcaption>Source: <a href="https://www.clearpeaks.com/database-connection-pooling-a-guide-to-tuning-performance-optimisation/">Clearpeaks</a></figcaption></figure><p>The situation changes as concurrency increases.</p><p>Consider an API receiving hundreds or thousands of requests per second. If every request creates a new database connection, the database server must continuously perform authentication, session initialization, resource allocation, and connection cleanup.</p><p>At this point, the database is no longer spending most of its resources executing business queries. Instead, a substantial portion of its workload becomes dedicated to connection management.</p><p>Several consequences typically emerge:</p><h4>Increased Latency</h4><p>Before a query can execute, a connection must first be established. The repeated creation of connections introduces additional delays that directly impact response times.</p><h4>Higher Resource Consumption</h4><p>Authentication and session management consume CPU and memory. Repeating these operations at scale creates unnecessary overhead for the database server.</p><h4>Connection Exhaustion</h4><p>Most relational databases impose limits on concurrent connections.</p><p>As traffic increases, systems may eventually encounter errors such as:</p><pre>Too many connections</pre><p>or</p><pre>Connection timeout</pre><p>At this stage, application performance becomes constrained not by query execution, but by connection management.</p><h3>The Real Cost of a Database Connection</h3><p>The performance impact of connection creation is often underestimated because the process happens behind the scenes.</p><p>Each new connection typically requires:</p><ul><li>TCP connection establishment.</li><li>Authentication and authorization.</li><li>Session creation.</li><li>Resource allocation.</li><li>Internal bookkeeping within the database engine.</li></ul><p>These operations must occur before useful work can begin.</p><p>An effective analogy is a restaurant that builds a new table every time a customer arrives and dismantles it after the customer leaves. Even if food preparation is highly efficient, the constant effort of constructing and removing tables eventually becomes a bottleneck.</p><p>The same principle applies to database connections. Excessive connection creation introduces overhead that scales with traffic volume.</p><h3>Introducing Connection Pooling</h3><p>Connection pooling addresses this problem by maintaining a collection of reusable database connections.</p><p>Instead of creating a new connection for every request, applications borrow an existing connection from a predefined pool. Once the operation is complete, the connection is returned to the pool rather than being closed.</p><p>This approach significantly reduces the overhead associated with connection establishment.</p><p>In simple terms:</p><ul><li>Connections are created once.</li><li>Connections are reused multiple times.</li><li>Connections are returned to the pool after use.</li></ul><p>As a result, requests gain immediate access to an already established connection, eliminating the need to repeat expensive setup operations.</p><h3>How Connection Pooling Works</h3><p>The internal workflow of a connection pool is relatively straightforward.</p><h4>1. Pool Initialization</h4><p>When an application starts, it creates a predefined number of database connections and stores them in a connection pool. These connections remain open and ready to serve incoming requests. By establishing connections upfront, the application avoids the overhead of creating new connections during request processing.</p><p>For example, a pool may maintain ten active connections ready for use.</p><h4>2. Request Arrival</h4><p>When a request requires access to the database, the application checks the pool for an available connection. If a connection is available, it is immediately assigned to the request. This eliminates the need to perform a new connection handshake and authentication process.</p><p>No new connection needs to be established.</p><h4>3. Query Execution</h4><p>Once a connection has been acquired, the application executes the required database operations. The database processes the query and returns the requested results. During this stage, the borrowed connection remains exclusively assigned to the active request.</p><h4>4. Connection Return</h4><p>After the database operation is completed, the connection is returned to the pool instead of being closed. The connection remains active and ready for future use. This approach significantly reduces the cost of repeatedly establishing new database sessions.</p><p>Importantly, the connection remains open and available for future requests.</p><h4>5. Connection Reuse</h4><p>Subsequent requests can reuse connections that are already available in the pool. Because the connection is already established, no additional authentication or session initialization is required. Reusing existing connections improves response times and reduces resource consumption on the database server.</p><p>This cycle continues throughout the lifetime of the application.</p><h3>Why Connection Pooling Improves Performance</h3><p>Connection pooling delivers several measurable benefits for production workloads.</p><h4>1. Reduced Response Times</h4><p>Connection pooling reduces the time required to access the database by eliminating the need to establish a new connection for every request. Because connections are already available in the pool, requests can immediately begin executing database operations. As a result, overall response times become faster and more consistent, especially under high traffic conditions.</p><h4>2. Improved Throughput</h4><p>Creating and destroying database connections consumes valuable processing time and resources. By reusing existing connections, the application can spend more time handling business logic and serving user requests. This allows the system to process a greater number of requests within the same period.</p><h4>3. Lower Database Overhead</h4><p>Establishing a database connection requires authentication, session initialization, and resource allocation. When connections are reused, these operations occur far less frequently. This reduces unnecessary workload on the database server and frees resources for query execution.</p><h4>4. More Efficient Resource Utilization</h4><p>Every active database connection consumes CPU, memory, and network resources. Reusing connections minimizes the overhead associated with repeatedly creating and terminating sessions. As a result, both the application and database server can utilize their resources more efficiently and predictably.</p><h3>Connection Pooling Is Not a Silver Bullet</h3><p>Although connection pooling is a fundamental optimization, its effectiveness depends heavily on proper configuration.</p><p>Poorly configured pools can introduce new bottlenecks.</p><h4>1. Pool Size Too Small</h4><p>A connection pool that is too small may not provide enough connections to handle incoming traffic efficiently. When all available connections are occupied, new requests must wait until a connection becomes available. This waiting time can increase latency and negatively impact user experience even when the database server itself is operating normally.</p><h4>2. Pool Size Too Large</h4><p>Configuring an excessively large connection pool does not automatically improve application performance. Each active connection consumes memory and other resources on the database server, regardless of whether it is actively being used. As a result, an oversized pool can place unnecessary pressure on the database and reduce overall system efficiency.</p><h4>3. Connection Leaks</h4><p>A connection leak occurs when an application borrows a connection from the pool but fails to return it after completing its work. Over time, the number of available connections decreases as more connections become permanently occupied. If left unresolved, connection leaks can exhaust the entire pool and prevent new requests from accessing the database.</p><h4>4. Long-Running Queries</h4><p>Queries that take a long time to execute keep database connections occupied for extended periods. While those connections are busy, fewer connections remain available for other incoming requests. This can create bottlenecks within the application and increase waiting times across the system, particularly during periods of high traffic.</p><p>For this reason, connection pooling should be viewed as one component of a broader performance strategy that includes query optimization, indexing, caching, and resource management.</p><h3>Connection Pooling in Modern Technology Stacks</h3><p>Connection pooling has become a standard practice across modern application platforms.</p><p>Common examples include:</p><ul><li>Prisma, Sequelize, and Knex in Node.js environments.</li><li>database/sql and GORM in Go applications.</li><li>PgBouncer for PostgreSQL deployments.</li></ul><p>Although implementation details vary, the underlying principle remains identical which is reuse expensive connections whenever possible.</p><p>The widespread adoption of connection pooling reflects a simple reality. Efficient connection management is essential for building scalable systems.</p><h3>The Serverless Challenge</h3><p>The rise of serverless computing introduces a unique challenge for connection management.</p><p>Traditional applications typically operate as long-running processes. A connection pool remains active throughout the application’s lifecycle, allowing connections to be reused efficiently.</p><p>Serverless environments behave differently.</p><p>As traffic increases, cloud platforms may rapidly create multiple function instances. If each instance establishes its own pool of database connections, the number of active connections can grow dramatically within a short period.</p><p>This phenomenon is often referred to as connection explosion.</p><p>Without proper safeguards, databases may reach connection limits long before CPU or memory resources become constrained.</p><p>To address this issue, many architectures incorporate dedicated connection proxies such as PgBouncer or managed services like Amazon RDS Proxy.</p><p>These solutions help centralize connection management and prevent uncontrolled connection growth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Cgb4R_bvvYV28vXyh0IeA.png" /><figcaption>Source: <a href="https://ahmadammar.my.id/">Author</a></figcaption></figure><h3>Conclusion</h3><p>Performance bottlenecks are often associated with inefficient queries, insufficient infrastructure, or poor application design. While these factors certainly matter, database connection management is frequently overlooked despite its substantial impact on scalability.</p><p>Every database connection carries a cost. Authentication, session creation, resource allocation, and network communication all contribute to the overhead of establishing a connection. As traffic increases, these costs accumulate rapidly.</p><p>Connection pooling solves this challenge by reusing existing connections instead of repeatedly creating new ones. The result is lower latency, reduced resource consumption, improved throughput, and better scalability.</p><p>For modern backend systems, connection pooling is not merely an optimization. It is a foundational component of efficient database architecture and one of the simplest ways to improve performance under load.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47ea9247e71a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Guide I Wish I Had as a Beginner in Go Concurrency]]></title>
            <link>https://medium.com/@ammarmusyaffa/the-guide-i-wish-i-had-as-a-beginner-in-go-concurrency-c156fe73856d?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c156fe73856d</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Thu, 14 May 2026 01:54:57 GMT</pubDate>
            <atom:updated>2026-05-14T01:54:57.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*KL3gJh1rj9XDA1r0NRbbJw.png" /><figcaption>Source: (<a href="https://mobisoftinfotech.com/resources/wp-content/uploads/2022/02/hire-golang-developers-1.png">Mobisoft Infotech</a>)</figcaption></figure><p>Go (often called Golang) is an open source and statically typed programming language developed by Google. Go is a compiled language, that means the source code is directly translated into machine code and packaged into an executable file. Now we will talk about one of most powerful features in this programming language which is concurrency.</p><p>But before discussing concurrency, it is important to understand the concepts of processes, threads, and CPU cores.</p><p>A process is an independent program running in the operating system. Each process has its own memory space and system resources. A thread is the smallest unit of execution inside a process. A process can contain multiple threads that share the same memory and resources to perform different tasks concurrently. Meanwhile, a CPU core is the physical processing unit inside a processor that executes instructions. Modern CPUs often contain multiple core enabling several threads to run simultaneously.</p><h3><strong>What is concurrency?</strong></h3><p>Concurrency is the ability to manage multiple tasks at once, even if those tasks are not executed simultaneously. In other words, concurrency is not necessarily about doing many things at the exact same time, but about efficiently handling multiple tasks by organizing them into independent units of work. These tasks can continue progressing while others are waiting or blocked. In practice, concurrency can even run on a single CPU core by rapidly switching between tasks.</p><p>Think of a single chef in a kitchen. They start boiling water and while waiting they chop vegetables. And then while those cook they prepare the sauce, salt, etc. One person managing multiple tasks by switching between them when one is waiting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pl50aeaNvC-nnL2lCw4RDw.png" /><figcaption>Source: (<a href="https://www.udemy.com/course/pemrograman-go-lang-pemula-sampai-mahir/">Programmer Zaman Now</a>)</figcaption></figure><p>As we can see in the diagram, the A process switching between tasks while one process is still waiting. When the green sub-process (thread) is waiting, the A process switching to purple sub-process and then back to green sub-process and so on. This make concurrency is a different thing with parallelism. Parallelism is a paradigm that multiple tasks actually running simultaneously on different CPU cores. Go gives concurrency primitives. Whether they run in parallel depends on your hardware and the Go runtime scheduler.</p><h3>Hello Goroutine</h3><p>Goroutine is a lightweight thread managed by the Go runtime. In operating systems, creating and managing OS threads can be expensive because each thread requires a relatively large amount of memory and system resources. An OS thread usually uses around 1 MB of memory.</p><p>Goroutines are designed to be much more efficient. A goroutine starts with only around 2 KB of memory and can grow dynamically when needed. Because of this lightweight design, Go applications can run thousands or even millions of goroutines at the same time with relatively low resource usage.</p><p>Another important difference is that goroutines are not managed directly by the operating system. Instead, they are managed by the Go runtime which schedules and distributes goroutines across available CPU cores efficiently.</p><p>To create a goroutine in Go, we simply use the go keyword before calling a function. When the go keyword is added, the function runs concurrently with the rest of the program.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func sayHello(name string) {<br>    fmt.Printf(&quot;Hello, %s!\n&quot;, name)<br>}<br><br>func main() {<br>    // Normal function call - blocks until complete<br>    sayHello(&quot;Alice&quot;)<br>    <br>    // Goroutine - runs concurrently<br>    go sayHello(&quot;Bob&quot;)<br>    <br>    // Main goroutine continues immediately<br>    fmt.Println(&quot;Main function continues&quot;)<br>    <br>    // Wait a bit so Bob&#39;s goroutine can finish<br>    time.Sleep(100 * time.Millisecond)<br>}</pre><pre>Hello, Alice!<br>Main function continues<br>Hello, Bob!</pre><p>When you call sayHello(&quot;Alice&quot;) normally the program waits for it to complete before moving to the next line. Execution is sequential.</p><p>When you call go sayHello(&quot;Bob&quot;) the Go runtime spawns a new goroutine to execute that function. The main goroutine continues immediately to the next line without waiting. Now two goroutines are running concurrently, main and the one printing Bob&#39;s greeting.</p><p><strong>The critical detail everyone misses is </strong>when the main() function exits all goroutines are immediately killed. It doesn&#39;t matter if they&#39;re still working. Main exits, program terminates, goroutines die.</p><p>This is why we have that awkward time.Sleep() call. We&#39;re telling main to wait 100 milliseconds so Bob&#39;s goroutine has time to print before main exits. This is a hack. The proper solution involves WaitGroups which we&#39;ll cover later.</p><h3>Channels Basics</h3><p>Channels are how goroutines communicate. Think of a channel as a pipe. One goroutine puts data in one end and another goroutine takes data out the other end. Channels are typed. A channel that carries integers only carries integers. A channel that carries strings only carries strings. The compiler enforces this.</p><p>Creating a channel:</p><pre>messages := make(chan string)</pre><p>This creates a channel that can carry string values.</p><p>Sending a value into a channel:</p><pre>messages &lt;- &quot;ping&quot;</pre><p>The &lt;- operator with the channel on the left means &quot;send into this channel.&quot;</p><p>Receiving a value from a channel:</p><pre>msg := &lt;-messages</pre><p>The &lt;- operator with the channel on the right means &quot;receive from this channel.&quot;</p><p>Here’s a complete example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    messages := make(chan string)<br>    <br>    // Send in a goroutine<br>    go func() {<br>        messages &lt;- &quot;ping&quot;<br>    }()<br>    <br>    // Receive in main<br>    msg := &lt;-messages<br>    fmt.Println(msg)<br>}</pre><p>The goroutine sends “ping” into the channel and then the main goroutine receives it and prints it.</p><p><strong>Why does the send happen in a goroutine?</strong> Because by default channels are unbuffered and synchronous. A send operation blocks until someone receives. A receive operation blocks until someone sends.</p><p>If we tried messages &lt;- &quot;ping&quot; in main without a goroutine the program would deadlock. Main would block forever waiting for someone to receive. But the receiver code is on the next line which never executes because the send never completes.</p><p>Putting the send in a goroutine breaks this cycle. The goroutine sends (and blocks waiting for a receiver). Main continues to the receive operation (and blocks waiting for a sender). Now both sides are ready. The value transfers. Both unblock. Program continues.</p><p>This blocking behavior is actually synchronization. The send and receive must happen together. One goroutine waits for the other. This coordination is powerful for building correct concurrent systems.</p><h4>Real Example: Fetching Multiple Users Concurrently</h4><p>Imagine you need to fetch data for 5 users from an API. Each request takes 100 milliseconds.</p><p>Sequential approach:</p><pre>func fetchUserSequential(userID int) string {<br>    time.Sleep(100 * time.Millisecond)  // Simulate API call<br>    return fmt.Sprintf(&quot;User %d data&quot;, userID)<br>}<br><br>func main() {<br>    userIDs := []int{1, 2, 3, 4, 5}<br>    <br>    for _, id := range userIDs {<br>        data := fetchUserSequential(id)<br>        fmt.Println(data)<br>    }<br>}</pre><p>Total time: 5 requests × 100ms = 500ms</p><p>Concurrent approach with goroutines and channels:</p><pre>func fetchUserConcurrent(userID int, resultChan chan string) {<br>    time.Sleep(100 * time.Millisecond)  // Simulate API call<br>    resultChan &lt;- fmt.Sprintf(&quot;User %d data&quot;, userID)<br>}<br><br>func main() {<br>    userIDs := []int{1, 2, 3, 4, 5}<br>    results := make(chan string)<br>    <br>    // Launch all fetches concurrently<br>    for _, id := range userIDs {<br>        go fetchUserConcurrent(id, results)<br>    }<br>    <br>    // Collect all results<br>    for i := 0; i &lt; len(userIDs); i++ {<br>        fmt.Println(&lt;-results)<br>    }<br>}</pre><p>Total time: ~100ms (all requests happen simultaneously)</p><p><strong>What’s happening?</strong></p><p>We spawn 5 goroutines that all start their API calls at roughly the same time. Each goroutine sends its result into the shared results channel when done. The main goroutine receives from the channel 5 times, collecting all results.</p><p>The speedup is dramatic. Instead of 500ms we spend roughly 100ms. We’re using the waiting time productively by doing all the waiting in parallel instead of sequentially.</p><h4>Buffered vs Unbuffered Channels</h4><p>The channels we’ve seen so far are unbuffered. Every send must have a matching receive happening simultaneously. The sender blocks until someone receives. The receiver blocks until someone sends.</p><p>Buffered channels add capacity. They can hold a certain number of values before blocking the sender.</p><p>Creating an unbuffered channel:</p><pre>ch := make(chan int)</pre><p>Creating a buffered channel with capacity 3:</p><pre>ch := make(chan int, 3)</pre><p>This channel can hold 3 integers. Sends only block when the buffer is full. Receives only block when the buffer is empty.</p><p><strong>Unbuffered Channel Behavior</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    ch := make(chan int)<br>    <br>    // This would deadlock<br>    // ch &lt;- 1<br>    <br>    // Fix: send in goroutine<br>    go func() {<br>        ch &lt;- 1<br>    }()<br>    <br>    fmt.Println(&lt;-ch)<br>}</pre><p>If we uncommented ch &lt;- 1 the program would deadlock immediately. The send blocks waiting for a receiver. But the receiver (the Println line) never executes because the send never completes. Deadlock.</p><p>The fix is put the send in a goroutine. Now the send blocks in its own goroutine while main continues to the receive. Both sides meet and the value transfers.</p><p><strong>Buffered Channel Behavior</strong></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    ch := make(chan int, 2)<br>    <br>    // These don&#39;t block - buffer has space<br>    ch &lt;- 1<br>    ch &lt;- 2<br>    <br>    // This would block - buffer is full<br>    // ch &lt;- 3<br>    <br>    fmt.Println(&lt;-ch)  // Prints 1<br>    fmt.Println(&lt;-ch)  // Prints 2<br>}</pre><p>The first two sends succeed immediately because the buffer has space. They don’t need a receiver yet. The values sit in the buffer.</p><p>If we tried a third send the buffer would be full. That send would block waiting for someone to receive and free up space.</p><p>The receives pull values out of the buffer in FIFO order (first in first out).</p><h4>When to Use Each Type</h4><p><strong>Unbuffered channels</strong> are for synchronization. You want the sender and receiver to coordinate. A send doesn’t complete until someone receives. This creates a happens-before relationship that’s useful for correctness.</p><p>Use unbuffered when you want tight coordination between goroutines and you don’t need to decouple production from consumption.</p><p><strong>Buffered channels</strong> are for smoothing out temporary mismatches in production and consumption rates. If producers sometimes create values faster than consumers process them a buffer prevents the producers from blocking immediately.</p><p>Use buffered when you know the maximum queue size and you want to avoid blocking producers for temporary slowdowns in consumption.</p><p>The danger with buffered channels: picking an arbitrary buffer size. If you make it 100 because “that seems big enough” you’re guessing. Either the buffer is unnecessary (traffic never fills it) or it’s too small (producers still block when it fills) or it hides a design problem (unbounded queue growth that you’re papering over with a fixed buffer).</p><p><strong>General guidance:</strong> start with unbuffered. Add a buffer only when profiling shows producers blocking unnecessarily and you understand the traffic pattern well enough to pick a meaningful size.</p><h3>WaitGroups: Waiting for Goroutines Properly</h3><p>Remember that hack with time.Sleep() to wait for goroutines? WaitGroups are the proper solution.</p><p>A WaitGroup is a counter. You increment it when spawning goroutines. Each goroutine decrements it when finishing. You block waiting for the counter to reach zero.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>func worker(id int, wg *sync.WaitGroup) {<br>    defer wg.Done()  // Decrement counter when function exits<br>    <br>    fmt.Printf(&quot;Worker %d starting\n&quot;, id)<br>    time.Sleep(100 * time.Millisecond)<br>    fmt.Printf(&quot;Worker %d done\n&quot;, id)<br>}<br><br>func main() {<br>    var wg sync.WaitGroup<br>    <br>    for i := 1; i &lt;= 5; i++ {<br>        wg.Add(1)  // Increment counter<br>        go worker(i, &amp;wg)<br>    }<br>    <br>    wg.Wait()  // Block until counter reaches 0<br>    fmt.Println(&quot;All workers finished&quot;)<br>}</pre><p>Walking through this:</p><ol><li>We create a WaitGroup called wg</li><li>Before spawning each goroutine we call wg.Add(1) which increments the internal counter</li><li>We spawn the goroutine passing a pointer to the WaitGroup</li><li>Inside each goroutine defer wg.Done() runs when the function exits, decrementing the counter</li><li>Main calls wg.Wait() which blocks until the counter reaches zero</li><li>When all 5 goroutines finish and call Done() the counter hits zero and Wait() unblocks</li><li>Main continues and prints “All workers finished”</li></ol><p>The defer keyword is important. It ensures Done() runs even if the function panics or returns early. You don&#39;t want to forget to decrement the counter because then Wait() blocks forever.</p><p><strong>Why pass a pointer to the WaitGroup?</strong> Because if you pass the WaitGroup by value each goroutine gets a copy. Calling Done() on a copy doesn&#39;t affect the original WaitGroup that main is waiting on. You&#39;d wait forever. Always pass &amp;wg (a pointer) so all goroutines work with the same WaitGroup.</p><h4>Common WaitGroup Mistake: Loop Variable Capture</h4><p>This bug appears constantly:</p><pre>// WRONG - bug lurking<br>var wg sync.WaitGroup<br><br>for i := 1; i &lt;= 5; i++ {<br>    wg.Add(1)<br>    go func() {<br>        defer wg.Done()<br>        fmt.Println(i)  // BUG: all goroutines see the same i<br>    }()<br>}<br><br>wg.Wait()</pre><p>What you expect: prints 1, 2, 3, 4, 5 in some order</p><p>What actually happens: might print 6, 6, 6, 6, 6 or 5, 5, 5, 5, 5</p><p><strong>Why?</strong> The goroutines capture the variable i by reference, not by value. By the time the goroutines actually run and read i, the loop has already finished. The variable i now holds 6 (the value that made the loop condition false). All goroutines read that same variable and see 6.</p><p><strong>The fix is </strong>pass the value explicitly:</p><pre>// CORRECT<br>var wg sync.WaitGroup<br><br>for i := 1; i &lt;= 5; i++ {<br>    wg.Add(1)<br>    go func(id int) {<br>        defer wg.Done()<br>        fmt.Println(id)<br>    }(i)  // Pass i as argument<br>}<br><br>wg.Wait()</pre><p>Now each goroutine receives its own copy of the value when spawned. Goroutine 1 gets value 1. Goroutine 2 gets value 2. No shared variable, no race condition.</p><p>This pattern, passing loop variables as function arguments and applies any time you spawn goroutines in a loop.</p><p>Concurrency in Go is about structure.</p><p>You write code that breaks work into independent pieces. Goroutines execute those pieces. Channels coordinate between them. WaitGroups track completion.</p><p>The go keyword is deceptively simple. Add it carelessly and you get memory leaks, deadlocks, and race conditions that only appear under load. Use it with channels and WaitGroups and you get clean concurrent code that survives production.</p><p>Start with the simplest case: one goroutine sending to one channel. Then add WaitGroups when you need to spawn multiple goroutines and wait for them. Then explore buffered channels when unbuffered synchronization becomes a bottleneck.</p><p><strong>The bugs you’ll hit:</strong> goroutine leaks from channels that never close, deadlocks from unbuffered channels without receivers, loop variable captures that give all goroutines the wrong value.</p><p><strong>The patterns you’ll use:</strong> fan-out/fan-in for parallel processing, worker pools for bounded concurrency, done channels for cancellation, WaitGroups for synchronization.</p><p>Go’s concurrency model isn’t about making code run faster. It’s about making concurrent code that’s correct, readable, and doesn’t explode when real users hit it.</p><p>Follow for more tech contents I learned :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c156fe73856d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your App is Slow Because of N+1 Queries]]></title>
            <link>https://medium.com/@ammarmusyaffa/your-app-is-slow-because-of-n-1-queries-fe4b779e1081?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe4b779e1081</guid>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Sat, 02 May 2026 01:31:28 GMT</pubDate>
            <atom:updated>2026-05-02T01:31:28.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*MfZ9BsHwSqQiTuX4OgAkJQ.png" /><figcaption>N+1 Query Illustration (<a href="https://www.linkedin.com/pulse/classic-n1-problem-sql-neelendra-kumar-i2kxc/">Source</a>)</figcaption></figure><p>Your app works perfectly in development.</p><p>You test it with 10 users. Fast. You test it with 20 posts. Smooth. Everything loads in milliseconds. You deploy to production feeling confident.</p><p>Then real users start using it. Suddenly pages take 3 seconds to load. The database CPU spikes to 80%. Your monitoring dashboard lights up like a Christmas tree haha.</p><p><strong>What happened?</strong></p><p>You have a N+1 query problem. And the worst part? Your code looks completely normal. No obvious bugs. No syntax errors. Just innocent-looking loops that are secretly destroying your database performance.</p><h3>What Is a N+1 Query Problem?</h3><p>The N+1 problem happens when your code makes one query to fetch a list of items, then makes additional queries for each item in that list. This problem usually happened if we use the ORM. <br>ORM stands for Object Relational Mapping which is a programming technique that lets you interact with a database using the language you are already using (like Python, Java, Javascript, or PHP) instead of writing raw SQL. It acts as a bridge between Objects (in code) and Tables (in a Relational Database). You treat database rows like objects. For example, instead of SELECT * FROM users, you might just call User.all(). While ORMs make development faster, they often hide the underlying SQL execution, leading to the N+1 Query problem. This occurs primarily due to a feature called Lazy Loading.</p><p><strong>One query to get N items, then N queries to get related data. That’s N+1 queries total.</strong></p><p>Let me show you the exact code that causes this. You’ve probably written something similar.</p><pre>// Fetching all users<br>const users = await User.findAll(); // 1 query<br><br>// Looping through users to get their posts<br>for (const user of users) {<br>  const posts = await Post.findAll({ where: { userId: user.id } }); // N queries<br>  user.posts = posts;<br>}</pre><p>Looks harmless right? You fetch all users and then for each user you fetch their posts. Clean code and easy to read.</p><p><strong>But here’s what actually happens in the database:</strong></p><pre>-- Query 1: Get all users<br>SELECT * FROM users;<br><br>-- Query 2: Get posts for user 1<br>SELECT * FROM posts WHERE user_id = 1;<br><br>-- Query 3: Get posts for user 2<br>SELECT * FROM posts WHERE user_id = 2;<br><br>-- Query 4: Get posts for user 3<br>SELECT * FROM posts WHERE user_id = 3;<br><br>-- ... this continues for every single user</pre><p>If you have 100 users you’re making 101 database queries. If you have 1000 users you’re making 1001 queries.</p><p><strong>Each query has overhead.</strong> Network latency. Query parsing. Execution planning. Result serialization. It all adds up.</p><h3>Why This Destroys Performance</h3><p>Database queries are expensive. Not because the database is slow but because of everything that happens around the query.</p><h4>The hidden costs of each query</h4><p><strong>Network round trip: </strong>Your application server talks to your database server over the network. Even on the same data center this takes milliseconds. Do this 1000 times and those milliseconds become seconds.</p><p><strong>Connection overhead: </strong>Opening and maintaining database connections uses memory and CPU. Connection pools help but they have limits. Flood your pool with tiny queries and you’ll exhaust connections.</p><p><strong>Query planning: </strong>The database needs to parse your SQL, build an execution plan, and optimize it. For simple queries this is fast but it still takes time. Multiply by 1000 and it becomes noticeable.</p><p><strong>Context switching: </strong>The database switches between queries. Each switch has a cost and your database works harder doing administrative tasks than actual data retrieval.</p><h4>The math gets ugly fast:</h4><pre>10 users = 11 queries = 50ms total<br>100 users = 101 queries = 500ms total<br>1000 users = 1001 queries = 5000ms total (5 seconds!)<br>10000 users = 10001 queries = 50000ms total (50 seconds!!!)</pre><p>And this is just for one page load. Imagine 100 concurrent users all triggering this pattern.</p><p><strong>Your database doesn’t stand a chance.</strong></p><h3>Real-World Example: The Blog Dashboard</h3><p>Let me show you a real scenario I’ve seen destroy production systems multiple times.</p><p>You’re building a blog platform. The admin dashboard shows all posts with their authors and comment counts.</p><pre>// Get all posts<br>const posts = await Post.findAll(); // 1 query<br><br>// For each post, get the author<br>for (const post of posts) {<br>  const author = await User.findOne({ where: { id: post.authorId } }); // N queries<br>  post.author = author;<br>  <br>  // And get comment count<br>  const commentCount = await Comment.count({ where: { postId: post.id } }); // N more queries<br>  post.commentCount = commentCount;<br>}</pre><p><strong>What’s happening here:</strong></p><ul><li>1 query to get all posts</li><li>N queries to get each author</li><li>N queries to get each comment count</li><li><strong>Total: 1 + N + N = 1 + 2N queries</strong></li></ul><p>For 50 posts you’re making 101 queries. The page that should load in 100ms now takes 2 seconds.</p><h4>The SQL being executed:</h4><pre>SELECT * FROM posts;<br><br>SELECT * FROM users WHERE id = 1;<br>SELECT COUNT(*) FROM comments WHERE post_id = 1;<br><br>SELECT * FROM users WHERE id = 2;<br>SELECT COUNT(*) FROM comments WHERE post_id = 2;<br><br>SELECT * FROM users WHERE id = 3;<br>SELECT COUNT(*) FROM comments WHERE post_id = 3;<br><br>-- ... and so on for 50 posts</pre><p>Your database is working overtime to fetch data that could have been retrieved in 3 queries.</p><h3>How to Fix N+1 Queries</h3><p>The solution is simple in concept: fetch everything you need in as few queries as possible.</p><h4>Solution 1: Eager Loading (The ORM Way)</h4><p>Most ORMs have built-in support for eager loading. You tell the ORM what related data you need upfront.</p><p><strong>Prisma ORM (Node.js):</strong></p><pre>// BEFORE (N+1 Query Problem)<br>// 1 query to get all users<br>const users = await prisma.user.findMany();<br><br>users.forEach(async (user) =&gt; {<br>  // N queries: Each loop triggers a separate DB call for posts<br>  const posts = await prisma.post.findMany({ where: { authorId: user.id } });<br>  console.log(posts);<br>});<br><br><br>// AFTER (with Eager Loading way)<br>// Only 2 queries: One for users, one for all related posts (using IN)<br>const users = await prisma.user.findMany({<br>  include: {<br>    posts: true,<br>  },<br>});</pre><p><strong>Eloquent ORM (Laravel / PHP):</strong></p><pre>// BEFORE (N+1 Query)<br>// 1 query: select * from books<br>$books = Book::all();<br><br>foreach ($books as $book) {<br>    // N queries: select * from authors where id = ?<br>    echo $book-&gt;author-&gt;name;<br>}<br><br><br>// AFTER (with Eager Loading way)<br>// Only 2 queries: select * from books &amp; select * from authors where id IN (...)<br>$users = User::with(&#39;posts&#39;)-&gt;get();<br>// SQL: select * from users;<br>// SQL: select * from posts where user_id in (1, 2, 3...);</pre><p><strong>Django (Python):</strong></p><pre># BEFORE (N+1 Query)<br># 1 query to get all orders<br>orders = Order.objects.all()<br><br>for order in orders:<br>    # N queries to get each customer<br>    print(order.customer.name)<br><br><br># AFTER (with Eager Loading way)<br># Runs 2 queries<br>users = User.objects.prefetch_related(&#39;posts&#39;).all()</pre><p>The ORM generates two separate queries (one for the main data, one for the related data using IN) and maps them together in memory.</p><h4>Solution 2: Manual JOINs (The SQL Way)</h4><p>Sometimes you need more control. Write the JOIN yourself.</p><pre>-- Instead of 101 queries, use 1 query with a JOIN<br>SELECT <br>  users.id,<br>  users.name,<br>  posts.id AS post_id,<br>  posts.title,<br>  posts.content<br>FROM users<br>LEFT JOIN posts ON posts.user_id = users.id;</pre><p>This returns all users and their posts in a single query. You’ll need to restructure the data in your application code but the database hit happens once.</p><h4>Solution 3: Separate Optimized Queries</h4><p>Sometimes JOINs aren’t the answer. When you have multiple relationships it’s often better to use separate queries that fetch all the data efficiently.</p><pre>// Get all posts<br>const posts = await Post.findAll(); // 1 query<br><br>// Get all unique author IDs<br>const authorIds = [...new Set(posts.map(p =&gt; p.authorId))];<br><br>// Fetch all authors in one query<br>const authors = await User.findAll({ where: { id: authorIds } }); // 1 query<br><br>// Fetch all comment counts in one query<br>const commentCounts = await Comment.findAll({<br>  where: { postId: posts.map(p =&gt; p.id) },<br>  attributes: [&#39;postId&#39;, [sequelize.fn(&#39;COUNT&#39;, sequelize.col(&#39;id&#39;)), &#39;count&#39;]],<br>  group: [&#39;postId&#39;]<br>}); // 1 query<br><br>// Map the data together in application code<br>const authorsMap = Object.fromEntries(authors.map(a =&gt; [a.id, a]));<br>const countsMap = Object.fromEntries(commentCounts.map(c =&gt; [c.postId, c.count]));<br><br>posts.forEach(post =&gt; {<br>  post.author = authorsMap[post.authorId];<br>  post.commentCount = countsMap[post.id] || 0;<br>});</pre><p><strong>Total queries: 3 instead of 101.</strong></p><p>The key principle is the same, fetch all the data you need in the minimum number of queries and then assemble it in memory.</p><h3>Common Mistakes When Fixing N+1</h3><h4>Mistake 1: Over-Eager Loading</h4><p>You fix one N+1 problem by eager loading everything and now you’re fetching data you don’t need.</p><pre>// Overkill pattern<br>const users = await User.findAll({<br>  include: [<br>    { model: Post, include: [{ model: Comment, include: [{ model: Like }] }] },<br>    { model: Profile },<br>    { model: Setting },<br>    { model: Notification }<br>  ]<br>});</pre><p>You wanted to show usernames on a list page. You just fetched their entire social graph including posts, comments, likes, profiles, settings, and notifications.</p><p><strong>Now you have a different performance problem.</strong> You’re transferring megabytes of data you’ll never use.</p><p>Fix that with only eager load what you actually need for that specific view.</p><h4>Mistake 2: Ignoring Pagination</h4><p>You fixed the N+1 but you’re still loading all 10000 records into memory.</p><pre>// Still problematic<br>const users = await User.findAll({<br>  include: [{ model: Post }]<br>}); // Fetches all users and all their posts</pre><p>If you have thousands of users this will consume massive amounts of memory and still be slow.</p><p>Fix it with always paginate and fetch data in chunks.</p><pre>const users = await User.findAll({<br>  include: [{ model: Post }],<br>  limit: 20,<br>  offset: page * 20<br>});</pre><h4>Mistake 3: Not Monitoring Query Count</h4><p>You fix the obvious N+1 problems but miss the subtle ones. Without monitoring you don’t know if you’ve actually solved the issue.</p><p>Fix it with use query logging in development. Tools like Prisma built-in logger, Laravel Debugbar or Basic Query Logging, and Django Debug Toolbar query logging show you exactly how many queries run per request.</p><pre>const prisma = new PrismaClient({<br>  log: [<br>    {<br>      emit: &#39;stdout&#39;,<br>      level: &#39;query&#39;, // This logs every SQL query to the terminal<br>    },<br>    {<br>      emit: &#39;stdout&#39;,<br>      level: &#39;info&#39;,<br>    },<br>    {<br>      emit: &#39;stdout&#39;,<br>      level: &#39;warn&#39;,<br>    },<br>  ],<br>})</pre><p>In development if you see more than 5–10 queries for a single page load you probably have an N+1 problem lurking.</p><h3>How to Detect N+1 Problems</h3><h4>In Development:</h4><p><strong>Enable query logging.</strong> Most ORMs can log every SQL query. Watch for patterns where the same query runs multiple times with different parameters.</p><pre>SELECT * FROM posts WHERE user_id = 1<br>SELECT * FROM posts WHERE user_id = 2<br>SELECT * FROM posts WHERE user_id = 3</pre><p>If you see this pattern you have N+1.</p><p><strong>Use profiling tools.</strong> Browser dev tools can show you slow API responses. ORM profilers can show you query counts.</p><h4>In Production:</h4><p><strong>Monitor database query counts.</strong> If a single endpoint generates hundreds of queries something is wrong.</p><p><strong>Watch for slow endpoints.</strong> An endpoint that’s slow under load but fast with 10 test records probably has N+1 issues.</p><p><strong>Check database CPU and connection usage.</strong> Spiking CPU with high query throughput but low data transfer often indicates many small queries instead of few large ones.</p><h3>N+1 queries are invisible until they’re not.</h3><p>Your code looks clean. Your tests pass and everything works in development. Then you deploy to production with real data volumes and the performance collapses.</p><p><strong>The pattern is always the same:</strong> loops that trigger database queries.</p><pre>for (const item of items) {<br>  await fetchRelatedData(item); // RED FLAG<br>}</pre><p>Any time you see await inside a loop and it&#39;s calling the database you should immediately think &quot;is this an N+1 problem?&quot;</p><p>The fix is conceptually simple: fetch everything upfront, then loop through it in memory.</p><pre>// Fetch all at once<br>const allRelatedData = await fetchAllRelatedData(items.map(i =&gt; i.id));<br><br>// Loop in memory (fast)<br>for (const item of items) {<br>  item.relatedData = allRelatedData.filter(d =&gt; d.itemId === item.id);<br>}</pre><p><strong>Database queries are expensive. Memory operations are cheap.</strong> Fetch once. Process in memory.</p><p>N+1 queries are silent killers.</p><p>They don’t throw errors. They don’t fail tests. They just make your app slower and slower as your data grows.</p><p><strong>The warning signs:</strong></p><ul><li>Pages that are fast in development but slow in production</li><li>Query counts that scale with data volume</li><li>Database CPU that spikes under load</li><li>Endpoints that make dozens or hundreds of queries</li></ul><p><strong>The solution is always the same:</strong> stop querying in loops. Fetch everything you need upfront. Use eager loading, JOINs, or batch queries.</p><p>Your database will thank you. Your users will notice. Your AWS bill will drop.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe4b779e1081" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API is Just Like “JSON Over HTTP” API]]></title>
            <link>https://medium.com/@ammarmusyaffa/rest-api-is-just-more-like-json-over-http-api-f0b028e9d925?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0b028e9d925</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 03:15:16 GMT</pubDate>
            <atom:updated>2026-04-21T03:37:43.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzbRWoI8bpf42wof1DijOg.png" /></figure><p>You’ve built a REST API.</p><p>At least that’s what you call it. You have endpoints like /api/users and /api/products. You use GET for fetching data and POST for creating data in the resources. You return the JSON and you think you&#39;re following REST principles.</p><p><strong>But the uncomfortable truth is your API probably isn’t RESTful at all.</strong></p><p>And the plot twist? It doesn’t matter. Most “REST APIs” in production are just HTTP APIs with JSON responses. They work perfectly fine. Companies make millions with them and developers love using them.</p><p>So why does everyone claim to build REST APIs when they’re actually building something else entirely?</p><h3><strong>What REST Actually Means</strong></h3><p>REST stands for Representational State Transfer. It was defined by Roy Fielding in his 2000 PhD dissertation. That’s not a blog post or a tutorial. That’s a formal academic paper that most developers have never read.</p><p>Fielding laid out six architectural constraints that a system must follow to be considered RESTful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*pT5NDzn5Svc-kX7FYVeGVQ.png" /></figure><p>Most developers know the first three. But the sixth constraint (uniform interface), is where everything falls apart. This constraint has four sub-requirements that almost no API actually implements.</p><h3>The Uniform Interface Constraint (Where Your API Fails)</h3><p>To have a true uniform interface your API needs four things:</p><h4>1. Identification of Resources</h4><p>Resources should be identified through URIs. Most APIs get this right. You have /users/123 to represent user 123. You have /products/456 to represent product 456.</p><p><strong>This part is easy.</strong> Almost every HTTP API does this naturally.</p><h4>2. Manipulation of Resources Through Representations</h4><p>When a client holds a representation of a resource it should have enough information to modify or delete that resource. The JSON you return should include everything needed for the client to perform operations.</p><p><strong>Most APIs get this right too.</strong> You return a user object with all the data and the client knows how to update it.</p><h4>3. Self-Descriptive Messages</h4><p>Each message should include enough information to describe how to process it. This means proper use of HTTP headers, media types, and status codes.</p><p>Your API probably does this halfway. You use Content-Type: application/json and return proper status codes like 200 or 404. But you probably don&#39;t use standard media types like application/vnd.api+json or include hypermedia controls.</p><p><strong>This is where things start to crack.</strong></p><h4>4. Hypermedia as the Engine of Application State (HATEOAS)</h4><p>This is the big one. The constraint that almost nobody implements.</p><p>HATEOAS means your API responses should include links that tell clients what they can do next. The client should be able to navigate your entire API by following links, just like browsing a website.</p><p><strong>A true RESTful response looks like this:</strong></p><pre>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;links&quot;: {<br>    &quot;self&quot;: {<br>      &quot;href&quot;: &quot;https://api.example.com/users/123&quot;,<br>      &quot;method&quot;: &quot;GET&quot;<br>    },<br>    &quot;update&quot;: {<br>      &quot;href&quot;: &quot;https://api.example.com/users/123&quot;,<br>      &quot;method&quot;: &quot;PUT&quot;<br>    },<br>    &quot;delete&quot;: {<br>      &quot;href&quot;: &quot;https://api.example.com/users/123&quot;,<br>      &quot;method&quot;: &quot;DELETE&quot;<br>    },<br>    &quot;orders&quot;: {<br>      &quot;href&quot;: &quot;https://api.example.com/users/123/orders&quot;,<br>      &quot;method&quot;: &quot;GET&quot;<br>    }<br>  }<br>}</pre><p>The client doesn’t need to know your URL structure. It just follows the links you provide. If you change /users/123/orders to /orders?userId=123 tomorrow the client still works because it&#39;s following the link you gave it.</p><p><strong>Your API probably returns this instead:</strong></p><pre>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><p>No links. No discoverability. The client has to hardcode all your endpoints. If you change the URL structure the client breaks.</p><p><strong>This is not REST. This is a JSON API over HTTP.</strong></p><h3>Why Nobody Actually Builds RESTful APIs</h3><p>HATEOAS sounds great in theory. In practice it’s a nightmare.</p><h4>The problems with HATEOAS:</h4><p><strong>It makes responses enormous.</strong> Adding links to every response increases payload size significantly. When you’re fetching a list of 100 users those link objects add up fast. More bandwidth. Slower responses. Higher costs.</p><p><strong>Clients ignore the links anyway.</strong> Frontend developers hardcode endpoints. Mobile apps hardcode endpoints. Nobody writes code that dynamically discovers and follows links. It’s easier to read the documentation and write fetch(&#39;/api/users/123/orders&#39;) than to parse through link objects.</p><p><strong>It’s harder to version.</strong> When your API evolves you need to maintain those link structures. Breaking changes become more complex because you’re not just changing data formats, you’re changing navigation paths.</p><p><strong>Documentation becomes confusing.</strong> Try explaining to a new developer that they need to first fetch /api/users/123 to get links, then follow the orders link to get orders. Or just tell them to call /api/users/123/orders directly. Which do you think is clearer?</p><p><strong>The tooling isn’t there.</strong> Postman and Swagger don’t have first-class support for HATEOAS. API clients don’t automatically follow links. Testing becomes more complex.</p><h3>What We Actually Build (And Why It Works)</h3><p>Most modern APIs are what we call <strong>HTTP APIs</strong> or <strong>JSON APIs</strong>. They use HTTP methods and return JSON but they don’t follow all REST constraints.</p><p>Here’s what a typical modern API looks like:</p><pre>// GET /api/users/123<br>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;email&quot;: &quot;john@example.com&quot;,<br>  &quot;created_at&quot;: &quot;2024-01-15T10:30:00Z&quot;<br>}<br><br>// POST /api/users<br>{<br>  &quot;name&quot;: &quot;Jane Smith&quot;,<br>  &quot;email&quot;: &quot;jane@example.com&quot;<br>}<br><br>// PUT /api/users/123<br>{<br>  &quot;name&quot;: &quot;John Updated&quot;,<br>  &quot;email&quot;: &quot;john.new@example.com&quot;<br>}<br><br>// DELETE /api/users/123<br>// Returns 204 No Content</pre><p>This works because:</p><p><strong>It’s predictable.</strong> Developers know that GET fetches data, POST creates, PUT updates, DELETE removes. No surprises.</p><p><strong>It’s well-documented.</strong> Tools like Swagger and OpenAPI make it trivial to generate interactive documentation. Developers can see all endpoints, test them, and understand them in minutes.</p><p><strong>It’s efficient.</strong> Responses contain only the data you need. No extra link objects bloating the payload.</p><p><strong>It’s easy to consume.</strong> Frontend frameworks and mobile SDKs can generate type-safe clients automatically. No dynamic link parsing required.</p><p><strong>It scales.</strong> When your API serves millions of requests per day every byte matters. Removing unnecessary link objects saves bandwidth and money.</p><h3>The Great REST Debate</h3><p>The backend community has fought about this for years. Purists argue that if you’re not following all six constraints you shouldn’t call it REST. Pragmatists argue that REST is a spectrum and practical implementations are good enough.</p><p><strong>Roy Fielding himself has weighed in.</strong> In 2008 he wrote a blog post titled “REST APIs must be hypertext-driven” where he stated that without hypermedia an API is not RESTful. He was frustrated that people were calling their APIs RESTful when they clearly weren’t.</p><p>But the industry didn’t listen. The term “REST API” had already taken on a life of its own. It became shorthand for “HTTP API that returns JSON and uses standard methods.” The academic definition got left behind.</p><h3>When True REST Actually Makes Sense</h3><p>There are scenarios where true RESTful APIs with HATEOAS are valuable:</p><p><strong>Public APIs with long lifespans.</strong> If you’re building an API that external developers will use for 10+ years and you want to evolve it without breaking clients, hypermedia can help. GitHub’s API is a good example — they use HATEOAS extensively.</p><p><strong>Complex workflows with many states.</strong> If your API represents a state machine where different actions are available at different states, HATEOAS can communicate what’s possible at each step. Payment processing APIs sometimes use this approach.</p><p><strong>APIs where discoverability matters more than performance.</strong> If developers need to explore your API interactively and you’re willing to trade payload size for flexibility, HATEOAS can provide a better developer experience.</p><p>But for most internal APIs, mobile backends, and microservices? The overhead isn’t worth it.</p><h3>What to Call Your API Instead</h3><p>If your API isn’t truly RESTful what should you call it?</p><p><strong>HTTP API</strong> is the most accurate term. You’re using HTTP methods and status codes but you’re not following REST constraints strictly.</p><p><strong>JSON API</strong> works if you’re specifically returning JSON. There’s even a specification called JSON API that standardizes response formats without requiring HATEOAS.</p><p><strong>RESTful-ish API</strong> is honest but sounds awkward in documentation.</p><p><strong>REST API</strong> is technically wrong but universally understood. If you use this term nobody will correct you. Everyone knows what you mean. It’s become the <em>de facto</em> standard terminology even if it’s academically incorrect.</p><h3>Best Practices for “REST” APIs (That Aren’t Actually RESTful)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PDUCxxYfb66eN9aX9MhUVA.jpeg" /></figure><p>If you’re building a modern HTTP API here’s what actually matters:</p><h4>Use HTTP Methods Correctly</h4><ul><li><strong>GET</strong> for fetching data (safe and idempotent)</li><li><strong>POST</strong> for creating resources</li><li><strong>PUT</strong> for full replacement of resources</li><li><strong>PATCH</strong> for partial updates</li><li><strong>DELETE</strong> for removing resources</li></ul><h4>Return Meaningful Status Codes</h4><ul><li><strong>200 OK</strong> for successful GET, PUT, PATCH</li><li><strong>201 Created</strong> for successful POST</li><li><strong>204 No Content</strong> for successful DELETE</li><li><strong>400 Bad Request</strong> for client errors</li><li><strong>401 Unauthorized</strong> for missing authentication</li><li><strong>403 Forbidden</strong> for insufficient permissions</li><li><strong>404 Not Found</strong> for missing resources</li><li><strong>500 Internal Server Error</strong> for server failures</li></ul><h4>Design Intuitive URLs</h4><pre>// Good<br>GET    /api/users<br>GET    /api/users/123<br>POST   /api/users<br>PUT    /api/users/123<br>DELETE /api/users/123<br>GET    /api/users/123/orders</pre><pre>// Bad<br>GET    /api/getUsers<br>POST   /api/createUser<br>POST   /api/deleteUser?id=123<br>GET    /api/user_orders?userId=123</pre><h4>Use Consistent Response Formats</h4><pre>// Success response<br>{<br>  &quot;data&quot;: {<br>    &quot;id&quot;: 123,<br>    &quot;name&quot;: &quot;John Doe&quot;<br>  }<br>}</pre><pre>// Error response<br>{<br>  &quot;error&quot;: {<br>    &quot;code&quot;: &quot;VALIDATION_ERROR&quot;,<br>    &quot;message&quot;: &quot;Email is required&quot;,<br>    &quot;details&quot;: [<br>      { &quot;field&quot;: &quot;email&quot;, &quot;message&quot;: &quot;This field is required&quot; }<br>    ]<br>  }<br>}</pre><h4>Version Your API</h4><pre>// URL versioning (most common)<br>/api/v1/users<br>/api/v2/users</pre><pre>// Header versioning (more &quot;RESTful&quot;)<br>GET /api/users<br>Accept: application/vnd.myapi.v2+json</pre><h4>Document Everything</h4><p>Use tools like Swagger/OpenAPI. Generate interactive documentation. Make it easy for developers to understand and test your endpoints without reading code.</p><p>The industry collectively decided that practical APIs are more valuable than academically pure ones.</p><p>REST as Fielding defined it is a brilliant architectural style. But it was designed for the web, for browsers navigating hyperlinked documents. APIs are different. They serve mobile apps, single-page applications, and backend services that need predictable, efficient endpoints.</p><p><strong>HATEOAS works great for humans browsing websites. It’s overkill for machines calling APIs.</strong></p><p>So we kept the good parts, HTTP methods, status codes, resource-based URLs , and dropped the parts that added complexity without clear value. The result isn’t REST but it works better for the problems we’re actually solving.</p><p>Your API probably isn’t RESTful and that’s completely fine.</p><p>You’re building a JSON API over HTTP. You’re using standard methods and status codes. You’re designing intuitive resource URLs. You’re returning structured data that clients can consume efficiently.</p><p><strong>This is what the industry needs.</strong> It’s what developers want to build. It’s what companies depend on.</p><p>The academic definition of REST still matters. It taught us valuable principles about statelessness, caching, and uniform interfaces. But we’ve evolved beyond the original constraints to build something more practical.</p><p>Call it a REST API if you want. Call it an HTTP API if you’re being pedantic. Just build it well, document it clearly, and make it easy for developers to use.</p><p><strong>That’s what actually matters.</strong></p><p><strong>What do you call your APIs? REST, HTTP, or something else? Have you ever implemented HATEOAS in production? Share your experience in the comments.</strong></p><p>Follow for more honest takes on backend development that cut through the buzzwords.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0b028e9d925" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Has No Memory, Every Request Is a Stranger]]></title>
            <link>https://medium.com/@ammarmusyaffa/http-has-no-memory-every-request-is-a-stranger-e139a61fb93f?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e139a61fb93f</guid>
            <category><![CDATA[stateless]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Tue, 14 Apr 2026 11:25:18 GMT</pubDate>
            <atom:updated>2026-04-14T11:25:18.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*RPcj-YCNLdKey7YFMdblhA.jpeg" /></figure><p>Imagine you just logged into your favorite app. You click around, add items to cart, and update your profile. Then you refresh the page and… you’re still logged in.</p><p><strong>But here’s the weird part, HTTP forgot you existed 0.3 seconds ago.</strong></p><p>HTTP has no memory. Every request is a completely new conversation. The server doesn’t remember who you are, what you just did, or whether you’re logged in. Each request stands alone.</p><p>Think of it like talking to someone with amnesia. Every sentence you say they treat you like a stranger. You introduce yourself, have a conversation, then the next time you speak they ask “Who are you again?”</p><p>That’s HTTP.</p><h3>Why HTTP Was Built This Way</h3><p>Statelessness isn’t a limitation. It’s a superpower.</p><p>When servers don’t remember anything between requests they become infinitely scalable. Any server in a cluster can handle any request without needing to know what happened before. No session synchronization. No sticky routing. No memory overhead.</p><p>If a server crashes it doesn’t take user sessions down with it. The next request just goes to a different server and life continues.</p><p><strong>Statelessness = Scalability.</strong></p><p>This design choice is why the web can handle billions of users simultaneously. It’s why you can refresh a page and hit a completely different server without noticing.</p><h3>The Problem This Creates</h3><p>But statelessness creates an obvious issue. You log in and the server says “OK you’re authenticated.” Then you make another request and the server has no idea who you are.</p><p><strong>So how do websites remember you?</strong></p><p>The answer is <strong>they don’t remember you</strong>. Instead they make <em>you</em> remember, and prove it every single time.</p><h4>Solution 1: Session</h4><p>The server gives you an ID card:</p><pre>HTTP/1.1 200 OK<br>Set-Cookie: sessionId=abc123xyz; HttpOnly; Secure</pre><p>Your browser automatically shows this ID with every future request. The server checks the ID against its database, finds your session data, and knows it’s you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*F7JXwQpwhO0phjYBXX_51Q.jpeg" /></figure><p><strong>The brilliance here? </strong>The server is still stateless in terms of HTTP. It doesn’t remember the <em>connection</em>. It just remembers that “sessionId abc123xyz belongs to user John.” Any server can look that up.</p><h4>Pros:</h4><ul><li><strong>More secure by default: </strong>HttpOnly flag prevents JavaScript from accessing the token (XSS protection).</li><li><strong>Easy revocation: </strong>Delete the session from the database and the user is instantly logged out.</li><li><strong>Browser handles everything: </strong>No manual code needed to attach tokens to requests.</li></ul><h4>Cons:</h4><ul><li><strong>Requires server-side storage: </strong>You need Redis or a database to store sessions (adds infrastructure).</li><li><strong>Harder to scale: </strong>All servers need access to the same session store.</li><li><strong>CSRF vulnerability: </strong>Browsers send cookies automatically, making CSRF attacks possible without proper protection.</li></ul><h4>Solution 2: JWT (JSON Web Tokens)</h4><p>Instead of giving you an ID that references server-side data, JWT gives you <strong>all the data</strong> in the token itself:</p><pre>// Server creates token<br>const token = jwt.sign(<br>  { userId: 123, role: &#39;admin&#39;, email: &#39;user@example.com&#39; },<br>  &#39;secret-key&#39;,<br>  { expiresIn: &#39;1h&#39; }<br>)</pre><p>The token is cryptographically signed so it can’t be tampered with. The client sends it with every request and the server just verifies the signature. No database lookup. No session storage. Completely stateless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFL3dSyYJT1eFJJyz8vc5w.png" /></figure><p><strong>This is why microservices architecture love JWT.</strong> Each service can verify tokens independently without coordinating with a central session store.</p><h4>Pros:</h4><ul><li><strong>Truly stateless: </strong>No server-side session storage needed, easier to scale horizontally</li><li><strong>Works across domains: </strong>Perfect for APIs consumed by mobile apps or third-party services</li><li><strong>Microservices-friendly: </strong>Each service can verify tokens independently without a shared database</li></ul><h4>Cons:</h4><ul><li><strong>Can’t revoke before expiry: </strong>Once issued, the token is valid until it expires (logout just deletes it client-side)</li><li><strong>Payload visible to anyone: </strong>JWTs are encoded not encrypted, never store sensitive data in them (e.g. password, account number, identification number, etc.)</li><li><strong>Larger request size: </strong>Token is sent with every request, increasing bandwidth compared to a small session ID</li></ul><h3>When to Use Session or JWT?</h3><h4>Use Cookies when:</h4><ul><li>You’re building a traditional web app with server-side rendering</li><li>Security is critical (HttpOnly cookies prevent XSS attacks)</li><li>You need fine-grained session control (immediate logout, session revocation)</li></ul><h4>Use JWT when:</h4><ul><li>You’re building APIs consumed by mobile apps or SPAs</li><li>You have a microservices architecture</li><li>You want true statelessness (no server-side session storage)</li><li>You need cross-domain authentication</li></ul><p>The debate isn’t about which is better. It’s about which fits your architecture.</p><p>HTTP is stateless by design. Every framework, every auth system, every “stay logged in” feature is just a clever workaround.</p><p><strong>We’re all building memory on top of amnesia.</strong></p><p>The server forgets you every 0.3 seconds. But through cookies or tokens you carry proof of who you are. You present it with every request. The server validates it and continues the conversation as if nothing happened.</p><p>It’s a beautiful dance. And once you see it you can’t unsee it.</p><p><strong>What’s your approach, Session Team or JWT Team? Any horror stories about stateless auth? Drop them in the comments.</strong></p><p>Follow for more deep dives into the tech powering your apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e139a61fb93f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every Click You Make on the Internet Involves HTTP (But You Never Notice)]]></title>
            <link>https://medium.com/@ammarmusyaffa/every-click-you-make-on-the-internet-involves-http-but-you-never-notice-3372ee03759e?source=rss-7f7079ab82a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3372ee03759e</guid>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ahmad Ammar Musyaffa]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 00:49:17 GMT</pubDate>
            <atom:updated>2026-04-10T00:49:17.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*0G8eMPyyWVNXC761ebjKxQ.png" /></figure><p>You just clicked this article.</p><p>Before the text appeared on your screen something happened in milliseconds. A conversation. Your browser whispered a request and a server somewhere whispered back. What is that conversation? That is HTTP.</p><p>But here’s the thing: you’ve been using it thousands of times a day for years and you probably never thought about it once.</p><h3>What HTTP Actually Is?</h3><p>Imagine you’re at a restaurant.</p><p>You (the client) tell the waiter what you want. The waiter writes it down and takes it to the kitchen (the server). The kitchen prepares your food and sends it back through the waiter. You receive your meal.</p><p><strong>That’s HTTP.</strong></p><p>HTTP stands for HyperText Transfer Protocol. Strip away the jargon and it’s just a <strong>set of rules for how computers talk to each other</strong> over the internet.</p><p>When you try to type www.example.com into your browser:</p><ol><li>Your browser creates an HTTP request</li><li>That request travels across the internet to a server</li><li>The server processes it</li><li>The server sends back an HTTP response</li><li>Your browser renders the response (HTML, CSS, JavaScript, images)</li></ol><p>All of this happens in <strong>under a second.</strong></p><h3>The Anatomy of an HTTP Request (The Stuff You Actually Need to Know)</h3><p>Here’s what a real HTTP request looks like:</p><pre>GET /api/users/123 HTTP/1.1<br>Host: api.example.com<br>User-Agent: Mozilla/5.0<br>Accept: application/json<br>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><p>Let me break this down:</p><h4>The Request Line</h4><p>GET /api/users/123 HTTP/1.1</p><ul><li><strong>GET</strong> = the HTTP method (what you want to do)</li><li><strong>/api/users/123</strong> = the resource you want</li><li><strong>HTTP/1.1</strong> = the protocol version</li></ul><h4>The Headers</h4><p>Those lines after the request line? Headers. Metadata about your request.</p><ul><li>Host tells the server which domain you&#39;re targeting</li><li>User-Agent identifies your browser</li><li>Accept tells the server what format you want back</li><li>Authorization proves you&#39;re allowed to access this resource</li></ul><p>Think of headers as the <strong>envelope</strong> around your letter. The request line is the letter itself.</p><h3>The HTTP Methods You’ll Actually Use</h3><p>There are 9 HTTP methods but realistically you’ll use these 5:</p><h4>GET : “Give me something”</h4><pre>fetch(&#39;https://api.github.com/users/octocat&#39;)<br>  .then(res =&gt; res.json())<br>  .then(data =&gt; console.log(data))</pre><p>Reading data. No side effects. Idempotent (you can call it 100 times and get the same result).</p><h4>POST : “Create something new”</h4><pre>fetch(&#39;https://api.example.com/users&#39;, {<br>  method: &#39;POST&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({ name: &#39;Alex&#39;, email: &#39;alex@example.com&#39; })<br>})</pre><p>Creating resources. Not idempotent (calling it twice creates two resources).</p><h4><strong>PUT</strong> : “Replace this entirely”</h4><pre>fetch(&#39;https://api.example.com/users/123&#39;, {<br>  method: &#39;PUT&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({ name: &#39;Alex Updated&#39;, email: &#39;newemail@example.com&#39; })<br>})</pre><p>This method will make full replacement of a resource.</p><h4>PATCH: “Update part of this”</h4><pre>fetch(&#39;https://api.example.com/users/123&#39;, {<br>  method: &#39;PATCH&#39;,<br>  headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  body: JSON.stringify({ email: &#39;newemail@example.com&#39; })<br>})</pre><p>Partial update. Only the fields you send get changed.</p><h4>DELETE : “Remove this”</h4><pre>fetch(&#39;https://api.example.com/users/123&#39;, {<br>  method: &#39;DELETE&#39;<br>})</pre><p>Self-explanatory.</p><p>In the PUT, PATCH, and DELETE method usually use the primary or unique resource part like id, email, etc.</p><h3>HTTP Status Codes: The Server’s Way of Talking Back</h3><p>When the server responds it sends a status code. Three digits that tell you everything.</p><h4>2xx = Success</h4><ul><li><strong>200 OK: </strong>Everything worked</li><li><strong>201 Created: </strong>Resource successfully created</li><li><strong>204 No Content: </strong>Success but no data to return</li></ul><h4>3xx = Redirection</h4><ul><li><strong>301 Moved Permanently: </strong>This resource has a new address</li><li><strong>302 Found: </strong>Temporary redirect</li></ul><h4>4xx = Client Error (You Messed Up)</h4><ul><li><strong>400 Bad Request: </strong>Your request was malformed</li><li><strong>401 Unauthorized: </strong>You need to log in</li><li><strong>403 Forbidden: </strong>You’re logged in but you don’t have permission</li><li><strong>404 Not Found: </strong>This resource doesn’t exist</li></ul><h4>5xx = Server Error (They Messed Up)</h4><ul><li><strong>500 Internal Server Error: </strong>Something broke on the server</li><li><strong>502 Bad Gateway: </strong>The server got an invalid response from another server</li><li><strong>503 Service Unavailable: </strong>Server is down or overloaded</li></ul><p><strong>Pro tip:</strong> If you get a 4xx it’s usually from your fault. If you get a 5xx it’s usually their fault.</p><p><strong>What’s your biggest “aha moment” with HTTP? Drop it in the comments.</strong></p><p>If this clicked for you give it a clap and follow for more deep dives into the tech you use every day without realizing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3372ee03759e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>