<?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 Kelvin Anigboro on Medium]]></title>
        <description><![CDATA[Stories by Kelvin Anigboro on Medium]]></description>
        <link>https://medium.com/@arrayoftech?source=rss-665d221b51ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u_GuFOdPMJkZ5qYKe6yi6A@2x.jpeg</url>
            <title>Stories by Kelvin Anigboro on Medium</title>
            <link>https://medium.com/@arrayoftech?source=rss-665d221b51ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:55:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arrayoftech/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 Bug That Lives in the Gap. TOCTOU]]></title>
            <link>https://blog.stackademic.com/the-bug-that-lives-in-the-gap-toctou-774ff95a8c95?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/774ff95a8c95</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Sat, 23 May 2026 12:22:56 GMT</pubDate>
            <atom:updated>2026-05-27T07:07:08.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ToXF6cqRES99ZTOEreYGkg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tumbao1949?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">James Wainscoat</a> on <a href="https://unsplash.com/photos/macro-shot-of-assorted-insects-on-green-leaf-GGewLGcQD-I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You check that a train seat is empty, then walk over to sit down. By the time you get there, someone’s already in it. You did the check. The check was correct. The world just changed between checking and acting.</p><p>That gap has a name in software! TOCTOU, time-of-check to time-of-use. It’s a whole class of bugs, and it’s one of those things that’s invisible until someone points it out, then you start seeing it everywhere.</p><p>A TOCTOU bug shows up whenever code checks a condition and then acts on it, assuming nothing changed in between. On a real system with multiple threads, processes, or users hitting it at once, plenty can change in between. That window is a race condition, two things are racing, and whether your code is correct depends on who wins.</p><p>The shape is always roughly this:</p><pre>1. Check:  is this thing safe / valid / available?<br>2. (...a sliver of time passes...)<br>3. Use:    act as if step 1 is still true.</pre><p>If something can change the state during step 2, the check in step 1 bought you nothing.</p><p>The famous version comes from Unix file handling. Say a privileged program wants to write to a file, but only if the user running it actually has access.</p><pre>// check: does the user have access?<br>if (access(&quot;/tmp/userfile&quot;, W_OK) == 0) {<br>    // use: open it and write<br>    int fd = open(&quot;/tmp/userfile&quot;, O_WRONLY);<br>    write(fd, data, len);<br>}</pre><p>Looks careful. It checks permissions before writing. But there’s a gap between access() and open(), and an attacker can use it: swap /tmp/userfile for a symlink pointing at something sensitive, like a system config file. The access() check passed against the original harmless file. The open() now hits the attacker&#39;s target instead. Your program writes somewhere it never should have, with privileges the attacker doesn&#39;t have.</p><p>The fix is to stop separating the check from the use. Open the file once and work with the resulting handle, so there’s no second lookup to hijack.</p><p>That example is from the 1990s, but the shape outlived the context. If you write web apps, this might read like an old C problem. It isn’t. The same thing turns up constantly in normal backend code, anywhere you look-then-leap across a boundary where state can change.</p><p>A user has £10 in credit. Two requests land at nearly the same instant, each trying to spend £10:</p><pre>const balance = await getBalance(userId);   // both read £10<br>if (balance &gt;= 10) {                         // both pass<br>    await charge(userId, 10);                // both charge -&gt; -£10<br>}</pre><p>Both requests read the balance before either one wrote, so both saw £10 and both went ahead. The user just spent £20 they didn’t have. Same thing with signup flows that check “is this username taken?” and then insert: two people register coolname at once, both checks come back clear, both inserts fire.</p><p>The lesson across all of these is the same: don’t trust a check you’ve separated from the action it’s guarding. A few ways to close the gap:</p><p><strong>Make it atomic.</strong> Collapse the check and the action into one indivisible step so nothing can slip in between. The balance race goes away if you let the database do the checking at write time:</p><pre>UPDATE accounts<br>SET balance = balance - 10<br>WHERE user_id = 1<br>  AND balance &gt;= 10;</pre><p>If that returns zero rows updated, someone else already spent the money — and you never moved it. The condition and the write are the same operation, so there’s no gap to lose. The username race dies the same way, to a uniqueness constraint: the database enforces “only one” when the row is written, instead of you asking first and hoping.</p><p><strong>Lock if you must.</strong> A row lock or mutex forces racers to take turns — the second one waits, then sees the real state. It works, but reach for it after atomic database guarantees, not before. Locks are easy to hold too long, and distributed locks in particular are their own rabbit hole; they rarely give you guarantees as strong as the database enforcing the write itself. If a single atomic write does the job, prefer it.</p><p><strong>Use the handle, not the name.</strong> This is the one worth internalising, because it goes well beyond files. In the C example the bug was re-resolving a <em>name</em> (/tmp/userfile) that could point somewhere new by the time you used it; the fix was to hold the <em>handle</em> and operate on that. The same move shows up everywhere once you look for it. An ETag or a row version number lets a write say &quot;only if nothing&#39;s changed since I read it.&quot; A lease or an opaque token pins you to a specific grant rather than re-checking a condition that might have flipped. The pattern is always the same: capture a reference to the exact thing you checked, then act on that instead of resolving a name the world is free to re-point underneath you.</p><p>TOCTOU bugs come from treating the world as frozen between observation and action. On real systems, it never is. The fix isn’t to check more carefully, it’s to design as if the state will change the instant after you look, because on any system busy enough to matter, eventually it will.</p><p><strong>Further reading</strong></p><p><a href="https://cwe.mitre.org/data/definitions/367.html"><strong>CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition</strong> </a>— MITRE’s canonical definition, built around the same SUID/symlink example. (cwe.mitre.org)</p><p><a href="https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use"><strong>TOCTOU on Wikipedia</strong> </a>— the history, and a good rundown of where it shows up beyond filesystems.</p><p><a href="https://capec.mitre.org/data/definitions/29.html"><strong>CAPEC-29: Leveraging TOCTOU Race Conditions</strong> </a>— the same thing from the attacker’s side: how the window actually gets exploited.</p><p><a href="https://nvd.nist.gov/vuln/detail/CVE-2026-35359"><strong>CVE-2026–35359</strong> </a>— a TOCTOU bug in the cp utility of uutils coreutils, patched May 2026. Almost exactly the example above: check whether a path is a symlink, then open it without O_NOFOLLOW, and an attacker swaps a real file for a symlink in the gap. The textbook bug, still landing in real tools thirty years on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=774ff95a8c95" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-bug-that-lives-in-the-gap-toctou-774ff95a8c95">The Bug That Lives in the Gap. TOCTOU</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Outbox Pattern: Never Lose an Event Again]]></title>
            <link>https://blog.stackademic.com/the-outbox-pattern-never-lose-an-event-again-ab2c11e1875d?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab2c11e1875d</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[events]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Mon, 17 Nov 2025 09:15:11 GMT</pubDate>
            <atom:updated>2025-12-02T06:15:02.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Aimc_F5Y8hQqihkN" /><figcaption>Photo by <a href="https://unsplash.com/@sergeyuxui?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sergey Beschastnykh</a> on <a href="https://unsplash.com/photos/a-man-riding-a-motorcycle-down-a-street-Vf4Wgp0vJdw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You’ve built this nice API. Clean separation of concerns, decoupled services, the works. When someone completes an order, you save it to the database and fire off an event, maybe to send them a confirmation email, update inventory, or kick off the shipping workflow.</p><p>Then one day, you’re looking through the logs and notice something odd. Orders are getting saved, but some of the confirmation emails never went out. You dig deeper. The database writes are fine, but now and then the event publish fails; network blip, message broker hiccup, doesn’t matter. What matters is you’ve got orders sitting in the database that nobody knows about.</p><p>This is the dual-write problem, and if you’ve been doing distributed systems for any amount of time, you’ve probably been bitten by it.</p><h3>Why Two Writes Are a Problem</h3><p>When you need to update your database AND publish an event, you’re doing two separate operations against two different systems. Here’s what can go wrong:</p><p><strong>Scenario 1: Database succeeds, event fails</strong></p><pre>✓ Order saved to database<br>✗ Event publish fails (network hiccup, broker&#39;s down, whatever)<br>Result: Order exists but nobody downstream ever hears about it</pre><p><strong>Scenario 2: Event succeeds, database fails</strong></p><pre>✓ Event published to message broker<br>✗ Database write fails (constraint violation, timeout, you name it)<br>Result: Downstream services start processing an order that doesn&#39;t actually exist</pre><p><strong>Scenario 3: The “did it work or not” nightmare</strong></p><pre>✓ Order saved to database<br>? Event publish (timeout, who knows what happened)<br>→ Retry? You might send duplicate events<br>→ Don&#39;t retry? You might miss the event entirely</pre><p>“Just use a transaction!” you say. Great idea, except your database transaction doesn’t extend to your message broker. They’re completely separate systems with their own transaction boundaries. You’re stuck.</p><h3>Enter the Outbox Pattern</h3><p>The outbox pattern fixes this by making event publishing part of the same database transaction as your actual data. Here’s the trick:</p><p><strong>Instead of this (asking for trouble):</strong></p><pre>1. Write order to database<br>2. Publish event to message broker</pre><p><strong>Do this:</strong></p><pre>1. Write order to database<br>2. Write event to an &quot;outbox&quot; table (same transaction!)<br>3. Have a separate background job read the outbox and publish events</pre><p>The insight here is simple: if you write both your business data and your event to the same database in a single transaction, you get atomicity for free. Either both write happens, or neither does. No more inconsistency.</p><h3>Visualising the Problem vs. Solution</h3><h3>❌ The Broken Way: Dual-Write</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*peho70LXXlFWb-FNeF5NGA.png" /></figure><p><strong>Problem</strong>: Two separate operations → anything can fail in between → drift.</p><h3>✅ The Safe Way: Outbox Pattern</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*U5acRKqDm1urcDCvXX3Mfw.png" /></figure><p><strong>Why this works</strong>: The DB write + outbox write happen together or not at all. Even if your service crashes, the outbox table still has the event. A worker will always retry until it’s sent.</p><h3>How It Works</h3><h3>Step 1: Create an Outbox Table</h3><pre>CREATE TABLE outbox_events (<br>    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>    aggregate_type VARCHAR(255) NOT NULL,<br>    aggregate_id VARCHAR(255) NOT NULL,<br>    event_type VARCHAR(255) NOT NULL,<br>    payload JSONB NOT NULL,<br>    sent BOOLEAN DEFAULT FALSE,<br>    created_at TIMESTAMP DEFAULT NOW(),<br>    sent_at TIMESTAMP NULL<br>);<br>CREATE INDEX idx_outbox_unsent ON outbox_events(sent, created_at) WHERE sent = FALSE;</pre><h3>Step 2: Write Business Data and Events Together</h3><pre>import { Pool } from &#39;pg&#39;;<br>import { v4 as uuid } from &#39;uuid&#39;;<br>const pool = new Pool({<br>  host: process.env.DB_HOST,<br>  database: process.env.DB_NAME,<br>  user: process.env.DB_USER,<br>  password: process.env.DB_PASSWORD,<br>});<br>async function completeOrder(orderId, userId) {<br>  const client = await pool.connect();<br>  <br>  try {<br>    await client.query(&#39;BEGIN&#39;);<br>    <br>    // Update business data<br>    const orderResult = await client.query(<br>      `UPDATE orders <br>       SET status = &#39;COMPLETED&#39;, completed_at = NOW() <br>       WHERE id = $1 <br>       RETURNING *`,<br>      [orderId]<br>    );<br>    <br>    const order = orderResult.rows[0];<br>    <br>    // Write event to outbox (same transaction!)<br>    await client.query(<br>      `INSERT INTO outbox_events (<br>        id, aggregate_type, aggregate_id, event_type, payload<br>      ) VALUES ($1, $2, $3, $4, $5)`,<br>      [<br>        uuid(),<br>        &#39;Order&#39;,<br>        orderId,<br>        &#39;OrderCompleted&#39;,<br>        JSON.stringify({<br>          orderId: orderId,<br>          userId: userId,<br>          total: order.total,<br>          completedAt: order.completed_at,<br>        }),<br>      ]<br>    );<br>    <br>    await client.query(&#39;COMMIT&#39;);<br>    <br>    // Transaction commits atomically<br>    // Both writes succeed or both fail<br>    <br>  } catch (error) {<br>    await client.query(&#39;ROLLBACK&#39;);<br>    throw error;<br>  } finally {<br>    client.release();<br>  }<br>}</pre><h3>Step 3: Publish Events Asynchronously</h3><p>A separate process (often called a “relay” or “publisher”) polls the outbox table and publishes pending events:</p><pre>import { SNSClient, PublishCommand } from &#39;@aws-sdk/client-sns&#39;;<br>const sns = new SNSClient({ region: &#39;us-east-1&#39; });<br>const TOPIC_ARN = process.env.ORDER_TOPIC_ARN;<br>async function publishEventToSNS(event) {<br>  const message = JSON.stringify({<br>    id: event.id,<br>    type: event.event_type,<br>    payload: event.payload,<br>    createdAt: event.created_at,<br>  });<br>  await sns.send(new PublishCommand({<br>    TopicArn: TOPIC_ARN,<br>    Message: message,<br>    MessageAttributes: {<br>      eventType: {<br>        DataType: &#39;String&#39;,<br>        StringValue: event.event_type,<br>      },<br>    },<br>  }));<br>}<br>async function processOutbox() {<br>  const client = await pool.connect();<br>  <br>  try {<br>    // Fetch unprocessed events<br>    const result = await client.query(<br>      `SELECT * FROM outbox_events <br>       WHERE sent = FALSE <br>       ORDER BY created_at <br>       LIMIT 100`<br>    );<br>    <br>    for (const event of result.rows) {<br>      try {<br>        // Publish to message broker<br>        await publishEventToSNS(event);<br>        <br>        // Mark as processed<br>        await client.query(<br>          `UPDATE outbox_events <br>           SET sent = TRUE, sent_at = NOW() <br>           WHERE id = $1`,<br>          [event.id]<br>        );<br>        <br>      } catch (error) {<br>        console.error(`Failed to publish event ${event.id}:`, error);<br>        // Will retry on next poll<br>      }<br>    }<br>    <br>  } finally {<br>    client.release();<br>  }<br>}<br>// Run every 5 seconds<br>setInterval(processOutbox, 5000);</pre><h3>What You Get Out of This</h3><p><strong>You won’t lose events anymore.</strong> Once an event is in that outbox table, it’s there. If publishing fails, no problem, it’ll just retry until it works.</p><p><strong>Your writes are actually atomic.</strong> Your business logic and event recording happen in one shot. No more “well, half of it worked.”</p><p><strong>Publishing is somebody else’s problem.</strong> Your business logic doesn’t care about SNS being down or Kafka having a bad day. That’s the background job’s headache now. You can upgrade it, scale it, or swap it out without touching your API code.</p><p><strong>You get an audit trail for free.</strong> Every event that has ever happened is sitting right there in your database with timestamps. Great for debugging, compliance, or just figuring out what the hell happened last Tuesday.</p><h3>Real-World Implementation Variants</h3><p>The core pattern stays the same, but you can adapt it to different message brokers and cloud services. Here’s the basic approach with SNS:</p><h3>Publishing to Your Message Broker</h3><pre>import { SNSClient, PublishCommand } from &#39;@aws-sdk/client-sns&#39;;<br>const sns = new SNSClient({ region: &#39;us-east-1&#39; });<br>const TOPIC_ARN = process.env.ORDER_TOPIC_ARN;<br>async function publishEventToSNS(event) {<br>  const message = JSON.stringify({<br>    id: event.id,<br>    type: event.event_type,<br>    payload: event.payload,<br>    createdAt: event.created_at,<br>  });<br>  await sns.send(new PublishCommand({<br>    TopicArn: TOPIC_ARN,<br>    Message: message,<br>    MessageAttributes: {<br>      eventType: {<br>        DataType: &#39;String&#39;,<br>        StringValue: event.event_type,<br>      },<br>    },<br>  }));<br>}</pre><p><strong>Using something else?</strong> The pattern is identical, just swap the client library:</p><ul><li><strong>SQS</strong>: Use SendMessageCommand instead of PublishCommand</li><li><strong>Kafka</strong>: Use kafkajs producer with producer.send()</li><li><strong>EventBridge</strong>: Use PutEventsCommand</li><li><strong>RabbitMQ</strong>: Use amqplib with channel.publish()</li></ul><p>The outbox table and worker logic stay exactly the same.</p><h3>Serverless with AWS Lambda</h3><p>Instead of a continuously running worker, trigger a Lambda function on a schedule (every 1–5 minutes via EventBridge). The logic is identical to the polling example above. Just fetch unsent events, publish them, and mark them as sent. The scheduled trigger replaces the setInterval.</p><h3>DynamoDB with Streams (No Polling Needed)</h3><p>With DynamoDB Streams, you can skip the polling entirely. Every write to your DynamoDB table automatically appears in a stream, and you can trigger a Lambda to process those changes. It’s like having a built-in outbox where the database itself tells you about changes.</p><p>The trade-off: you lose the explicit outbox table (so no easy way to see pending events), but you gain lower latency and simpler architecture. Works great if you’re already on DynamoDB.</p><h3>Handling Idempotency (Critical!)</h3><p>The outbox pattern retries failed events, which means consumers might receive the same event multiple times. Your consumers <strong>must be idempotent</strong>.</p><h3>Track Processed Events</h3><pre>CREATE TABLE processed_events (<br>  id UUID PRIMARY KEY,<br>  processed_at TIMESTAMP DEFAULT NOW()<br>);<br><br>CREATE INDEX idx_processed_events_time ON processed_events(processed_at);</pre><h3>Idempotent Consumer Pattern</h3><pre>async function handleOrderCompleted(event) {<br>  const client = await pool.connect();<br>  <br>  try {<br>    await client.query(&#39;BEGIN&#39;);<br>    <br>    // 1. Check if we&#39;ve already processed this event<br>    const checkResult = await client.query(<br>      &#39;SELECT 1 FROM processed_events WHERE id = $1&#39;,<br>      [event.id]<br>    );<br>    <br>    if (checkResult.rowCount &gt; 0) {<br>      await client.query(&#39;ROLLBACK&#39;);<br>      console.log(`Event ${event.id} already processed, skipping`);<br>      return; // Already handled<br>    }<br>    <br>    // 2. Apply business logic<br>    await client.query(<br>      `INSERT INTO order_read_model (order_id, customer_id, amount, status)<br>       VALUES ($1, $2, $3, $4)<br>       ON CONFLICT (order_id) DO UPDATE SET status = EXCLUDED.status`,<br>      [<br>        event.payload.orderId,<br>        event.payload.customerId,<br>        event.payload.amount,<br>        &#39;completed&#39;<br>      ]<br>    );<br>    <br>    // 3. Mark event as processed<br>    await client.query(<br>      &#39;INSERT INTO processed_events (id) VALUES ($1)&#39;,<br>      [event.id]<br>    );<br>    <br>    await client.query(&#39;COMMIT&#39;);<br>    <br>  } catch (error) {<br>    await client.query(&#39;ROLLBACK&#39;);<br>    throw error;<br>  } finally {<br>    client.release();<br>  }<br>}</pre><p>Now, even if the same event is delivered 10 times, the side effects only happen once.</p><h3>Things That Can Bite You</h3><h3>You’ll Get Duplicate Events</h3><p>Here’s a fun one: your publisher sends an event to SNS, then crashes before it can mark the event as processed. Next time it runs, it sees that same event and sends it again. Congrats, you just double-charged someone.</p><p><strong>The fix:</strong> Make your consumers idempotent. They need to handle getting the same event twice without doing the work twice. See the “Handling Idempotency” section. This is non-negotiable.</p><h3>Your Outbox Table Will Get Huge</h3><p>Processed events just sit there forever unless you do something about them. Give it a few months, and you’re looking at millions of rows you don’t need anymore.</p><p><strong>The fix:</strong> Run a cleanup job. Delete or archive old events on a schedule:</p><pre>async function cleanupOutbox() {<br>  const sevenDaysAgo = new Date();<br>  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);<br>  <br>  const result = await pool.query(<br>    `DELETE FROM outbox_events <br>     WHERE sent = TRUE <br>     AND sent_at &lt; $1`,<br>    [sevenDaysAgo]<br>  );<br>  <br>  console.log(`Cleaned up ${result.rowCount} old events`);<br>}<br>// Run daily<br>setInterval(cleanupOutbox, 24 * 60 * 60 * 1000);</pre><h3>Event Ordering Might Get Weird</h3><p>If you’ve got multiple publisher instances running, there’s no guarantee events get published in the exact order they were created. Sometimes that matters, sometimes it doesn’t.</p><p><strong>The fix:</strong></p><ul><li>Partition events by aggregate_id So the same publisher always handles the same aggregate&#39;s events</li><li>Use a message broker that guarantees ordering within a partition (Kafka or SQS FIFO)</li><li>Add sequence numbers to your events</li><li>Query your outbox with ORDER BY created_at, id to at least try to maintain order</li></ul><h3>Your Publisher Might Fall Behind</h3><p>During a traffic spike, events get written faster than your publisher can handle them. Now you’ve got a backlog, and events are delayed.</p><p><strong>The fix:</strong></p><ul><li>Watch your metrics. If the outbox is growing, you’ve got a problem</li><li>Run multiple publisher instances with partitioning</li><li>Batch your publishes — send 50 events at once instead of one at a time</li><li>Speed up your polling interval when you detect lag</li></ul><h3>The Failure Flow: Where Outbox Protects You</h3><p>Let’s see exactly what happens when things go wrong:</p><h3>❌ Without Outbox (Danger Zone)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*tWNEEVLQSLalN3dp8AD5cw.png" /></figure><pre>Result:<br>- DB says &quot;order created&quot;<br>- No event was ever sent<br>- Downstream systems never see the order</pre><p>You now have an inconsistent reality. The order exists but no one was notified. Your email service never sent a confirmation. Your inventory service never decremented stock. Your shipping service never scheduled a delivery.</p><h3>✅ With Outbox (Protected)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeYQbZImwwzlWy-jHmk-Yw.png" /></figure><p><strong>Key insight</strong>: The outbox row sitting in the database is your buffer. As long as it exists with sent = false, the system keeps trying. The event <strong>will eventually be delivered</strong>, even if it takes minutes, hours, or until the broker comes back online.</p><h3>Real-World Considerations</h3><p><strong>Polling vs. Change Data Capture (CDC)</strong></p><p>Instead of polling, you can use CDC tools like Debezium to watch the outbox table and automatically publish events. This reduces lag and database load but adds complexity.</p><p><strong>Message Ordering</strong></p><p>If strict ordering matters, include a sequence number in your events and ensure consumers process them in order.</p><p><strong>Schema Evolution</strong></p><p>Store events in a flexible format (like JSON) and version your event schemas. Consumers should handle both old and new versions.</p><h3>Performance Considerations</h3><h3>The Latency Trade-off</h3><p>Here’s the deal: with the outbox pattern, there’s a small gap between when you write data and when the event actually gets published. We’re talking seconds here; it depends on how often your worker polls or how fast your stream processes.</p><p><strong>What you’re looking at:</strong></p><ul><li>Polling every 5 seconds: anywhere from 0–5 seconds delay</li><li>DynamoDB Streams: usually under a second</li><li>Change Data Capture tools: usually under a second</li></ul><p>For most stuff, this is completely fine. Your customer isn’t going to notice if their order confirmation email shows up 3 seconds after checkout instead of instantly. But if you’re building something that needs real-time updates — like a live dashboard or anything involving high-frequency trading — you might need a different approach.</p><h3>Database Overhead (It’s Not Bad)</h3><p>Each event adds one row to your outbox table. That’s it. The overhead is pretty minimal:</p><ul><li>One extra INSERT in the same transaction (fast)</li><li>Index maintenance on the sent column</li><li>Cleanup jobs running periodically</li></ul><p><strong>Ways to keep it fast:</strong></p><ul><li>Use partial indexes: CREATE INDEX idx_outbox_unsent ON outbox_events(created_at) WHERE sent = FALSE;</li><li>Batch your publishes — grab 50–100 events at once instead of one at a time</li><li>If you’re really hammering it, partition the outbox table by date</li><li>Archive old events to S3 or something instead of deleting if you need them for compliance</li></ul><h3>Scaling</h3><p>The outbox pattern actually scales pretty well:</p><ul><li><strong>Horizontal</strong>: Run multiple publisher workers, each handling different aggregates</li><li><strong>Vertical</strong>: Your database does the heavy lifting, and databases are good at that</li><li><strong>Message broker</strong>: The actual publishing goes to systems built for high throughput (Kafka, SNS, etc.)</li></ul><h3>Security Stuff You Need to Think About</h3><p>Your outbox table has the same data as your events, which means it might have sensitive stuff in it.</p><p><strong>Treat it like real production data:</strong></p><ul><li>Encrypt it at rest, just like your other tables</li><li>Use SSL/TLS for your worker’s database connection</li><li>Lock down access, only the services that need it should be able to touch it</li><li>If you’re storing credit card numbers or SSNs in the payload, consider field-level encryption (AES-256-GCM works well)</li></ul><p><strong>Don’t keep data forever:</strong></p><ul><li>If there’s PII in those events, don’t just let them pile up forever</li><li>Set up cleanup policies that match your compliance requirements (GDPR says hi)</li><li>If you need audit trails for years, move old events to cold storage with proper access controls</li></ul><p>Only encrypt sensitive payloads if you’re dealing with actually sensitive data, credit cards, health records, that sort of thing. For most business events (order placed, item shipped), standard database encryption at rest is fine.</p><h3>When You Actually Need This</h3><p><strong>Use the outbox pattern when:</strong></p><ul><li>Missing an event would cause real problems. lost money, angry customers, and data drift</li><li>You’re coordinating multiple services that absolutely need to stay in sync</li><li>You need a record of everything that happened (audit trail, debugging, compliance)</li><li>You’re doing event-driven architecture, and events are a first-class citizen in your system</li></ul><p><strong>Skip it when:</strong></p><ul><li>You’re just tracking analytics or user activity, and losing the occasional event is fine</li><li>You’re building a simple CRUD app that doesn’t have a distributed architecture</li><li>The event is a nice-to-have, not a must-have (like “user viewed this page”)</li><li>You need instant event delivery (sub-second) and can’t tolerate any lag</li><li>You’re dealing with absolutely massive throughput, where even one extra write per event matters</li></ul><p><strong>Real talk: when is this overkill?</strong></p><p>If you’re sending a welcome email after signup, and it’s not the end of the world if 1 in 10,000 gets lost, just publish the event directly. Don’t overthink it. The outbox pattern means you’re managing another table, running background jobs, monitoring lag, and doing cleanup. That’s operational overhead.</p><p>But here’s the thing for anything involving money, inventory, customer orders, or critical business workflows, the outbox pattern should be your default. Yeah, it’s more code. Yeah, it’s more complex. But you’ll sleep better at night.</p><h3>To Conclude</h3><p>Look, the outbox pattern isn’t sexy. It’s not going to impress anyone at a conference. But it’s one of those things that separates systems that work from systems that kind of work most of the time.</p><p>It solves the dual-write problem by putting everything under one transaction. Yeah, you’ve got to manage an extra table. Yeah, you need a background job running. Yeah, there’s monitoring and cleanup to think about. And yeah, your events show up a few seconds late instead of instantly.</p><p>But what you get in return is pretty great: events that actually get delivered, no more half-finished writes, and consistency between your database and event stream. These aren’t easy things to get otherwise.</p><p><strong>Bottom line:</strong> If you’re dealing with anything where missing or duplicating an event would suck, orders, payments, inventory, anything involving money. Just use the outbox pattern. It’s the right default. The extra complexity is worth not getting paged at 3 AM because your systems drifted out of sync.</p><p>For stuff that doesn’t matter as much, analytics, activity tracking, “user looked at this page” events, you can probably just publish directly and move on with your life.</p><p>Next time you’re about to write to a database and publish an event, stop for a second. Ask yourself: what happens if one works and the other doesn’t? If that question makes you nervous, you know what to do.</p><p><strong>Want to go deeper?</strong></p><ul><li><strong>Event Sourcing</strong>: Store all state changes as events (takes this pattern even further)</li><li><strong>Saga Pattern</strong>: Coordinate long-running transactions across multiple services</li><li><strong>Change Data Capture (CDC)</strong>: Tools like Debezium that watch your database and stream changes in real-time</li><li><strong>Transactional Outbox with CDC</strong>: Combine both for even lower latency</li></ul><h3>Recommended Reading</h3><p>If you want to understand distributed systems and event-driven architecture properly, these books are worth your time:</p><p><a href="https://dataintensive.net/"><strong>Designing Data-Intensive Applications</strong></a><strong> by Martin Kleppmann</strong><br>The bible of distributed systems. Chapter 11 covers stream processing and exactly this kind of problem. If you only read one book on distributed systems, make it this one.</p><p><a href="https://www.oreilly.com/library/view/building-event-driven-microservices/9781492057888/"><strong>Building Event-Driven Microservices</strong></a><strong> by Adam Bellemare</strong><br> Practical guide to event-driven architecture. Covers the outbox pattern and other event sourcing patterns in detail, with real-world examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab2c11e1875d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-outbox-pattern-never-lose-an-event-again-ab2c11e1875d">The Outbox Pattern: Never Lose an Event Again</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Think TfL’s Contactless Payment System Really Works]]></title>
            <link>https://blog.stackademic.com/how-i-think-tfls-contactless-payment-system-really-works-cb24fd5a9810?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb24fd5a9810</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[payment-processing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 06:50:25 GMT</pubDate>
            <atom:updated>2025-08-26T08:41:20.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dy1Fj_oNirEqsQsWIZZBFQ.jpeg" /><figcaption>“In the Midst of Chaos” — Photo by <a href="https://www.instagram.com/framespective/">Framespective</a></figcaption></figure><p>You tap your card on a London Underground barrier, hear a satisfying beep, and the gate swings open in milliseconds. Hours later, after multiple journeys across buses and tubes, a single charge appears on your bank statement. As someone who uses the Underground daily, I’ve become fascinated by this seemingly seamless process.</p><p>How does Transport for London (TfL) make this feel so effortless when payment systems are notoriously complex and slow? Based on my observations as a regular user and my background in system design, the answer lies in brilliant architecture that separates access control from payment processing.</p><p><strong>Disclaimer: </strong>This analysis is based on user observations and system design principles. I don’t have insider knowledge of TfL’s actual implementation; these are educated assumptions about how I think such a system would need to work to deliver the experience we see.</p><h3>Speed vs Reliability</h3><p>Traditional payment systems require real-time authorisation from your bank. Even modern contactless payments at shops take 2–3 seconds to process. But imagine if every London commuter had to wait 3 seconds at each barrier during rush hour, the system would collapse under its own success.</p><p>TfL handles over 5 million contactless transactions daily across 270+ stations and 8,000+ buses. They needed to solve the fundamental tension between speed (gates must open instantly) and reliability (everyone must be charged correctly).</p><p>I believe their solution is elegant: don’t try to charge people in real-time at all.</p><h3>What Actually Happens</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nH4GdHeuNrUfc8AbV_5nOA.png" /></figure><p>When you tap your contactless card, you’re not making a payment. You’re checking into TfL’s system, like scanning a loyalty card at a coffee shop. The actual payment happens hours later, after TfL has figured out exactly what you owe.</p><h3>The Big Picture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fs3nJOtlPMnsQxN_poaqPA.png" /></figure><p>Based on my observations and understanding of distributed systems, I think this architecture separates the system into three distinct layers:</p><p><strong>Edge Layer (Gates/Readers)</strong>: Fast, offline-capable decision making <strong>Processing Layer (TfL Backend)</strong>: Journey reconstruction and fare calculation<br> <strong>Settlement Layer (Payment Networks)</strong>: Bank transactions and risk management</p><h3>Key System Design Principles</h3><h3>1. Separation of Concerns</h3><p>What fascinates me most is what I believe is the most crucial design decision: separating <strong>access control</strong> from <strong>billing</strong>.</p><ul><li><strong>Access control</strong>: “Is this a valid payment card that should be allowed through?”</li><li><strong>Billing</strong>: “How much should this person be charged based on their journeys?”</li></ul><p>By handling these concerns separately, TfL can optimise each for different requirements. Access control needs to be fast and work offline. Billing can be slow, complex, and eventually consistent.</p><h3>2. Event-Driven Architecture</h3><p>Every tap generates an event that flows through the system:</p><pre>Tap Event: {<br>  cardToken: &quot;abc123...&quot;,<br>  location: &quot;King&#39;s Cross St Pancras&quot;,<br>  timestamp: &quot;2024-08-25T08:30:15Z&quot;,<br>  readerID: &quot;KCSP_NB_001&quot;,<br>  direction: &quot;entry&quot;<br>}</pre><p>These events stream into TfL’s backend systems, where they’re processed asynchronously to reconstruct complete journeys.</p><h3>3. Offline-First Design</h3><p>Gate readers must work even when network connectivity is poor. They maintain:</p><ul><li><strong>Hotlist cache</strong>: Known bad/blocked cards</li><li><strong>Validation logic</strong>: Basic EMV contactless checks</li><li><strong>Local storage</strong>: Events queued for later transmission</li></ul><p>This ensures that a network outage doesn’t shut down the entire transport system.</p><h3>4. Batch Processing and Aggregation</h3><p>Instead of charging you £2.80 for each bus ride separately, TfL:</p><ol><li>Collects all your day’s journeys</li><li>Applies complex fare rules (zones, caps, discounts)</li><li>Submits a single charge to your bank</li></ol><p>This dramatically reduces transaction volume and enables sophisticated pricing like daily and weekly caps.</p><h3>5. Eventually Consistent Charging</h3><p>TfL’s system embraces eventual consistency. You might travel all day and not see a charge for 24–48 hours. This is by design; accuracy matters more than immediacy for billing.</p><h3>What Happens During a Tap</h3><p>Let’s trace a single tap through the entire system:</p><h3>Step 1: The Tap (0–300ms)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6xQaET5LP3D06UrbEhZkg.png" /></figure><p>The reader likely doesn’t need to wait for full authorisation from your bank but whether there’s <em>no</em> contact at all is something I’m not certain about. Based on what I understand about transit systems, processing a payment card at the entry gate must be completed in under 400 milliseconds, which cannot be achieved via online authorisation in the traditional sense. I hypothesise that TfL uses EMV offline authentication to verify the card is genuine, possibly with some minimal real-time validation, but defers the actual payment authorisation until later.</p><h3>Step 2: Event Ingestion (1–10 minutes)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Cr_vFNLsompOURxDFFMQw.png" /></figure><p>Events are batched and uploaded periodically to handle network latency and reduce overhead.</p><h3>Step 3: Journey Reconstruction (hourly)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmFi9RzmIc1tD4_NyD9Cmw.png" /></figure><p>This is where I believe TfL’s fare calculation engine shines, handling complex zone boundaries and journey types.</p><h3>Step 4: Daily Aggregation (overnight)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGT1d_Fy4E-clwlxzEXtUA.png" /></figure><h3>Step 5: Payment Settlement (24–48 hours after travel)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fLsjwft8ZGWDzZqV78Hd1g.png" /></figure><p>The numbers behind TfL’s system are staggering, and each one represents a significant engineering challenge that I believe required careful architectural decisions.</p><h3>The Volume Problem</h3><p>During morning rush hour at King’s Cross St. Pancras, I’ve watched hundreds of people stream through the barriers in minutes. If my estimates are correct, TfL might be processing Tens of thousands of taps per minute across the entire network during peak times. That’s not just a database problem, it’s a distributed systems nightmare.</p><p>Think about what happens when someone taps: the gate reader needs to make a decision in under 400ms, log the event, and coordinate with dozens of other readers in the same station. Multiply this by 270+ stations, and you have thousands of independent devices all generating events simultaneously.</p><p>I guess that TfL solved this through what I’d call “edge intelligence”, pushing processing power out to the gate readers themselves rather than centralising everything. Each reader probably maintains its own local database of recent transactions and blocked cards, syncing periodically with the central system. This way, a network hiccup doesn’t shut down an entire station.</p><p>For the backend systems, I imagine they use database partitioning strategies, likely by card token and date. When you tap your card, the system probably routes your transaction to a specific database shard based on your card’s identifier. This means the system can scale horizontally by adding more database nodes rather than trying to make one massive database handle everything.</p><h3>When Things Go Wrong</h3><p>What I find equally compelling is how the system handles failure. London’s transport network can’t just “go down for maintenance” during rush hour. The system needs to gracefully degrade rather than fail.</p><p>I suspect TfL uses circuit breaker patterns throughout its architecture. When the central fare calculation system is overloaded, gate readers might fall back to basic validation, letting people through based on cached card information rather than risking system-wide failures. It’s better to let a few questionable transactions through than to trap thousands of commuters in stations.</p><p>The monitoring requirements must be intense. I imagine TfL has real-time dashboards showing tap success rates across every station, with alerts firing when certain thresholds are crossed. They probably track metrics like “percentage of taps resolved in under 300ms” and “number of incomplete journeys per hour”, operational metrics that directly impact the passenger experience.</p><h3>The Fraud Balancing Act</h3><p>Perhaps the most interesting challenge is risk management. TfL needs to prevent fraud without making the system unusable. This requires what I think of as “smart blocking”, being aggressive enough to stop genuine fraud while avoiding false positives that would strand legitimate travellers.</p><p>The card blocking logic probably considers multiple factors: payment failures (maybe your bank account is empty), velocity patterns (did this card just tap in at Oxford Circus and then immediately at Heathrow, physically impossible), and historical behaviour. But the system can’t be too aggressive; blocking someone’s card during their commute would be a customer service disaster.</p><p>What’s clever is the recovery process I’ve observed. I’ve seen cards that were declined get automatically unblocked after a successful payment attempt. This suggests TfL’s system is constantly re-evaluating risk rather than permanently blocking cards based on single incidents.</p><p>The system also needs to handle edge cases: what happens when someone’s card expires mid-journey? How do you handle chargebacks from bank customers who dispute TfL charges weeks later? Each of these scenarios requires a careful balance between operational efficiency and customer experience.</p><h3>Why It Feels So Reliable</h3><p>The system’s reliability comes from several factors:</p><p><strong>Redundancy at every level</strong>: From gate readers to data centres to payment processors</p><p><strong>Graceful degradation</strong>: When components fail, the system continues operating with reduced functionality rather than complete failure</p><p><strong>Offline capability</strong>: Critical functions work without network connectivity</p><p><strong>Eventual consistency</strong>: Temporary inconsistencies are acceptable as long as they resolve correctly</p><p><strong>User experience priority</strong>: The system is designed around “let people travel first, figure out payment later”</p><h3>Lessons for System Design</h3><p>TfL’s contactless system demonstrates several crucial principles for large-scale systems:</p><ol><li><strong>Optimise for the critical path</strong>: Make the user-facing interaction as fast as possible by deferring complex processing</li><li><strong>Embrace eventual consistency</strong>: Perfect real-time consistency isn’t always necessary if eventual accuracy is guaranteed</li><li><strong>Design for failure</strong>: Assume network partitions, server failures, and external service outages will happen</li><li><strong>Separate concerns clearly</strong>: Different parts of your system can have different performance and consistency requirements</li><li><strong>Batch when possible</strong>: Aggregating operations reduces load and enables more sophisticated processing</li></ol><h3>Conclusion</h3><p>Next time you tap through a TfL barrier, remember that you’re likely interacting with one of London’s most sophisticated distributed systems. Behind that simple beep is what I believe to be a masterclass in system design: event-driven architecture, offline-first thinking, and the elegant separation of access control from payment processing.</p><p>The magic isn’t necessarily in the technology itself; it’s in understanding what trade-offs to make. I hypothesise that TfL chose to optimise for user experience and system reliability over real-time financial accuracy. The result is a system that feels effortless for millions of daily users while handling the complexity of modern payment networks behind the scenes.</p><p>Every time I use the Underground, I’m reminded that sometimes the best user experience comes from understanding what users actually need: fast, reliable access to transport, with accurate billing that happens transparently in the background. Whether my analysis is exactly right or not, the principles behind what I observe, prioritising the critical user path, embracing eventual consistency, and designing for failure are what make great distributed systems.</p><p>That’s what I call real engineering magic.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb24fd5a9810" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-i-think-tfls-contactless-payment-system-really-works-cb24fd5a9810">How I Think TfL’s Contactless Payment System Really Works</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Network All Around Us]]></title>
            <link>https://blog.stackademic.com/the-network-all-around-us-52a233f11830?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a233f11830</guid>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 06:55:26 GMT</pubDate>
            <atom:updated>2025-06-30T09:55:15.580Z</atom:updated>
            <content:encoded><![CDATA[<p>Why Everyone Should Understand the Digital Highways We Travel Every Day</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHayS_vNQsW2y-vj912TRg@2x.jpeg" /></figure><p>Last Saturday, I was cycling through the local trail when I struck up a conversation with a group of fellow riders taking a water break. As conversations do, it meandered from the weather to weekend plans, and eventually to what we all did for work. When I mentioned I’m a backend engineer at a networking company, their eyes lit up with that familiar mix of curiosity and bewilderment.</p><p>“So you work with computers and the internet?” one asked.</p><p>“Something like that,” I replied. Now, I’m no networking expert, I just took a few networking modules during my computer science degree, but I found myself trying to explain how networks power everything from their smartphone GPS tracking our route to the weather app they’d just checked. What struck me wasn’t their polite interest, but their genuine surprise when I mentioned that we’re constantly surrounded by dozens of networks working in harmony just to make their morning bike ride possible.</p><p>That conversation got me thinking: in an age where we’re more connected than ever, most people have little understanding of the invisible infrastructure that makes our digital lives possible. It’s like driving on highways every day without knowing what lanes, traffic lights, or road signs do.</p><p>And honestly? I’m still learning about networks myself. But the basics I picked up in college have been surprisingly useful in everyday life, and I think everyone could benefit from understanding at least the fundamentals: not just fixing WiFi, but understanding how our entire digital world works.</p><h3>The Journey of a Single Click</h3><p>Right now, as you read this article, you’re participating in one of humanity’s greatest collaborative achievements. But let’s trace what happened when you clicked to open this page.</p><h3>What Happens When You Visit Your Favourite Website</h3><p>Ever wonder what’s happening in those few seconds between clicking a link and seeing a webpage load? Let’s break down the journey your request takes: it’s more complex and fascinating than you might think.</p><p><strong>Step 1: DNS Lookup Finding the Address.</strong> Your click triggered your device to ask, “Where is Medium.com?” This question went to a DNS (Domain Name System) server, think of it as the internet’s phone book. That server responded with an IP address, essentially saying, “Medium lives at this numeric address: 162.159.152.4.”</p><p><strong>Step 2: The Route Planning.</strong> Your device now knows where to send the request, but it needs to figure out how to get there. This is where routing comes in. Your request gets packaged into small data packets, each tagged with the destination IP address.</p><p><strong>Step 3: The Journey Begins.</strong> These packets travel from your device to your router, then to your Internet Service Provider (ISP). From there, they might travel through fibre optic cables, undersea cables if you’re reading from another continent, or mobile towers if you’re on your phone.</p><p><strong>Step 4: Crossing Networks</strong> Here’s where it gets interesting: your packets don’t travel directly to Medium. They hop through multiple networks, each owned by different companies. A packet might go from your ISP to a regional network provider, then to an international backbone provider, then to Medium’s hosting provider. Each hop involves network equipment making split-second decisions about the best path forward.</p><p><strong>Step 5: Load Balancing</strong> When your packets finally reach Medium’s infrastructure, they don’t go to just one server. Load balancers distribute incoming requests across multiple servers to prevent any single machine from being overwhelmed. A server in Ireland may handle your request, while someone else’s request is directed to a server in Singapore.</p><p><strong>Step 6: The Database Dance.</strong> The server that received your request now needs to fetch this article. It queries databases that might be distributed across multiple data centres for redundancy. The text, images, and formatting information might come from different storage systems entirely.</p><p><strong>Step 7: The Journey Back</strong> Once the server has assembled your webpage, it packages the response into packets and sends them back through the same complex network journey in reverse. Your browser receives these packets, reassembles them, and renders the page you’re now reading.</p><p>This entire round trip (involving dozens of networks, multiple companies, and potentially thousands of miles) happened in milliseconds. That’s not magic; that’s engineering at scale.</p><h3>The Three Worlds of Networking</h3><p>To understand modern networks, you need to think about three distinct but interconnected environments:</p><p><strong>On-Premises Networks</strong>: These are the traditional networks inside offices and data centres. Companies still maintain their servers, databases, and internal systems. Think of your bank’s core systems or a hospital’s patient records; they often live on-premises for security and compliance reasons.</p><p><strong>Cloud Networks</strong>: This is where the action is happening now. Instead of owning physical servers, companies rent computing power from providers like AWS, Microsoft Azure, or Google Cloud. Your Netflix recommendations, your online banking, your email, most of this runs in the cloud.</p><p><strong>Hybrid Networks</strong>: The reality for most organisations. They keep some critical systems on-premises whilst moving others to the cloud, creating complex networks that span both worlds. A retail company might keep customer data in their own data centre while using cloud services for its website and mobile app.</p><h3>Why Network Architecture Matters to Everyone</h3><p>Here’s where it gets interesting for everyday users. The networking decisions companies make directly affect your experience:</p><p>When Zoom struggled during early COVID lockdowns, it wasn’t just about server capacity, it was about network architecture. They had to rapidly scale their network infrastructure across multiple cloud providers and regions to handle the sudden surge in traffic.</p><p>When your favourite app loads instantly in London but crawls in rural areas, that’s network design at work. Companies use Content Delivery Networks (CDNs) to place copies of their data closer to users. Netflix doesn’t stream your movie from one giant server in California; they store copies in data centres around the world.</p><p>When your online banking feels rock-solid while that new startup’s app keeps crashing, it’s often because established companies have invested in redundant network paths, load balancers that distribute traffic, and failover systems that kick in when something breaks.</p><h3>The Hidden Complexity of “Simple” Apps</h3><p>Let’s take something as basic as checking your bank balance on your phone. Here’s what’s happening behind the scenes:</p><ol><li><strong>Authentication</strong>: Your login request travels through multiple security layers, often hitting identity servers that verify who you are</li><li><strong>Load Balancing</strong>: Your request gets distributed to one of many servers to prevent any single server from being overwhelmed</li><li><strong>Database Queries</strong>: The server queries databases that might be spread across multiple data centres for redundancy</li><li><strong>API Calls</strong>: Your balance might come from one system, your recent transactions from another, your credit score from a third-party service</li><li><strong>Content Delivery</strong>: The app interface itself is likely served from a CDN to ensure fast loading</li><li><strong>Monitoring</strong>: Every step is monitored by network management systems, watching for performance issues or security threats</li></ol><p>Each of these steps involves network communication, often across different cloud providers and geographic regions. What feels like a simple app tap is a complex orchestration of network services.</p><h3>The Economics of Network Decisions</h3><p>Understanding networks helps you know why companies make certain choices that affect your experience as a user:</p><p><strong>Why do some services work better in certain regions?</strong> Network latency and infrastructure costs. It’s expensive to build fast network connections everywhere.</p><p><strong>Why do some apps require a constant internet connection while others work offline?</strong> Network architecture philosophy. Some companies build “cloud-first” applications that depend on server processing, while others design for “offline-first” functionality.</p><p><strong>Why do enterprise tools often feel clunky compared to consumer apps?</strong> Enterprise networks prioritise security and compliance over user experience, adding layers of authentication and monitoring that can slow things down.</p><p><strong>Why do some companies have more outages than others?</strong> Network resilience costs money. Building redundant systems across multiple cloud providers and regions is expensive, so companies make trade-offs based on their priorities and budgets.</p><h3>Security in a Networked World</h3><p>Every network connection is a potential entry point, and the complexity of modern networking creates new security challenges:</p><p>When you connect to public WiFi, you’re not just risking someone intercepting your personal browsing, you’re potentially exposing any business applications you access. Many companies now require VPNs (Virtual Private Networks) specifically because they can’t trust the networks their employees use.</p><p>When companies move to the cloud, they’re essentially trusting their data to networks they don’t control. This requires new approaches to security, like encrypting data not just when it’s stored, but while it’s travelling between systems.</p><p>The rise of remote work has forced companies to rethink network security entirely. The old model of a secure “corporate network” with a firewall around the perimeter doesn’t work when employees are connecting from coffee shops, home offices, and co-working spaces around the world.</p><h3>The Future Is Distributed</h3><p>We’re moving toward a world where the distinction between “local” and “remote” becomes meaningless:</p><p><strong>Edge Computing</strong>: Instead of sending all data to distant cloud servers, companies are placing computing power closer to where it’s needed. Your smart car processes some decisions locally, your smart city systems respond in real-time, and your AR glasses overlay information without waiting for the cloud.</p><p><strong>5G and Beyond</strong>: Faster mobile networks enable new applications that weren’t possible before. Remote surgery, autonomous vehicles, and real-time AI applications all depend on ultra-low latency networks.</p><p><strong>Mesh Networks</strong>: Traditional hierarchical networks are giving way to mesh architectures where devices can communicate directly with each other, creating more resilient and flexible systems.</p><h3>What This Means for You</h3><p>You don’t need to become a network engineer, but understanding these concepts helps you:</p><ul><li><strong>Make better technology choices</strong>: Understanding why certain apps work better than others, why some services cost more, why some solutions are more secure</li><li><strong>Navigate digital transformation</strong>: As your workplace adopts new tools and cloud services, understanding the networking implications helps you adapt faster</li><li><strong>Troubleshoot more effectively</strong>: When something breaks, you can think systematically about where the problem might be in the network chain</li><li><strong>Protect yourself better</strong>: Understanding how networks work helps you make smarter security decisions</li></ul><h3>Starting Your Network Journey</h3><p>The best way to learn networking is to start asking, “How does this actually work?” when you use digital services:</p><ul><li>When you video call someone on another continent, trace the path your voice might take</li><li>When you upload a photo to social media, think about where that photo gets stored and how it reaches your friends</li><li>When you stream a movie, consider how the service knows what quality to send you based on your network speed</li></ul><p>The rabbit holes are endless, but they’re fascinating rabbit holes that help you understand the digital world we’re all living in.</p><h3>The Trail Continues</h3><p>As I finished trying to explain all this to my fellow cyclists that Saturday (probably oversimplifying half of it), one of them pulled out her phone and said, “I never thought about how this GPS app knows where we are and can show real-time traffic.” She started asking about cell towers, satellite communication, and data privacy.</p><p>That’s the beauty of understanding networks; once you see the invisible infrastructure around us, you can’t unsee it. You start noticing the cell towers disguised as trees, appreciating the engineering marvel behind seamless video calls across continents, and making more informed decisions about the technology in your life.</p><p>In our hyperconnected world, network literacy isn’t just useful, it’s essential. Whether you’re choosing between cloud services, understanding why certain apps drain your battery, or simply wanting to comprehend the digital infrastructure that powers modern life, knowing networking basics makes you a more informed citizen of the internet age.</p><p>The trail of knowledge starts with curiosity. Why not follow it and see where it leads?</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a233f11830" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-network-all-around-us-52a233f11830">The Network All Around Us</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What code refactoring taught me about living smarter]]></title>
            <link>https://blog.stackademic.com/what-code-refactoring-taught-me-about-living-smarter-bd85bf55daef?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd85bf55daef</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Fri, 23 May 2025 07:44:09 GMT</pubDate>
            <atom:updated>2025-05-27T07:35:59.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NAVQzVQVuf2nn_c5" /><figcaption>Photo by <a href="https://unsplash.com/@meshushe?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Anya Chernik</a> on <a href="https://unsplash.com/photos/a-plastic-container-filled-with-lots-of-crafting-supplies-OZLtcdRVGIg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Refactoring code is like renovating a house whilst continuing to live in it. You’re improving structure, enhancing functionality, and making maintenance easier, all without changing what the house fundamentally is or does. As both our codebases and lives grow increasingly complex, the principles of pure refactoring become even more relevant.</p><h4>Improvement Without Change</h4><p>Pure refactoring is the art of improving code structure without altering its external behaviour. The code before and after refactoring should produce identical outputs given the same inputs, much like reorganising your kitchen. You’re not changing the meals you can cook, but rather making the cooking process more efficient.</p><p>Consider this breakfast preparation scenario:</p><p><strong>Before Refactoring:</strong></p><pre>function prepareBreakfast() {<br>  // Get eggs from the refrigerator<br>  const eggs = refrigerator.getItem(&#39;eggs&#39;);<br>  <br>  // Walk to the other side of the kitchen<br>  // Open the drawer where utensils are mixed together<br>  // Search through the drawer<br>  const whisk = findInMixedDrawer(&#39;whisk&#39;);<br>  <br>  // Walk back to the refrigerator<br>  // Get milk<br>  const milk = refrigerator.getItem(&#39;milk&#39;);<br>  <br>  // Walk to the cabinet where bowls are stored with decorative items<br>  const bowl = findInMixedCabinet(&#39;mixing bowl&#39;);<br>  <br>  // Mix ingredients and cook<br>  return cook(mix(eggs, milk, bowl, whisk));<br>}</pre><p><strong>After Refactoring:</strong></p><pre>function prepareBreakfast() {<br>  // Get all ingredients in one trip<br>  const ingredients = getBreakfastIngredients();<br>  <br>  // Get all tools in one trip<br>  const tools = getBreakfastTools();<br>  <br>  // Mix ingredients and cook<br>  return cook(mix(ingredients, tools));<br>}<br><br>function getBreakfastIngredients() {<br>  return {<br>    eggs: refrigerator.getItem(&#39;eggs&#39;),<br>    milk: refrigerator.getItem(&#39;milk&#39;)<br>  };<br>}<br><br>function getBreakfastTools() {<br>  return {<br>    whisk: cookingTools.get(&#39;whisk&#39;),<br>    bowl: bowls.get(&#39;mixing bowl&#39;)<br>  };<br>}</pre><p>In your kitchen, this means grouping similar items together, keeping frequently used items within easy reach, and organising based on workflow. The meals haven’t changed, but the process is now more efficient and less prone to errors.</p><h3><strong>Refactoring Techniques in Code and Life</strong></h3><h4>The Joy of Modular Living</h4><p>Just as good developers break down complex tasks into manageable subroutines, we can extract repetitive or complex pieces of code into their own functions:</p><pre>// Before<br>function processOrder(order) {<br>  let total = 0;<br>  for (const item of order.items) {<br>    total += item.price * item.quantity;<br>  }<br>  <br>  const tax = total * 0.08;<br>  const shipping = total &gt; 100 ? 0 : 10;<br>  const grandTotal = total + tax + shipping;<br>  <br>  return grandTotal;<br>}<br><br>// After<br>function processOrder(order) {<br>  const subtotal = calculateSubtotal(order.items);<br>  const tax = calculateTax(subtotal);<br>  const shipping = calculateShipping(subtotal);<br>  <br>  return subtotal + tax + shipping;<br>}<br><br>function calculateSubtotal(items) {<br>  let total = 0;<br>  for (const item of items) {<br>    total += item.price * item.quantity;<br>  }<br>  return total;<br>}<br><br>function calculateTax(amount) {<br>  return amount * 0.08;<br>}<br><br>function calculateShipping(subtotal) {<br>  return subtotal &gt; 100 ? 0 : 10;<br>}</pre><p>This is like meal prepping in real life. Instead of making individual meals from scratch each day, you prepare components ahead of time: chopped vegetables, cooked grains, and portioned proteins. The meal itself hasn’t changed, but the process has become more manageable, reusable, and less error-prone.</p><p>In AI systems, this principle is even more crucial, as large language models break down complex reasoning into smaller chunks, much like how we might decompose a difficult problem into simpler parts before solving it.</p><h4>The Power of Precise Language</h4><p>Both SWE and users thrive on clear communication. Renaming variables and functions to reflect their true purpose is perhaps the simplest yet most powerful refactoring technique:</p><pre>// Before<br>function calc(a, b) {<br>  return a * b;<br>}<br><br>// After<br>function calculateArea(width, height) {<br>  return width * height;<br>}</pre><p>In our homes, this is akin to replacing vague labels with specific ones. Rather than a box labelled “stuff”, you have boxes labelled “winter accessories”, “tax documents”, or “holiday decorations”. The contents stay the same, but they’re now easier to find and understand.</p><p>For software teams, clear naming is even more critical. When variables, functions and classes have descriptive names, debugging becomes easier and collaboration more effective just as clearer communication improves our human relationships.</p><h4>The Wisdom of Single Sources of Truth</h4><p>Repeated code is a liability. Change it once, and you must remember to change it everywhere. Similarly, well-designed systems benefit enormously from centralised knowledge representations:</p><pre>// Before<br>function validateUser(user) {<br>  if (!user.name) return false;<br>  if (!user.email) return false;<br>  if (!user.email.includes(&#39;@&#39;)) return false;<br>  return true;<br>}<br><br>function saveUser(user) {<br>  if (!user.name) return false;<br>  if (!user.email) return false;<br>  if (!user.email.includes(&#39;@&#39;)) return false;<br>  database.save(user);<br>  return true;<br>}<br><br>// After<br>function isValidUser(user) {<br>  if (!user.name) return false;<br>  if (!user.email) return false;<br>  if (!user.email.includes(&#39;@&#39;)) return false;<br>  return true;<br>}<br><br>function validateUser(user) {<br>  return isValidUser(user);<br>}<br><br>function saveUser(user) {<br>  if (!isValidUser(user)) return false;<br>  database.save(user);<br>  return true;<br>}</pre><p>In daily life, this is like maintaining a single “Home Departure Checklist” that everyone references: turn off appliances, lock doors, set thermostat. The process remains the same, but it’s maintained in one place.</p><p>Modern software architecture relies heavily on this principle through shared libraries and modular design. Rather than building separate systems for related tasks, they share foundational components and specialise only where necessary, much like how humans build on core knowledge when learning related skills.</p><h4>When to Refactor</h4><p>Just as applications need periodic optimisation, our code and lives occasionally need restructuring. Here are some signals that it’s time to refactor:</p><p><strong>Long Methods</strong>: Functions longer than a screen suggest too much responsibility in one place. In life, this manifests as overwhelming to-do lists that span multiple domains.</p><p><strong>Duplicated Logic</strong>: Finding yourself writing similar code in multiple places is a classic refactoring trigger. In life, repeatedly explaining the same information to different people suggests the need for a more efficient communication system.</p><p><strong>Complex Conditionals</strong>: Extensive if-else chains often indicate a need for refactoring. In daily routines, this might be overly complicated decision trees for handling recurring situations.</p><p><strong>Difficulty Onboarding</strong>: When new team members struggle to understand the codebase, refactoring can help. Similarly, if friends or family can’t easily adapt to your systems (where to find things, how processes work), it might be time to simplify.</p><p>For software systems, these signs have their parallels: excessive complexity that hampers maintainability, redundant code paths, and difficulty extending to new requirements are all indicators that architectural refactoring might be beneficial.</p><h4>The Refactoring Process</h4><p>Effective refactoring, whether in code or life, follows a disciplined approach:</p><p><strong>Take Small Steps</strong>: Make one change at a time, verify it works, then move on. In life, reorganise one cupboard before tackling the whole house; establish one new habit before overhauling your entire routine.</p><p><strong>Maintain Safety Nets</strong>: In code, automated tests provide confidence. In life, keeping a journal of changes and their effects allows you to “roll back” if needed.</p><p><strong>Version Control</strong>: Commit changes frequently with clear messages. Similarly, document life changes and their impact, creating waypoints you can return to if necessary.</p><p>Software development teams follow similar principles, gradual architecture modifications with continuous integration testing, maintaining benchmarks to ensure performance doesn’t regress, and versioning code to enable rollback if needed.</p><p>Pure refactoring, whether in code or life, isn’t about changing what you do but how you do it. It’s about creating cleaner structures, reducing complexity, and making future changes easier.</p><p>As our software continues to evolve, the principles of refactoring become even more important. The most elegant codebases, like the most fulfilling lives, are those that evolve thoughtfully, balancing urgency with intention, and short-term needs with long-term clarity.</p><p>Remember: Refactoring isn’t a one-time task, but an ongoing practice. It’s how we edit our lives. A continuous conversation between your past, present, and future self. Through this lens, code improvement becomes more than a technical skill — it’s a philosophy for designing resilience.</p><p>So the next time you feel overwhelmed, ask yourself: <em>“What’s the structure behind this chaos?”</em> Because sometimes, the best way forward isn’t to push harder… but to step back, and rearrange smarter.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd85bf55daef" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/what-code-refactoring-taught-me-about-living-smarter-bd85bf55daef">What code refactoring taught me about living smarter</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI/UX vs Backend: Who Should Lead the Dance?]]></title>
            <link>https://medium.com/codetodeploy/ui-ux-vs-backend-who-should-lead-the-dance-231b93feb18a?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/231b93feb18a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ux-design]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[design-thinking]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 16:33:39 GMT</pubDate>
            <atom:updated>2025-11-11T03:09:53.978Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AWIybiJCPrQmGQdH" /><figcaption>Photo by <a href="https://unsplash.com/@ardianlumi?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Ardian Lumi</a> on <a href="https://unsplash.com/photos/group-of-people-dancing-6Woj_wozqmA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>🌍 <strong>Top Remote Tech Roles Are Open Now!</strong><br> Frontend · Backend · Full Stack · Mobile · DevOps · AI · Design<br> 💰 Earn $50–$120/hr | Global Full-Time &amp; Contract Roles<br> ⏳ Don’t wait — early applicants get priority.</p><p>👉 <a href="https://app.usebraintrust.com/r/code6/"><strong>Apply Now</strong></a><strong> — Secure the Best Offers!</strong></p><p>It wasn’t a direct question but a thought that popped into my head over Tea.</p><p>I was chatting with a product designer who recently joined our team. Nothing deep, just shooting the breeze about our project, but something clicked in my brain. I started wondering about something I’d never really put into words before.</p><p>Does UI/UX drive backend, or does backend drive UI/UX?</p><p>Pretty basic question, but I couldn’t shake it.</p><h3>Two Ways of Looking at It</h3><p>There are basically two camps on this, with loads of middle ground in between:</p><h3>UI/UX First</h3><p>Some reckon the user experience should be the main priority. All the technical stuff, data structures, APIs, and server architecture are just there to make the user experience work. Their thinking goes:</p><ol><li>Users couldn’t care less about your fancy database design</li><li>Technical limitations come and go; what users need stays pretty constant</li><li>Even the most powerful backend is useless if people hate using it</li></ol><p>In its purest form, this means designing the perfect user experience first, then telling the engineers to figure out how to make it happen. It’s that “we’ll sort out the how later” attitude that’s behind some pretty revolutionary products.</p><p>Look at the original iPhone. Apple didn’t start by asking what was technically possible; they imagined how people should interact with mobile devices and then made the technology catch up.</p><h3>Backend First</h3><p>The opposite view says solid products need solid technical foundations. Interface design should work with what the system can actually do, not demand the impossible. The logic:</p><ol><li>Technical reality wins in the end</li><li>Systems that are fast and reliable create better experiences anyway</li><li>Working within constraints often leads to more creative solutions</li></ol><p>With this approach, the engineers establish what’s technically doable, efficient and scalable, then designers create the best experience within those boundaries.</p><p>Google’s search box is dead simple, but it’s designed around the realities of how their indexing and ranking algorithms actually work. The interface shows you what’s possible rather than driving what happens behind the scenes.</p><h3>It’s Not Really Either/Or</h3><p>After thinking about this for a while, I reckon framing it as an either/or question misses the point.</p><p>The best products usually come from that constant back-and-forth between design and engineering, just real conversations, not power struggles. It’s not about who calls the shots, but about both sides pushing each other, asking tough questions, and figuring out better ways to solve the problem together.</p><p>In teams that really innovate:</p><ul><li>UX designers get technical constraints but know when to push back</li><li>Engineers understand what users need and find clever ways to solve seemingly impossible design challenges</li><li>Both sides know they’re ultimately serving the user, not winning internal arguments</li></ul><h3>It’s a Dance, Not a Driver</h3><p>Maybe a better way to think about it is like dancing. In ballroom, partners take turns leading and following, responding to each other’s movements. Neither is always in charge; the relationship shifts and adapts.</p><p>Good product teams work the same way. Sometimes UX leads with a bold vision that challenges technical assumptions. Other times, engineering leads with new capabilities that open up design possibilities nobody had thought of.</p><p>What matters isn’t who leads most often, but how well the partners work together and what they create.</p><h3>What This Means Day-to-Day</h3><p>This way of thinking has real implications for how teams should work:</p><ol><li><strong>Start with problems, not solutions.</strong> Both designers and engineers should understand what users actually need before proposing interfaces or technical approaches.</li><li><strong>Prototype together.</strong> Get engineers involved in early design, and designers involved in technical discussions.</li><li><strong>Respect expertise but question assumptions.</strong> The best designer-engineer relationships involve mutual respect for each other’s knowledge, plus a willingness to challenge “the way things are done”.</li><li><strong>Share the same goals.</strong> When both teams are measured against the same outcomes (user satisfaction, business impact), the artificial tension between UI and backend priorities starts to disappear.</li><li><strong>Keep talking.</strong> Regular check-ins between design and engineering throughout development ensure both sides can adjust as new information comes up.</li></ol><p>The nice thing about this topic is that it’s not binary at all. The relationship between interface design and technical implementation is on a spectrum, and different products or features might need different approaches.</p><p>Like, if you’re building some crazy AR thing, you might need to push what’s technically possible to make it look cool. But for something like banking software? You better make sure that data is rock solid first. Most stuff we build needs a mix of approaches depending on what part you’re working on.</p><p>What matters is making these decisions consciously, knowing the trade-offs, rather than defaulting to one approach out of habit or office politics.</p><p>That tea chat with our product designer didn’t settle the question nor should it have. The tension between interface vision and technical reality is actually a productive one that drives innovation when handled well.</p><p>This chat on Wednesday got me thinking about something I’ve felt but never really put into words before. Maybe that’s the whole point: not finding a final answer, but asking better questions and building tech that actually helps people.</p><p>So, does UI/UX drive backend, or does backend drive UI/UX?</p><p>Yes. Both. Neither. It depends.</p><p>And that’s exactly how it should be.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSB2gwj83y8MJ41gOWuLog.png" /></figure><p>👉 Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></p><p>👉 Follow us: <a href="https://x.com/Bhuwanchet67277"><strong>X</strong></a> | <a href="https://medium.com/codetodeploy"><strong>Medium</strong></a></p><p>👉 CodeToDeploy Tech Community is live on Discord — <a href="https://discord.gg/ZpwhHq6D"><strong>Join now!</strong></a></p><p>👉 <strong>Follow our publication, </strong><a href="https://medium.com/codetodeploy"><strong>CodeToDeploy</strong></a></p><p><strong>Note:</strong> This Post may contain affiliate links.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=231b93feb18a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetodeploy/ui-ux-vs-backend-who-should-lead-the-dance-231b93feb18a">UI/UX vs Backend: Who Should Lead the Dance?</a> was originally published in <a href="https://medium.com/codetodeploy">CodeToDeploy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning How to Learn: The Most Valuable Skill]]></title>
            <link>https://blog.stackademic.com/learning-how-to-learn-the-most-valuable-skill-946e414c7fd4?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/946e414c7fd4</guid>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[personal-growth]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 09:46:20 GMT</pubDate>
            <atom:updated>2025-03-03T06:57:41.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8wU033orMsnqCw9r" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Tim Mossholder</a> on <a href="https://unsplash.com/photos/love-to-learn-pencil-signage-on-wall-near-walking-man-WE_Kv_ZB1l0?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><blockquote>In tech, your most valuable skill isn’t what you know, it’s how quickly you can learn what you don’t know yet. Curiosity is the real programming language. — Me</blockquote><h3>The Learning Mindset Revolution</h3><p>I came into tech with a computer science degree under my belt. Three years of algorithms, data structures, database development, information management systems, event-driven programming, networking and operating systems, and theoretical foundations. You’d think that would have prepared me for everything, right? Not quite. Like many new developers, I still found myself obsessing over the wrong things, collecting certifications like Pokémon cards, memorising syntax until my eyes crossed, and chasing every shiny new technology that blew up on Twitter. I thought success meant knowing everything.</p><p>I was wrong. My CS degree taught me how to think, but the real world taught me how to learn.</p><p>The turning point came during a particularly challenging project. I was faced with a tech stack I’d never touched before, a tight deadline, and that familiar knot of anxiety in my stomach. But something was different this time. Instead of freezing up, I found myself getting excited. The unknown wasn’t scary anymore, it was fascinating.</p><p>That’s when it hit me: true growth isn’t about what you know, but how you learn.</p><h3>The Learning Framework That Changed Everything</h3><h4>Curiosity as Your North Star</h4><p>Curiosity isn’t just a nice-to-have personality trait, it’s your secret weapon. When I encounter something I don’t understand, I’ve trained myself to lean in instead of backing away. I treat every knowledge gap as a puzzle waiting to be solved.</p><p>Here’s what this looks like in practice:</p><ul><li>Instead of copying and pasting Stack Overflow solutions, I dig into why they work. I ask myself: Why does this approach work? What happens if I tweak it?</li><li>When a new technology emerges, I ask “What problem is this really solving?”</li><li>If something breaks, I celebrate, it’s a chance to understand the system better</li></ul><h4>The Project-Based Learning Loop</h4><p>Theory is important, but nothing beats getting your hands dirty. I’ve developed a learning cycle that consistently delivers results:</p><ol><li><strong>Grasp the Fundamentals</strong>: Start with documentation and key concepts</li><li><strong>Build Something Real</strong>: Create a project that solves an actual problem</li><li><strong>Push the Boundaries</strong>: Intentionally break things and experiment</li><li><strong>Learn and Iterate</strong>: Document insights and rebuild stronger</li></ol><p>For example, when learning GraphQL, I didn’t stop at tutorials. I built a small social media API, deliberately introduced complex queries, and worked through N+1 problems. Every challenge taught me something. Every mistake was a stepping stone.</p><h4>Embracing the Unknown</h4><p>The tech landscape changes faster than anyone can keep up. Last year’s best practices might be today’s antipatterns. Instead of viewing this as a burden, I’ve learned to see it as liberation. You don’t have to know everything, you just need to know how to find out.</p><p>My evolving learning toolkit includes:</p><ul><li>Deep-dive technical articles (but only after trying to solve problems myself)</li><li>Open-source contributions (reading good code is as valuable as writing it)</li><li>Side projects that stretch my comfort zone</li><li>Teaching others (nothing solidifies understanding like explanation)</li></ul><h3>Practical Strategies for Effective Learning</h3><h3>Breaking Down Complexity</h3><p>Complex systems are just collections of simpler parts working together. When tackling something new, I:</p><ol><li>Draw it out first, a visual representation helps identify patterns</li><li>Start with the smallest working example</li><li>Add complexity one layer at a time</li><li>Document my understanding through comments and README files</li></ol><h3>Managing Information Overload</h3><p>In a world of infinite resources, focus becomes your most precious resource. Here’s how I manage it:</p><ul><li>Set clear learning objectives before diving in</li><li>Use timeboxing to maintain momentum</li><li>Take structured notes that focus on concepts, not syntax</li><li>Limit myself to learning one major technology at a time</li></ul><h3>The Mindset Shift</h3><p>Learning effectively requires reframing common experiences:</p><ul><li><strong>Imposter syndrome?</strong> That’s your growth radar working perfectly</li><li><strong>Feeling overwhelmed?</strong> You’re at the edge of your comfort zone, exactly where growth happens</li><li><strong>Made a mistake?</strong> Congratulations, you just found a gap in your understanding</li></ul><h3>Tools That Accelerate Learning</h3><p>While the specific tools change, these categories remain constant:</p><ul><li><strong>Documentation readers</strong>: Because great docs are your best friends</li><li><strong>Note-taking systems</strong>: To build your second brain</li><li><strong>Code playgrounds</strong>: For rapid experimentation</li><li><strong>Community platforms</strong>: To learn from others’ experiences</li></ul><h3>The Path Forward</h3><p>In technology, your learning ability is your most valuable asset. Languages will evolve, frameworks will come and go, but a robust learning process will serve you forever.</p><p>The key isn’t to learn everything, it’s to learn how to learn anything.</p><p>Stay curious. Stay hungry. And remember: every expert was once a beginner who just kept learning.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946e414c7fd4" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/learning-how-to-learn-the-most-valuable-skill-946e414c7fd4">Learning How to Learn: The Most Valuable Skill</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Partial Caching Leads to Stale Data]]></title>
            <link>https://blog.stackademic.com/how-partial-caching-leads-to-stale-data-8c11c3e547a1?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c11c3e547a1</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 16:34:41 GMT</pubDate>
            <atom:updated>2025-02-24T01:57:45.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*poj6Y8yxSD7DJnjv" /><figcaption>Photo by <a href="https://unsplash.com/@darias_big_world?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Daria Strategy</a> on <a href="https://unsplash.com/photos/assorted-labeled-bottle-display-on-rack-BMnX7L9G5xc?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><strong>TL;DR</strong>: If your API response depends on a parameter, header, or path variable, include it in your cache key or users will get stale data.</p><h3>What is Caching?</h3><p>Think of caching like organising your kitchen counter: you keep frequently used ingredients and tools within easy reach so you don’t have to dig through the pantry every time you need them. Similarly, caching stores frequently accessed data (like API responses) in a fast, easily accessible location, reducing the need to recompute or fetch the same data repeatedly.</p><p>When building serverless applications with AWS Lambda and API Gateway, caching can be a powerful tool to improve performance and reduce costs. However, as I recently discovered, it can also lead to unexpected behaviours that might be difficult to debug. Here’s a cautionary tale about API Gateway caching that every developer should know about.</p><h3>The Scenario</h3><p>I encountered this issue while creating a new endpoint for a new system I am building. The endpoint accepted eight query parameters, and in an attempt to optimise performance, I decided to implement caching using only four of these parameters. It seemed like a reasonable approach at the time. why cache everything when only some parameters were frequently used?</p><p>To illustrate what happened, let’s look at a similar scenario: imagine an API endpoint for fetching product listings with eight query parameters:</p><ul><li>Cached parameters: category, sortOrder, page, limit</li><li>Uncached parameters: colour, size, priceMin, priceMax</li></ul><p>During testing of my new endpoint, I discovered something concerning: requests with different values for the uncached parameters were returning the same cached responses!</p><p>For example:</p><pre>Request 1: ?category=shoes&amp;sortOrder=price&amp;colour=red<br>Request 2: ?category=shoes&amp;sortOrder=price&amp;colour=blue</pre><p>Both returned identical results because colour wasn&#39;t part of the cache key. The API Gateway treated them as the same request, serving cached data from the first call. This meant users looking for blue shoes were seeing results for red shoes!</p><h3>The Unexpected Behavior</h3><p>What I discovered was shocking: requests with different values for the uncached parameters were still returning cached responses! This meant that users were getting incorrect data, even though their requests had different parameter values that weren’t supposed to be cached.</p><p>The root cause lies in how API Gateway generates cache keys:</p><ol><li>By default, API Gateway uses the entire API request as the cache key, including:</li><li>When you specify certain parameters for caching, you’re not just selecting what to cache — you’re defining the cache key structure itself.</li><li><strong>Critical Point</strong>: Parameters not included in the cache key configuration are effectively ignored for caching purposes. This means that two requests that differ only in uncached parameters will be treated as the same request from a caching perspective.</li></ol><h3>How API Gateway Processes Requests With Caching</h3><p>The following diagram illustrates the <strong>flow of a request</strong> through API Gateway when caching is enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5vCPb6R6SPaplzOKry1Ug.png" /><figcaption>tandard request flow through API Gateway with caching enabled</figcaption></figure><h3>Best Practices to Avoid This Pitfall</h3><p><strong>Carefully Consider Your Cache Key Parameters</strong></p><ul><li>Always include ALL parameters that could affect the response in your cache key configuration</li><li>If a parameter can influence the response, it should be part of the cache key</li></ul><p><strong>Document Your Caching Strategy</strong></p><ul><li>Maintain clear documentation about which parameters are part of the cache key</li><li>Include the reasoning behind caching decisions</li></ul><p><strong>Test Thoroughly</strong></p><ul><li>Create test cases that vary both cached and uncached parameters</li><li>Verify that changes in uncached parameters don’t return cached responses when they shouldn’t</li></ul><p><strong>Watch for Edge Cases</strong></p><ul><li><strong>Case sensitivity</strong>: param vs Param are treated as different parameters</li><li><strong>Encoding</strong>: user=john%20doe and user=john doe generate different keys</li><li><strong>Missing vs default parameters</strong>: Explicit ?param=default vs omitted param are different keys</li></ul><p><strong>Monitor Cache Behavior</strong></p><ul><li>Implement logging to track cache hits and misses</li><li>Set up alerts for unexpected cache behavior</li></ul><h4>How Uncached Parameters Are Ignored in Cache Key Generation</h4><p>This diagram visually explains how <strong>API Gateway ignores parameters</strong> not included in the cache key configuration, leading to incorrect cached responses</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtW0A2l_BqKXSJVBraKRAQ.png" /><figcaption>Same response returned despite different uncached parameters</figcaption></figure><h3>Implementation Example</h3><p>⚠️ <strong>Warning</strong>: Including many parameters increases cache size (and cost). Balance correctness with cost efficiency.</p><h3>Using the Serverless Framework</h3><pre>plugins:<br>  - serverless-api-gateway-caching<br><br>custom:<br>  apiGatewayCaching:<br>    enabled: true<br>    clusterSize: &#39;0.5&#39;<br>    ttlInSeconds: 300<br>    dataEncrypted: true<br>    perKeyInvalidation:<br>      requireAuthorization: true<br>      handleUnauthorizedRequests: Ignore<br><br>functions:<br>  get-user-data:<br>    handler: handlers/users.get<br>    events:<br>      - http:<br>          path: /users/{userId}<br>          method: get<br>          caching:<br>            enabled: true<br>            cacheKeyParameters:<br>              - name: request.path.userId<br>              - name: request.header.Authorization</pre><h3>Manually Invalidating API Gateway Cache Using AWS SDK</h3><p>To manually clear API Gateway’s cache via the AWS SDK (Node.js):</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>const apiGateway = new AWS.APIGateway({ region: &#39;us-east-1&#39; });<br><br>const invalidateCache = async (restApiId, stageName) =&gt; {<br>  await apiGateway.flushStageCache({ restApiId, stageName }).promise();<br>  console.log(`Cache invalidated for API Gateway Stage: ${stageName}`);<br>};<br><br>// Example usage<br>invalidateCache(&#39;your-rest-api-id&#39;, &#39;your-stage-name&#39;);</pre><p>👉 <strong>Alternative</strong>: You can also invalidate cache via CLI</p><pre>aws apigateway flush-stage-cache --rest-api-id YOUR_API_ID --stage-name YOUR_STAGE_NAME</pre><h3>API Gateway Cache Size Limits &amp; Cost Impact (Very Short)</h3><ul><li>API Gateway <strong>cache sizes</strong> range from <strong>0.5 GB</strong> to <strong>237 GB</strong>.</li><li>Larger caches <strong>reduce Lambda executions</strong> but <strong>increase AWS costs</strong>.</li><li><strong>Trade-off</strong>: Larger cache <strong>improves latency</strong> but costs more. Optimise wisely!</li></ul><h3>Conclusion</h3><p>The lesson learned is clear: when implementing API Gateway caching, you must include all parameters that can affect the response in your cache key configuration. Failing to do so can lead to subtle bugs where users receive incorrect cached responses.</p><p><strong>Remember</strong>: In API Gateway caching, what you don’t include in your cache key configuration is just as important as what you do include. When in doubt, include more parameters in your cache key rather than fewer.</p><h3>Key Takeaways</h3><ol><li>Partial parameter caching is dangerous unless you’re absolutely certain about your caching strategy</li><li>When in doubt, include all parameters in your cache key</li><li>Always test your caching configuration with varying parameter combinations</li><li>Monitor cache hits to detect unexpected behavior</li></ol><h3>Additional Resources</h3><ul><li><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-caching.html">AWS Documentation on API Gateway Caching</a></li><li><a href="https://github.com/DianaIonita/serverless-api-gateway-caching">Serverless API Gateway Caching Plugin</a></li></ul><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c11c3e547a1" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-partial-caching-leads-to-stale-data-8c11c3e547a1">How Partial Caching Leads to Stale Data</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making JavaScript Code Modular and Testable with Dependency Injection]]></title>
            <link>https://blog.stackademic.com/making-javascript-code-modular-and-testable-with-dependency-injection-01130beba287?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/01130beba287</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 08:47:00 GMT</pubDate>
            <atom:updated>2024-10-30T02:24:52.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWyIAcmpfCKwJuG-VL05Zg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dreamevile?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Raphael Koh</a> on <a href="https://unsplash.com/photos/photo-of-stackable-cube-92dgYPsir9k?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Imagine you’re building a JavaScript app, and everything is going smoothly. You’ve got a UserService that grabs user data from a database, a few functions to log information, and everything works perfectly. But then, testing time comes, or you need to make a quick change to how the database works — and suddenly, it’s not so easy. Your code is tangled up in dependencies, making changes tricky and testing hard.</p><p>This is where <strong>Dependency Injection (DI)</strong> steps in. With DI, we pass in dependencies (like your database or logger) instead of having the code create its own. This makes the code easier to test, more flexible, and modular (so each part does its own job well). Let’s see how DI can help you simplify your JavaScript code!</p><h3>So, What Exactly is Dependency Injection?</h3><p>Dependency Injection is a way of “injecting” the things a piece of code depends on (like a database or a logger) from the outside. Instead of creating these dependencies directly inside the code, we pass them in.</p><p>Think of it like a battery-powered flashlight: instead of building a flashlight with non-removable batteries, DI lets you pop batteries in and out, so you can easily replace them when needed.</p><h3>Why Use Dependency Injection in JavaScript?</h3><p>Dependency Injection helps you:</p><ul><li><strong>Keep Code Modular</strong>: Each part does its job without knowing too much about the others, making everything more flexible.</li><li><strong>Make Testing Easy</strong>: You can test code without depending on real databases or external services by swapping them with simple mock objects.</li><li><strong>Make Maintenance Easier</strong>: If something in the dependency changes (like your database), you don’t have to dig into every place it’s used. Just change it once where you set up the dependency.</li></ul><h3>Dependency Injection in Action</h3><p>Let’s look at an example of a service that grabs user data from a database.</p><h4>The Basic Approach (Without Dependency Injection)</h4><p>Here’s how it might look without DI, where everything is hardcoded:</p><pre>// DatabaseService.js<br>class DatabaseService {<br>  fetchUser(id) {<br>    if (!id) throw new Error(&quot;User ID is required&quot;);<br>    return { id, name: &quot;John Doe&quot; }; // Simulate database fetch<br>  }<br>}<br><br>// UserService.js<br>class UserService {<br>  constructor() {<br>    this.dbService = new DatabaseService();<br>  }<br><br>  getUser(id) {<br>    try {<br>      return this.dbService.fetchUser(id);<br>    } catch (error) {<br>      console.error(&quot;Error fetching user:&quot;, error.message);<br>      return null;<br>    }<br>  }<br>}<br><br>// Usage<br>const userService = new UserService();<br>console.log(userService.getUser(1));<br></pre><p>Here, UserService directly creates a DatabaseService instance. This means that UserService is completely tied to DatabaseService, making it hard to change or test.</p><h4>Refactoring with Dependency Injection</h4><p>Now, let’s rewrite this so we pass DatabaseService into UserService instead of creating it inside. This is Dependency Injection in action!</p><pre>// UserService.js with DI<br>class UserService {<br>  constructor(dbService) {<br>    if (!dbService) throw new Error(&quot;Database service is required&quot;);<br>    this.dbService = dbService;<br>  }<br><br>  getUser(id) {<br>    try {<br>      return this.dbService.fetchUser(id);<br>    } catch (error) {<br>      console.error(&quot;Error fetching user:&quot;, error.message);<br>      return null;<br>    }<br>  }<br>}<br><br>// Usage with DI<br>const dbService = new DatabaseService();<br>const userService = new UserService(dbService);<br>console.log(userService.getUser(1));<br>By injecting DatabaseService, UserService is now flexible. If you want to use a different database service or a mock one, you just pass it in when creating UserService.</pre><h3>Using Dependency Injection to Make Testing Easy</h3><p>DI is super helpful for testing. Let’s say you want to test UserService without connecting to a real database. With DI, you can just pass in a “mock” database.</p><h4>Testing with a Mock Dependency</h4><p>Here’s how you could use a mock DatabaseService for testing:</p><pre>// Mock DatabaseService for Testing<br>class MockDatabaseService {<br>  fetchUser(id) {<br>    // Mock different scenarios we want to test<br>    if (!id) throw new Error(&quot;Mock: User ID is required&quot;);<br>    <br>    // Mock successful case<br>    if (id === 1) {<br>      return { id: 1, name: &quot;Mock User&quot;, role: &quot;admin&quot; };<br>    }<br>    <br>    // Mock user not found case<br>    if (id === 999) {<br>      return null;<br>    }<br>    <br>    // Mock error case<br>    if (id === -1) {<br>      throw new Error(&quot;Mock: Database connection failed&quot;);<br>    }<br><br>    return { id, name: &quot;Mock User&quot; };<br>  }<br>}<br><br>// Mock Logger for Testing<br>class MockLoggerService {<br>  constructor() {<br>    this.logs = []; // Track logs for verification<br>  }<br><br>  log(message) {<br>    this.logs.push(message);<br>  }<br><br>  clearLogs() {<br>    this.logs = [];<br>  }<br>}<br><br>// Test examples<br>function runTests() {<br>  console.log(&quot;Running tests...&quot;);<br>  <br>  const mockDb = new MockDatabaseService();<br>  const mockLogger = new MockLoggerService();<br>  const userService = new UserService(mockDb, mockLogger);<br><br>  // Test 1: Successful user fetch<br>  const user = userService.getUser(1);<br>  console.assert(user.name === &quot;Mock User&quot;, &quot;Should fetch mock user&quot;);<br>  console.assert(mockLogger.logs[0] === &quot;Fetched user with id: 1&quot;, <br>    &quot;Should log fetch message&quot;);<br><br>  // Test 2: Handle missing ID<br>  const nullUser = userService.getUser(null);<br>  console.assert(nullUser === null, &quot;Should handle null ID gracefully&quot;);<br><br>  // Test 3: Handle non-existent user<br>  const nonExistentUser = userService.getUser(999);<br>  console.assert(nonExistentUser === null, <br>    &quot;Should handle non-existent user&quot;);<br><br>  mockLogger.clearLogs();<br><br>  // Test 4: Handle database error<br>  const errorCase = userService.getUser(-1);<br>  console.assert(errorCase === null, <br>    &quot;Should handle database error gracefully&quot;);<br><br>  console.log(&quot;Tests completed!&quot;);<br>}<br><br>// Run the tests<br>runTests();</pre><p>With DI, we can easily swap the real services for mock versions that help us test different scenarios:</p><ul><li>Successful data fetching</li><li>Error handling for invalid inputs</li><li>Handling non-existent data</li><li>Database error scenarios</li><li>Verifying that logging works correctly</li></ul><p>This makes our tests:</p><ul><li>Fast (no real database needed)</li><li>Reliable (no external dependencies)</li><li>Comprehensive (we can easily test error cases)</li><li>Isolated (each test runs independently)</li></ul><blockquote><strong>Note</strong>: In real applications, you’d typically use testing frameworks like Jest or Mocha/Chai, which provide more robust assertion methods and test organisation. The examples above demonstrate the concepts using basic JavaScript, but the same principles apply when using testing frameworks.</blockquote><p>Now that we’ve seen how DI makes testing easier, let’s look at how it can help make our code more modular</p><h3>Making Code More Modular with DI</h3><p>DI also makes your code more modular. Imagine you want UserService to have a logging feature. Instead of directly using a logging service, you can inject one.</p><h4>Adding Multiple Dependencies with DI</h4><p>Now, let’s add a logging service without locking it into UserService:</p><pre>// LoggerService.js<br>class LoggerService {<br>  log(message) {<br>    if (!message) throw new Error(&quot;Message is required for logging&quot;);<br>    console.log(message);<br>  }<br>}<br><br>// UserService.js<br>class UserService {<br>  constructor(dbService, loggerService) {<br>    if (!dbService) throw new Error(&quot;Database service is required&quot;);<br>    if (!loggerService) throw new Error(&quot;Logger service is required&quot;);<br><br>    this.dbService = dbService;<br>    this.loggerService = loggerService;<br>  }<br><br>  getUser(id) {<br>    try {<br>      const user = this.dbService.fetchUser(id);<br>      this.loggerService.log(`Fetched user with id: ${id}`);<br>      return user;<br>    } catch (error) {<br>      console.error(&quot;Error in UserService:&quot;, error.message);<br>      return null;<br>    }<br>  }<br>}<br><br>// Usage<br>const dbService = new DatabaseService();<br>const loggerService = new LoggerService();<br>const userService = new UserService(dbService, loggerService);<br>console.log(userService.getUser(1)); // Output: Fetched user with id: 1<br></pre><p>Here, UserService doesn’t know how LoggerService works or what kind of logging it does. You can swap it out for any type of logging service without modifying UserService itself.</p><h3>To Wrap Up</h3><p>Dependency Injection might sound fancy, but it’s really about making your code more flexible, testable, and modular. With DI, you can:</p><ul><li>Swap dependencies easily, making testing simple and reliable.</li><li>Keep parts of your code separate so each can do its job independently.</li><li>Make maintenance a breeze, so changes don’t mess up your whole codebase.</li></ul><p>Next time you’re building something in JavaScript, try using Dependency Injection. It might save you a lot of headaches in the long run, and you’ll enjoy having code that’s easier to test and work with!</p><h3>Key Takeaways</h3><ul><li><strong>DI Decouples Dependencies</strong>: Dependency Injection allows you to pass dependencies (like database or logging services) into a module, making it more flexible and modular.</li><li><strong>Easier and Isolated Testing</strong>: By injecting mock dependencies, you can test each part of your code independently without relying on real services, keeping tests fast and reliable.</li><li><strong>Simplifies Maintenance</strong>: With DI, changes to dependencies don’t affect the core logic, making it easier to update or replace services in your codebase.</li><li><strong>Promotes Code Reusability</strong>: DI encourages writing self-contained, reusable code since dependencies can be swapped or mocked as needed.</li><li><strong>Enhances Error Handling</strong>: DI helps handle different scenarios (like errors and missing data) by allowing you to test with varied responses from mock dependencies.</li></ul><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01130beba287" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/making-javascript-code-modular-and-testable-with-dependency-injection-01130beba287">Making JavaScript Code Modular and Testable with Dependency Injection</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cold Starts, Massive Files, and Lambda Drama: How I Make It Work]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.stackademic.com/cold-starts-massive-files-and-lambda-drama-how-i-make-it-work-d80a62844595?source=rss-665d221b51ae------2"><img src="https://cdn-images-1.medium.com/max/1920/1*r41pTQn4IepZ5IiVqV5jXw.jpeg" width="1920"></a></p><p class="medium-feed-snippet">I work with AWS Lambda functions every day. In fact, you could say that when I sleep, I have nightmares about AWS deprecating Node.js&#x2026;</p><p class="medium-feed-link"><a href="https://blog.stackademic.com/cold-starts-massive-files-and-lambda-drama-how-i-make-it-work-d80a62844595?source=rss-665d221b51ae------2">Continue reading on Stackademic »</a></p></div>]]></description>
            <link>https://blog.stackademic.com/cold-starts-massive-files-and-lambda-drama-how-i-make-it-work-d80a62844595?source=rss-665d221b51ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/d80a62844595</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Kelvin Anigboro]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 10:16:49 GMT</pubDate>
            <atom:updated>2024-09-17T10:16:49.906Z</atom:updated>
        </item>
    </channel>
</rss>