<?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 Akinola Oluwatofunmi on Medium]]></title>
        <description><![CDATA[Stories by Akinola Oluwatofunmi on Medium]]></description>
        <link>https://medium.com/@akinolatofunmi?source=rss-5fed123f13e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pOmaA8E7Mxy0KMhD</url>
            <title>Stories by Akinola Oluwatofunmi on Medium</title>
            <link>https://medium.com/@akinolatofunmi?source=rss-5fed123f13e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:42:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akinolatofunmi/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[A Backend Engineer with HNG Internship]]></title>
            <link>https://medium.com/@akinolatofunmi/a-backend-engineer-with-hng-internship-a7abfb69c7b7?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7abfb69c7b7</guid>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Sat, 13 Jun 2026 15:58:04 GMT</pubDate>
            <atom:updated>2026-06-13T16:05:28.852Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two Tasks That Changed How I Think About Backend Systems</h3><p><em>Oluwatofunmi Akinola — HNG Internship, Stage 9b</em></p><p>I have spent the last few months building backend systems under real pressure. Deadlines, teammates depending on my code, bugs that made no sense at midnight. Most of it was straightforward once I got into it. Two tasks were not.</p><p>This post is about those two. One I built alone. One I built with a team. Both took longer than they should have, both broke in ways I did not expect, and both left me thinking differently about how software actually works.</p><h3>Task One: Append-Only Event Store (Individual — Stage 7)</h3><h3>What it was</h3><p>The task was simple on paper. Build a small HTTP service that stores events in a log file and reads them back by ID — even after the server restarts. No SQLite. No JSON file you rewrite. The log file <em>is</em> the database.</p><p>Three endpoints: POST /events to write, GET /events/:id to read, GET /stats for counts and file size.</p><h3>The problem it was solving</h3><p>Every database you have ever used survives crashes the same way: it writes to a log before touching anything else. PostgreSQL’s write-ahead log. Kafka’s commit log. They all share the same core idea — append only, never overwrite, replay the log on restart to recover state.</p><p>The task was to build the smallest possible version of this from scratch.</p><h3>How I approached it</h3><p>I started with the storage design. Each event is written as a single JSON object followed by a newline character. The file grows, nothing changes, nothing gets deleted. On startup, the server reads the file from byte zero to the end, rebuilds an in-memory index, and is ready to serve requests.</p><p>The index is a dictionary: { event_id → { offset, length } }. When a read request comes in, the server looks up the offset, seeks directly to that position in the file, reads exactly length bytes, and returns the parsed JSON. No scanning. No reading the whole file.</p><pre>events.log on disk:<br>byte   0: {&quot;id&quot;:&quot;abc...&quot;,&quot;type&quot;:&quot;signup&quot;}\n    83 bytes<br>byte  83: {&quot;id&quot;:&quot;xyz...&quot;,&quot;type&quot;:&quot;login&quot;}\n     79 bytes<br>byte 162: ...<br>Index in memory:<br>{ &quot;abc...&quot;: { offset: 0,  length: 83 },<br>  &quot;xyz...&quot;: { offset: 83, length: 79 } <br>}</pre><p>I built this in Python with FastAPI. The write path opens the file in binary append mode, calls seek(0, 2) to get the current end position (the offset for the new record), writes the encoded bytes, and stores the offset and length in the index.</p><h3>What broke</h3><p>The first version seemed to work. Events wrote, reads worked, restart recovered the count. Then I added a Unicode character to a payload — something as simple as a name with an accent — and the reads started returning corrupted JSON.</p><p>I spent a while convinced the file was being written incorrectly. It was not. The file was fine. The problem was the index.</p><p>I was storing len(line) where line was a Python string. A Python string measures characters. The character é is one character. But in UTF-8 on disk it is two bytes. So when I stored length = 52 for a 52-character string, the actual bytes written were 53. When the server tried to read 52 bytes from that offset, it cut off the last byte of the record. The JSON parser failed silently on some records and visibly corrupted others.</p><p>The fix was one word. Measure the bytes, not the characters:</p><pre>data = line.encode(&quot;utf-8&quot;)  # convert first<br>length = len(data)            # measure bytes, not characters</pre><p>After that, I understood something that had always been abstract to me. Files do not store text. They store bytes. Text is an interpretation of those bytes. If you mix up the two, you get silent data corruption that only shows up for certain inputs.</p><p>The second problem was concurrency. FastAPI is async — multiple requests can run simultaneously on the same event loop. Without a lock, two concurrent writes could both call seek(0, 2) and get the same offset before either has written anything. Both would write to the same position and one event would overwrite the other. I added an asyncio.Lock around the seek and write, making the two operations atomic within the event loop.</p><h3>What I took away</h3><p>Before this task I had never thought below the level of “read a file” and “write a file”. Afterwards, I understood what seek() actually does — it moves a cursor to a specific byte position in a file, like scrubbing to a timestamp in a video. I understood why measuring bytes matters when the bytes and the characters are not the same thing. And I understood, concretely, why append-only storage is crash-safe in a way that in-place updates are not.</p><p>If the process crashes mid-write, the incomplete record lands at the end of the file. Everything before it is untouched. On recovery, the server reads line by line, skips any line that is not valid JSON, and rebuilds the index from what remains. The newline at the end of a record is effectively a commit marker. If it is there, the record is complete and valid.</p><p>I also understood, for the first time, why Kafka stores messages in an append-only partition log and why consumers track their position using offsets. I built a tiny version of that same mechanic from scratch. Reading about it never made it concrete. Building it did.</p><h3>Why I picked it</h3><p>It is the task that most changed how I read technical documentation. I can look at a description of Kafka, PostgreSQL’s WAL, or Loki’s chunk storage now and understand the design decision behind it immediately. That shift in understanding feels more valuable than any feature I shipped.</p><h3>Task Two: Clinical Sight — Real-Time Notifications (Team — Stage 6)</h3><h3>What it was</h3><p>Clinical Sight is an AI-powered platform where clinicians upload lab result images and receive structured interpretations. The pipeline is asynchronous — a Celery worker runs OCR, then passes the result to an LLM, and the whole thing can take anywhere from 20 to 60 seconds.</p><p>The problem was delivering the result to the browser the moment it was ready, without the user needing to refresh.</p><p>My team and I implemented three real-time systems for Stage 6: Server-Sent Events for notifications, a WebSocket chat endpoint, and a structured audit log for the processing pipeline. I am going to focus on the SSE notifications because that is where things went wrong in the most interesting way.</p><h3>The problem it was solving</h3><p>A user uploads a file. The HTTP response comes back immediately — the file is accepted, processing has started. Now what? The user is sitting on the results page. The browser has no idea when the AI is done.</p><p>The naive solution is polling: the browser hits GET /status every few seconds. It works but it wastes requests and still has latency equal to the poll interval.</p><p>We used Server-Sent Events instead. The browser opens a persistent connection to GET /notifications/stream. The server holds that connection open and pushes a message the moment the pipeline finishes. One message, instant delivery, no polling.</p><h3>How we approached it</h3><p>The architecture was straightforward. When the Celery pipeline completes, it publishes an event to a Redis pub/sub channel keyed by user ID. A FastAPI endpoint subscribes to that channel, listens for messages, and streams them to the browser as SSE.</p><p>We added a keepalive ping every 30 seconds so the browser does not assume the connection is dead during quiet periods.</p><h3>What broke</h3><p>The first bug was that the SSE endpoint was sending pings continuously — hundreds per second instead of one every 30 seconds. The cause was a single parameter. We were calling pubsub.get_message() without a timeout argument, which defaults to zero. With no timeout, get_message() is non-blocking — it returns None immediately if there is nothing in the buffer. Our loop was calling it thousands of times a second, getting None every time, and sending a ping for each None. The fix was either passing timeout=30 directly to get_message() or — what we settled on — a poll-with-sleep approach using asyncio.sleep(1) between polls. One second resolution, no tight loop.</p><p>The second bug was more interesting and took much longer to find.</p><p>After fixing the ping rate, the SSE connections started closing immediately after delivering one notification. The sequence was: user connects, waits, notification arrives, browser receives it, connection drops. Every single time.</p><p>My first diagnosis was wrong. I thought asyncio.wait_for was timing out and cancelling the generator that read from Redis, causing a StopAsyncIteration on the next poll. I removed the wait_for wrapper. The bug persisted.</p><p>My second diagnosis was also wrong. I thought there was a race condition between the generator closing and the endpoint loop. I restructured the generator. The bug persisted.</p><p>The actual cause was request.is_disconnected().</p><p>In Starlette, is_disconnected() does a non-blocking check by reading from the ASGI receive channel with a zero-second deadline using anyio.move_on_after(0). When there is a message in the receive queue, it reads it. When the queue is empty, the operation is cancelled and cancel_scope.cancelled_caught is set to True.</p><p>Here is the specific problem. At the start of every HTTP request, the ASGI server puts exactly one message in the receive channel: an http.request message with an empty body, signalling that the request body has been fully received. The first time is_disconnected() runs, it reads that message. The queue is now empty. Every subsequent call to is_disconnected() finds an empty queue, the zero-second deadline fires, and Starlette sets _is_disconnected = True — not because the client actually disconnected, but because the queue was empty.</p><p>We were checking is_disconnected() at the top of every loop iteration. So: user connects → one notification delivered → loop continues → is_disconnected() consumes the initial http.request message → next iteration, queue is empty → _is_disconnected = True → connection closes.</p><p>The fix was to remove is_disconnected() from the loop entirely. In asyncio, when a client actually disconnects, uvicorn cancels the ASGI task. That cancellation propagates as CancelledError through whatever the event loop is currently awaiting — in our case, the Redis poll. We added raise to the except asyncio.CancelledError block in the generator so the cancellation propagated cleanly up the call stack. The connection now stays open until the client actually closes it.</p><pre># Before — is_disconnected() lies when the receive queue is empty<br>while True:<br>    if await request.is_disconnected():<br>        return<br>    event = await sub_iter.__anext__()<br># After — let uvicorn&#39;s CancelledError close the connection naturally<br>while True:<br>    event = await sub_iter.__anext__()</pre><h3>What I took away</h3><p>Two things.</p><p>The first is about debugging. Both fixes required understanding something below the level I normally think at. The ping bug required understanding that “non-blocking” means “returns immediately even if there is nothing there.” The disconnect bug required understanding how Starlette implements is_disconnected() at the ASGI protocol level. Both times, the fix was one or two lines. Both times, finding it required understanding a layer I had never looked at before.</p><p>That is the pattern I now expect for hard bugs. The symptom is in your code. The cause is usually in something your code depends on.</p><p>The second is about asyncio.CancelledError. Before this, I treated it as an implementation detail. Now I treat it as a first-class mechanism. In asyncio, cancellation is how cleanup happens. If you swallow CancelledError without re-raising it, you break the cancellation chain. Things that were supposed to stop keep running. We had two separate bugs caused by this — the wait_for wrapping the generator, and the except CancelledError without raise in the EventBus subscriber. Both cases, the fix was the same: let cancellation propagate.</p><h3>Why I picked it</h3><p>I picked this one because of how long it took to find something so small. The is_disconnected() bug was one line of code that behaved completely differently from what the name suggested. Finding it required reading Starlette&#39;s source code, understanding the ASGI receive channel protocol, and then working backwards from the symptom to the cause.</p><p>That process — reading the source, not just the documentation — is a habit I did not have before. I have it now.</p><h3>Final thought</h3><p>Both tasks taught me the same thing from different angles: the way you understand a system from the outside is not the same as how it actually works. The file stores bytes, not text. The connection closes because the receive queue is empty, not because the client left. Both of those are obvious in hindsight. Neither was obvious before I had to find them the hard way.</p><p>That gap between the mental model and the actual behaviour is where the interesting bugs live. I am better at finding it now than I was six months ago. That is what I am taking out of this internship.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7abfb69c7b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EDD: Anomaly Detection Engine: V1 Post-Mortem & V2 Architecture]]></title>
            <link>https://medium.com/@akinolatofunmi/edd-anomaly-detection-engine-v1-post-mortem-v2-architecture-85afeeadb5da?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/85afeeadb5da</guid>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Thu, 11 Jun 2026 10:21:11 GMT</pubDate>
            <atom:updated>2026-06-11T10:21:11.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_54fJavNZhtztRZuVZe4IA.png" /><figcaption>Architectural diagram v2</figcaption></figure><p><strong>Preface</strong></p><p>V1 of this system works. It tails Nginx access logs, maintains a sliding window of request rates per IP and globally, computes Z-scores against a 30-minute rolling baseline, and fires iptables rules to block anomalous IPs. It sends Slack alerts. It has a dashboard. For a prototype under a deadline, it is complete.</p><p>For production, it is dangerous.</p><p>Not because the detection logic is wrong — the math is sound. It is dangerous because the architecture makes assumptions that do not hold under real adversarial pressure. This document is a post-mortem of those assumptions and a design for a system that does not make them.</p><h3><strong>V1 Architecture Critique</strong></h3><h4>What V1 Actually Is</h4><p>A single Python process. Five concurrent threads sharing in-process state: the main log-tailing loop, a baseline ticker, an unbanner, a Flask dashboard, and nothing else. All detection state — ban records, sliding windows, baseline statistics — lives in Python dictionaries. The process runs inside a Docker container with network_mode: host and cap_add: NET_ADMIN.</p><p>That last line deserves to be said plainly: the container has host networking and full network admin capability because there was no cleaner way to run iptables from inside a container. This is not a minor operational detail. It means any vulnerability in the detector code — in Flask, in PyYAML, in the requests library, in the log-parsing logic — hands an attacker the host network stack. Every security boundary Docker provides is gone. The application we are protecting from attackers has a security daemon attached to it that negates Docker’s container isolation entirely. This was a deadline trade-off. It should not survive into production.</p><h4>The Fundamental Problem With IP-Based Detection</h4><p>The system’s unit of identity is the IP address. Every detection heuristic, every ban record, every escalation level is keyed on IP. This is the architectural decision that limits everything else.</p><p>IP addresses are cheap. Residential proxy pools offer millions of unique IPs for under ten dollars per gigabyte of traffic. A botter who discovers that their IP is being blocked does not stop — they buy proxies. From that point, the ban list is a leaky bucket. New IPs arrive faster than the system can ban them. Escalation levels are meaningless because no IP is ever reused long enough to accumulate a level. The entire enforcement model stops functioning.</p><p>Worse: the attacker’s traffic does not disappear from the statistics when they start rotating IPs. It stays in the baseline window. If the attack runs long enough — and a proxy-equipped attacker can sustain pressure indefinitely — effective_mean drifts upward. The standard deviation widens. The Z-score threshold of 3.0 now requires a higher absolute rate to trigger because normal has been redefined to include the attack. The system becomes less sensitive in direct proportion to how long it has been under attack. This is not a hypothetical failure mode. It is a deterministic consequence of using mean and standard deviation on a dataset that includes adversarial samples.</p><h3>Specific Breaking Points</h3><p><strong>State evaporates on restart.<br></strong> blocker.banned_ips is a Python dictionary. A container redeploy — routine in any production environment — wipes it. An IP serving a two-hour ban is immediately unblocked. The escalation history is gone. The attacker’s fourth offence becomes their first again. There is no persistence layer.</p><p><strong>Distributed attacks cause alerts, not blocks.<br></strong> In main.py, when alert[‘type’] == ‘global’, the code calls notifier.send_global_alert(). It does not call blocker.block_ip(). A coordinated attack from five hundred IPs each sending three requests per second — well above what any single client would legitimately generate in aggregate — produces a Slack notification and nothing else. The system’s most dangerous attack scenario is the one it explicitly does not respond to.</p><p><strong>Notification calls block the detection loop.<br></strong> notifier.send_ban() is synchronous, called inline from the main event loop. During a DDoS wave with hundreds of unique IPs hitting the system in rapid succession, hundreds of requests.post() calls to Slack’s webhook API are queued in the same thread that is supposed to be processing new log entries. Slack rate-limits at one message per second. The detection loop stalls. The attacker is not just bypassing the blocking logic — they are causing the defender’s processing to slow down at the exact moment speed matters most.</p><p><strong>Baseline cold-start creates a false positive window.<br></strong> At startup, effective_mean = 1.0 and effective_stddev = 0.5. The first recalculation runs sixty seconds later. During that window, the rate multiplier threshold is 5 × 1.0 = 5 req/s. A Nextcloud mobile client syncing a photo album on first launch can hit six requests per second. The system bans a legitimate user before it has any real data to reason from.</p><p><strong>iptables rules do not survive reboots.<br></strong> iptables rules live in kernel memory. A server reboot clears them. Permanent bans are not permanent. An attacker who can trigger a reboot — through a separate vulnerability, through resource exhaustion, through an OOM kill — resets to a clean slate.</p><p><strong>No input validation before subprocess execution.<br></strong> In blocker.py, the IP string from the parsed log entry is passed directly into subprocess.run([“iptables”, “-A”, “INPUT”, “-s”, ip, “-j”, “DROP”]). The list invocation of subprocess.run prevents shell injection, but the iptables binary itself interprets its arguments. A crafted log entry with a malformed IP string produces a silent failure. There is no validation that the source_ip field from the Nginx JSON log actually contains a valid IP address before it enters the execution path.</p><p><strong>The dashboard has no authentication.<br></strong> Port 8081 is open to anyone who can reach the host. The /metrics endpoint returns current ban state, top IPs by request rate, baseline mean, and baseline standard deviation. This is a calibration guide for an attacker. Knowing the current effective mean tells them exactly how much traffic they can send while staying below the detection threshold.</p><h3><strong>New Features for V2</strong></h3><h4>2.1 Persistent State via Redis</h4><p>The single most impactful change in V2 is moving all detection state out of Python process memory and into Redis.</p><p><strong>What this actually changes:</strong> Ban records, escalation levels, sliding window data, and baseline statistics survive container restarts, redeployments, and process crashes. An IP serving a permanent ban stays banned. An IP on its third offence retains its escalation level.</p><p><strong>How sliding windows map onto Redis data structures:</strong> Per-IP and global windows are stored as Redis sorted sets. The key is window:ip:{ip} or window:global. Each entry uses the Unix timestamp as the score and request count as the value. Adding a new entry is ZADD. Evicting entries older than sixty seconds is ZREMRANGEBYSCORE key 0 {cutoff}. The current window size is ZCARD. These three operations execute in O(log N) in the Redis kernel, and the entire add-and-evict cycle for a single request is one round trip with a pipeline.</p><p><strong>How ban state maps onto Redis:</strong> Each banned IP is stored as a Redis Hash at ban:{ip} with fields for banned_at, level, duration, and active. For time-limited bans, the key is given a TTL matching the ban duration. When the key expires, Redis removes it atomically. The unbanner thread — a source of race conditions in V1 — is no longer needed for time-limited bans. Permanent bans are stored without TTL and require explicit deletion.</p><p><strong>Trade-off:</strong> Redis adds approximately 0.1ms of latency per window operation compared to in-process memory. At five hundred requests per second, this adds fifty milliseconds of cumulative Redis overhead per second across all window operations. For this use case — where the detection decision takes milliseconds and the enforcement action takes tens of milliseconds — this is acceptable. The operational cost is real: Redis becomes a dependency that must be monitored, backed up, and sized. For a deployment where container restarts are genuinely rare and false negatives (re-allowing a banned IP) are acceptable, in-memory state is simpler. The recommendation is Redis for any deployment where the ban list represents real security policy.</p><h4><strong>2.2 Robust Baseline Estimation Resistant to Poisoning</strong></h4><p>The core statistical problem in V1 is that mean and standard deviation are not resistant to adversarial samples. The fix is to use estimators that are.</p><p><strong>Median and Median Absolute Deviation (MAD)</strong> are the replacements. The median is the middle value of the sorted dataset — half of observations fall above it, half below. It is not pulled by outliers. A dataset where eighty percent of values represent legitimate traffic at eight requests per second and twenty percent represent attack traffic at forty requests per second: the mean shifts significantly toward forty. The median stays near eight, because the attack traffic does not constitute a majority of the data points.</p><p>MAD is the median of the absolute deviations from the median. Scaled by the constant 1.4826, it approximates the standard deviation for normally distributed data while remaining resistant to the same outliers that distort standard deviation.</p><p>The recalculation becomes:</p><pre>counts_sorted = sorted(counts)<br>median = statistics.median(counts_sorted)<br>mad = statistics.median([abs(x - median) for x in counts_sorted])<br>self.effective_mean = max(median, 1.0)<br>self.effective_stddev = max(1.4826 * mad, 0.5)</pre><p>The Z-score formula is unchanged. Only the estimators feeding it changes.</p><p><strong>Second-order defence meta-anomaly on the baseline itself:</strong> V2 monitors the baseline for drift. If effective_mean increases more than fifty percent within any ten-minute window, a BASELINE_DRIFT event is emitted to the notification queue. This fires when either an ongoing attack is inflating the baseline (bad) or when legitimate traffic has genuinely grown substantially (worth knowing). The alert does not trigger a block — it triggers operator awareness.</p><p><strong>Trade-off:</strong> Sorting the counts array is O(N log N) versus O(N) for mean calculation. On an 1800-element array, this is approximately twenty thousand comparisons instead of 1,800 additions. At a sixty-second recalculation interval, the cost is imperceptible. The statistical benefit is substantial.</p><h4><strong>2.3 TLS and TCP Fingerprinting as Auxiliary Detection Signal</strong></h4><p>IP addresses are rotatable. TLS ClientHello parameters are not as easily rotatable — they are a property of the specific TLS library version and its configuration.</p><p>Every TLS client sends a ClientHello message during handshake. The cipher suites it offers, the extensions it includes, the elliptic curves it prefers, the compression methods it supports — these collectively produce a fingerprint that is characteristic of the client’s TLS library. A Python requests client looks different from Chrome. Chrome on Windows looks different from Chrome on Android. curl with default settings looks different from all of them. The MD5 hash of these ClientHello fields is the <strong>JA3 fingerprint</strong>.</p><p>Most commodity botters — those running Python scripts, simple Go HTTP clients, or Selenium without stealth patches — produce JA3 fingerprints that do not match any common browser. This is a strong signal that does not require rate analysis to trigger.</p><p><strong>Important caveat:</strong> This is not a hard defence. Tools like tls-client, curl-impersonate, and uTLS allow applications to impersonate specific browser TLS fingerprints. These tools are publicly available and increasingly documented. A motivated attacker who knows about fingerprinting will bypass it. Fingerprinting is a pre-filter against the unsophisticated majority, not a primary defence against sophisticated adversaries.</p><p><strong>How V2 captures JA3:</strong> Nginx with the ngx_ssl_ja3 module injects the JA3 hash as a custom request header. The Nginx log format is extended to include it:</p><pre>&quot;ja3&quot;:&quot;$http_x_ja3_fingerprint&quot;</pre><p>The detector maintains a five-minute sliding window of request counts per JA3 fingerprint, stored in Redis. Any fingerprint that does not appear in the known-legitimate allowlist — maintained as a config file updated quarterly with current browser fingerprints — and accounts for more than fifteen percent of recent traffic has its Z-score detection threshold tightened from 3.0 to 1.8.</p><p><strong>TCP fingerprinting via p0f:</strong> TCP stack behaviour — initial window size, TTL, MSS, option ordering — reflects the underlying OS and is not controllable by the application layer. p0f runs as a passive sidecar, reading from the network interface and writing OS classifications to a Unix socket. When a single IP appears to be using multiple distinct OS fingerprints within a ten-minute window, it indicates proxy rotation across machines with different operating systems. This is stored in Redis at ip:os_fingerprints:{ip} as a sorted set and triggers a reduced Z-score threshold for subsequent requests from that IP.</p><h4><strong>2.4 Replacing network_mode: host with nftables via Socket</strong></h4><p><strong>The problem this solves:</strong> The entire reason V1 uses host networking is to run iptables commands. The fix is to use nftables, which supports a control socket that can be bind-mounted into a container without exposing the host network stack.</p><p><strong>How it works:</strong> The nftables socket at /run/nftables.sock is bind-mounted into the detector container with read-write permissions scoped to the detector’s UID. The container retains cap_add: NET_ADMIN — unavoidable for firewall operations — but runs in its own network namespace. A compromise of the detector process no longer gives access to the host’s entire network stack.</p><p><strong>Additional benefit — O(1) IP lookups:</strong> iptables performs a linear scan through all rules. At ten thousand concurrent bans, every incoming packet evaluation scans ten thousand entries. nftables with ipset stores IPs in a kernel-space hash table with O(1) lookup regardless of set size. At the same ten thousand bans, lookup takes under one microsecond.</p><p><strong>Timeout-based enforcement:</strong> nftables set elements support native TTL. A ban with a thirty-minute duration is expressed as:</p><p>nft add element inet filter blocked_ips { 203.0.113.42 timeout 30m }</p><p>The kernel expires the element automatically. No unbanner thread. No race conditions between the ban check and the unban operation.</p><h3><strong>Production Readiness</strong></h3><h4>Security</h4><p>The most important security change in V2 is the removal of network_mode: host. This single change meaningfully reduces the blast radius of a detector compromise from “host network stack compromised” to “firewall ruleset manipulated” — a serious incident, but a contained one.</p><p>The Slack webhook URL moves from an environment variable to a Docker secret mounted at /run/secrets/slack_webhook. Environment variables appear in docker inspect output, in container logs, and in process memory dumps. A leaked webhook URL lets an attacker flood the security channel with fake alerts or delete the audit trail. Docker secrets are mounted as tmpfs and never appear in inspect output.</p><p>The dashboard endpoint requires Bearer token authentication. The token is generated at startup and stored in Redis with a 24-hour TTL. Unauthenticated requests to /metrics receive a 401. The information currently exposed — baseline mean, ban list, top IPs by rate — is calibration data for an attacker and should not be publicly accessible.</p><p>All IP addresses from log entries are validated through ipaddress.ip_address() before any downstream operation. Invalid entries increment a Prometheus counter and are logged as structured warnings. An anomalous spike in that counter signals a possible log injection attempt.</p><h4>Scalability</h4><p>The detection hot path — log parsing, window update, Z-score calculation — is CPU-bound. Python’s GIL limits threading to one core. V2 runs multiple detector worker processes using ProcessPoolExecutor, each maintaining a local cache of effective_mean and effective_stddev refreshed every ten seconds from Redis. Window operations go directly to Redis. The notification path is fully decoupled: ban decisions push a JSON event to a Redis List, and a dedicated NotifierWorker process drains the queue at a controlled rate. The main detection loop never touches the Slack API.</p><p>Nginx-level rate limiting via ngx_http_limit_req_module caps each source IP at one hundred requests per second before requests enter the detection pipeline. This prevents the detector’s event queue from being overwhelmed before the statistical logic can respond.</p><h4>Observability</h4><p>V1’s audit logger writes flat text. V2 emits structured JSON to stdout for every security event:</p><pre>{<br>  &quot;ts&quot;: &quot;2026–06–01T14:32:11.402Z&quot;,<br>  &quot;event&quot;: &quot;ban&quot;,<br>  &quot;ip&quot;: &quot;203.0.113.42&quot;,<br>  &quot;condition&quot;: &quot;z-score&quot;,<br>  &quot;rate_rps&quot;: 47.3,<br>  &quot;baseline_mean&quot;: 8.1,<br>  &quot;z_score&quot;: 7.4,<br>  &quot;ban_level&quot;: 2,<br>  &quot;duration_min&quot;: 120,<br>  &quot;ja3&quot;: &quot;a0e9f5d64349fb13191bc781f81f42e1&quot;,<br>  &quot;instance_id&quot;: &quot;detector-1&quot;<br>}</pre><p>Core Prometheus metrics exposed at <strong>/metrics</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftAv6E152KH20BjSeA0QSA.png" /></figure><p>Alerting thresholds that matter: ban rate above fifty per minute for more than two minutes triggers PagerDuty — this is an active DDoS. False positive ratio above ten percent for more than five minutes triggers a Slack warning — the thresholds need tuning. Baseline mean increasing more than fifty percent in ten minutes triggers a Slack warning — possible statistical poisoning in progress. Redis connection loss triggers PagerDuty — the state layer is down and bans are not persisting.</p><h3><strong>Tech Stack Decisions</strong></h3><p><strong>Python 3.12</strong> is retained. The detection logic is non-trivial and the team has full context on it. Python 3.12 introduced per-interpreter GIL improvements (PEP 703) that enable true multi-core parallelism in the ProcessPoolExecutor used for V2’s worker model. The bottleneck at the expected traffic scale — under five thousand requests per second — is not the language. It is the lock contention and in-process state from V1.</p><p><strong>Redis 7.x</strong> was chosen over PostgreSQL for the detection state layer based on three specific properties. First, Redis sorted sets map directly onto the sliding window’s add-and-evict pattern in a way that a relational model does not. A PostgreSQL equivalent requires a transaction, a timestamped delete, an insert, and a count — four round trips. Redis does it in one. Second, native TTL support on hash keys eliminates the unbanner thread entirely for time-limited bans. Third, Redis pub/sub enables sub-millisecond ban propagation between detector instances. The trade-off is operational: Redis is a dependency that needs to be monitored and sized. For this use case — where the read/write ratio is heavily write-dominated during attacks and sub-millisecond latency matters — it is the right choice.</p><p><strong>nftables with ipset</strong> replaces iptables. The practical difference: at ten thousand concurrent bans, iptables evaluates every incoming packet against a linked list of ten thousand rules. ipset uses a kernel hash table. The lookup is O(1) regardless of set size, measured under one microsecond. The operational difference: nftables supports atomic ruleset transactions. iptables inserts rules one at a time with a brief window of partial application between steps. nftables eliminates that window. Both differences compound under attack conditions — the exact scenario where performance and correctness matter most.</p><p><strong>FastAPI + Uvicorn</strong> replaces Flask for the metrics endpoint. Flask’s default WSGI server is single-threaded. Concurrent dashboard requests queue behind each other. FastAPI with Uvicorn runs an async event loop on top of uvloop — concurrent /metrics requests are handled by coroutine context switches rather than thread overhead. The metrics endpoint is read-heavy under monitoring conditions and benefits directly from this model.</p><p><strong>Median and MAD</strong> replace mean and standard deviation in the baseline engine. This is not a preference — it is the correct statistical choice when the input data may include adversarial samples. Mean and standard deviation are not robust estimators. Median and MAD are. The computational cost difference is negligible at the recalculation intervals used here.</p><h3><strong>What V2 Still Does Not Solve</strong></h3><p>This document should be honest about the scope.</p><p><strong>Sophisticated proxy rotation at scale.</strong> MAD-based baselines and CIDR aggregation raise the cost of a proxy-based attack significantly. They do not eliminate it. A well-resourced attacker with a residential proxy pool spanning geographically distributed /24 subnets can evade subnet-level blocking while staying below the global rate trigger. At that point, the required defences move outside the scope of a network-layer daemon: application-layer behavioural analysis, CAPTCHA friction for suspicious sessions, and upstream BGP filtering via the hosting provider. These are not included here.</p><p><strong>Fingerprint impersonation.</strong> JA3 spoofing tools are freely available. The fingerprinting layer described here filters commodity bots. A motivated attacker who profiles the allowlist and configures tls-client to match an allowlisted fingerprint bypasses it entirely. The correct framing is that fingerprinting is a pre-filter that reduces load on the statistical detector — not a primary defence in its own right.</p><p><strong>Volumetric attacks that saturate upstream bandwidth.</strong> If attack traffic exceeds the VPS’s network capacity, traffic never reaches the detector. The entire system is bypassed at the provider level. BGP blackhole routing from the hosting provider is required. This is outside the scope of application-layer anomaly detection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85afeeadb5da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring with Grafana]]></title>
            <link>https://medium.com/@akinolatofunmi/monitoring-with-grafana-bfeffb568861?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfeffb568861</guid>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Tue, 19 May 2026 09:47:25 GMT</pubDate>
            <atom:updated>2026-05-20T11:27:56.703Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern software engineering, knowing that your service is running is not enough. We need to know <em>how well</em> it is running, <em>how fast</em> your team responds when it breaks, and <em>how reliably</em> it serves users over time. This is a documentation of how I built a production-grade observability and reliability platform from scratch, one that goes beyond simple uptime monitoring into user-centric reliability engineering.</p><p>The platform monitors a real production application (api.clinsight.hng14.com) running on a separate app server, using the full LGTM stack — Loki, Grafana, Tempo, and Prometheus — deployed entirely as Infrastructure as Code via Terraform.</p><h3>Architecture Overview</h3><p>The platform consists of two servers:</p><p><strong>Monitoring VPS (</strong><strong>157.180.45.114)</strong> — hosts the full observability stack:</p><ul><li>Prometheus (metrics)</li><li>Loki (logs)</li><li>Tempo (traces)</li><li>Grafana (unified dashboard)</li><li>Alertmanager (alert routing)</li><li>Node Exporter (monitoring VPS host metrics)</li><li>Blackbox Exporter (HTTP probing)</li><li>OpenTelemetry Collector (log and trace shipping)</li><li>GitHub Actions Exporter (DORA metrics)</li><li>SSH Tunnel Container (connects to app server Node Exporter)</li></ul><p><strong>App Server (</strong><strong>16.171.47.26)</strong> — hosts the clinsight application:</p><ul><li>clinsight API (Python/Django, managed by PM2)</li><li>Node Exporter (app server host metrics, accessed via SSH tunnel)</li><li>OpenTelemetry Collector (ships PM2 logs to Loki)</li></ul><pre>App Server (16.171.47.26)                Monitoring VPS (157.180.45.114)<br>────────────────────────                 ──────────────────────────────<br>clinsight API ──── PM2 logs ──────────── OTel Collector ──► Loki<br>Node Exporter ──── SSH tunnel ────────── app-server-tunnel ──► Prometheus<br>                                         Blackbox ──► probe_success, latency<br>                                         Node Exporter ──► VPS host metrics<br>                                         GitHub Actions Exporter ──► DORA                                        Prometheus ──► Grafana<br>                                         Alertmanager ──► #DevOps-Alerts (Slack)</pre><h3>Part 1: Why LGTM Over Managed Alternatives?</h3><p>Before building, I evaluated managed alternatives: Datadog, New Relic, Grafana Cloud. The decision to self-host came down to three factors:</p><p><strong>Cost at scale.</strong> Managed platforms charge per host, per metric, or per log line. At production scale, this becomes significant. The LGTM stack runs on a single VPS with a fixed monthly cost.</p><p><strong>Data ownership.</strong> Production logs often contain sensitive user data. Self-hosting means logs never leave your infrastructure.</p><p><strong>Full control.</strong> Managed platforms abstract away configuration. Understanding the full stack — how Loki stores log chunks, how Tempo builds trace spans, how Prometheus evaluates alert rules — makes you a better engineer and gives you full control over retention, cardinality, and performance.</p><h3>Part 2: Infrastructure as Code — One Command Deployment</h3><p>Every component is provisioned via Terraform. No manual configuration. No clicking in UIs. One command brings the entire stack up:</p><pre>terraform apply -var-file=&quot;terraform.tfvars&quot; -auto-approve</pre><p>This provisions:</p><ul><li>Docker network (monitoring) shared by all containers</li><li>All 9 monitoring containers with correct dependencies</li><li>SSH tunnel container for app server connectivity</li><li>Node Exporter installation on the app server via remote-exec provisioner</li><li>Alertmanager config generated from template with real secrets injected</li></ul><p>The alertmanager.yml is never committed to Git with real secrets. Terraform uses templatefile() to generate the config at apply time, substituting the Slack webhook URL from terraform.tfvars (gitignored).</p><p>A key challenge was connecting to the app server — its Security Group blocks inbound connections on port 9100. The solution was an SSH tunnel container running inside the monitoring Docker network, connecting via port 22 (which IS allowed) and forwarding Node Exporter metrics to app-server-tunnel:9100 — accessible to Prometheus by container name.</p><h3>Part 3: The Four Golden Signals as SLIs</h3><p>Before building any dashboard, I defined what reliability means for the clinsight service using Google’s Four Golden Signals framework.</p><h3>1. Latency</h3><p>How long does it take to serve a request? We measure the total HTTP probe duration broken down by phase: DNS resolution, TCP connection, TLS handshake, server processing, and data transfer.</p><pre># Total response time<br>sum(probe_http_duration_seconds{job=&quot;blackbox&quot;}) * 1000<br># Individual phase breakdown<br>probe_http_duration_seconds{job=&quot;blackbox&quot;, phase=&quot;processing&quot;}</pre><p>We distinguish successful request latency (2xx responses with normal timing) from error latency (failed probes with timeout).</p><h3>2. Traffic</h3><p>How much demand is the system handling? The Blackbox Exporter probes the health endpoint every 15 seconds. For application-level request rates, the clinsight app exposes these metrics via its own instrumentation.</p><pre># Probe rate (requests per second to health endpoint)<br>rate(probe_http_duration_seconds_count{job=&quot;blackbox&quot;}[5m])</pre><h3>3. Errors</h3><p>Rate of failed requests. We track explicit failures (non-2xx responses) via probe_success:</p><pre># Error rate SLI<br>1 - avg_over_time(probe_success{job=&quot;blackbox&quot;}[$__range])</pre><h3>4. Saturation</h3><p>How “full” is the system? We track CPU, memory, disk, and network I/O on both the monitoring VPS and the app server:</p><pre># CPU saturation (app server)<br>100 - (avg by (instance) (rate(node_cpu_seconds_total{mode=&quot;idle&quot;, instance=&quot;app-server&quot;}[5m])) * 100)<br># Memory saturation<br>(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100</pre><h3>Part 4: SLIs, SLOs, and Error Budgets</h3><h3>Defining SLOs</h3><p>For each SLI, I defined a target with reasoning:</p><p>SLI SLO Target Window Reasoning Availability 99.5% 30 days Allows 216 minutes downtime/month — realistic for a team without 24/7 on-call Latency (p95 &lt; 500ms) 95% 30 days Healthcare APIs must be responsive; 500ms is the UX threshold for perceived lag Error Rate 99% 30 days 1% error tolerance allows for transient failures without burning budget</p><h3>Error Budget Calculation</h3><pre>SLO: 99.5% availability over 30 days<br>Error Budget = (1 - 0.995) × 30 × 24 × 60<br>             = 0.005 × 43,200<br>             = 216 minutes</pre><p>216 minutes is our monthly allowance for downtime. Every minute the service is down costs 1 minute of budget.</p><h3>Burn Rate Alerting — Why It Reduces Alert Fatigue</h3><p>Traditional alerting fires when something is broken. Burn rate alerting fires when you are spending your reliability budget too fast — even if the service appears mostly up.</p><p><strong>Fast Burn (14.4x over 1 hour):</strong><br> At 14.4x burn rate, you exhaust the monthly budget in ~2 days. This number comes from:</p><pre>Budget: 216 minutes over 720 hours = 0.3 minutes/hour normal rate<br>To exhaust in 50 hours (2 days): need 216/50 = 4.32 min/hour<br>Burn rate: 4.32 / 0.3 = 14.4x</pre><p><strong>Slow Burn (5x over 6 hours):</strong><br> At 5x burn rate over 6 hours, the budget would exhaust in ~6 days — not immediately critical but needs attention before escalating.</p><p>This two-window approach catches both sudden outages (fast burn) and gradual degradation (slow burn) while dramatically reducing alert noise compared to threshold-based alerting.</p><h3>Error Budget Policy</h3><p>The full policy lives at runbooks/error-budget-policy.md. Key decision points:</p><ul><li><strong>50% consumed</strong> — team review, investigate root causes</li><li><strong>75% consumed</strong> — slow down deployments, prioritise reliability</li><li><strong>100% consumed</strong> — feature freeze, mandatory reliability sprint</li></ul><h3>Part 5: DORA Metrics — Connecting Engineering Performance to Business Outcomes</h3><p>DORA (DevOps Research and Assessment) identified four metrics that consistently predict both team performance and business outcomes. I built a custom GitHub Actions exporter that queries the hngprojects/clinical-api public repository API and exposes these as Prometheus metrics.</p><h3>The Four Metrics</h3><p><strong>Deployment Frequency</strong> — How often code reaches production. Elite teams deploy multiple times per day. More frequent deployments mean smaller changes, lower risk, faster feedback.</p><p><strong>Lead Time for Changes</strong> — From commit to production. Short lead times mean bugs surface quickly and fixes reach users faster.</p><p><strong>Change Failure Rate</strong> — Percentage of deployments causing incidents. High CFR means the deployment process lacks adequate testing or review.</p><p><strong>Mean Time to Restore</strong> — When something breaks, how fast is recovery? Low MTTR means strong incident response processes.</p><h3>Identifying Toil</h3><p>Reviewing the deployment process revealed two significant sources of toil:</p><p><strong>Toil 1 — Manual deployment verification.</strong> After each deployment, someone SSHs into the server to verify the service is healthy. Automated health checks and structured alert notifications eliminate this.</p><p><strong>Toil 2 — Manual incident correlation.</strong> During incidents, engineers manually correlate metrics, logs, and traces across separate tools. The unified Grafana dashboard with log-to-trace correlation eliminates this — a metric spike, correlated logs, and the causing trace are all one click away.</p><h3>Part 6: Log Shipping Architecture</h3><p>Getting logs from the clinsight app server (running PM2) into Loki required a two-part setup:</p><p><strong>On the app server:</strong> An OpenTelemetry Collector reads PM2 log files from ~/.pm2/logs/*.log and ships them to Loki on the monitoring VPS via OTLP HTTP.</p><p><strong>On the monitoring VPS:</strong> An OpenTelemetry Collector (running as a Docker container with user: &quot;0&quot; for file access) reads Docker container log files from /var/lib/docker/containers/*/*.log and ships them to Loki.</p><p>A critical Loki 3.7.2 requirement that caused extended debugging: allow_structured_metadata: true must be set in limits_config. Without it, Loki accepts OTLP requests but silently discards the data — no error, no acknowledgment, just empty streams. This took significant debugging to identify.</p><p>The logs panel in the unified dashboard queries:</p><pre>{service_name=&quot;clinsight&quot;}</pre><h3>Part 7: Five Grafana Dashboards</h3><p>All five dashboards are provisioned as JSON files — never manually configured in the UI. This ensures reproducibility and version control.</p><h3>Dashboard 1 — Node Exporter</h3><p>CPU (total and per-core), memory (used/cached/available), disk I/O, network I/O, and system load averages for both the monitoring VPS and the app server. The instance dropdown allows switching between monitoring-vps and app-server.</p><h3>Dashboard 2 — Blackbox Exporter</h3><p>Uptime/downtime timeline, HTTP response time breakdown by phase (DNS, TCP, TLS, processing, transfer), probe success rate, and SSL expiration countdown.</p><h3>Dashboard 3 — SLO &amp; Error Budget</h3><ul><li>Availability SLI gauge with 99.5% target line</li><li>Error budget remaining (clamped 0–100%)</li><li>Fast burn rate time series (14.4x threshold line)</li><li>Slow burn rate time series (5x threshold line)</li><li>Probe success history</li></ul><p>The dashboard uses Grafana’s $__range variable so panels adapt to the selected time range rather than hardcoding a fixed window that produces meaningless values when insufficient data exists.</p><h3>Dashboard 4 — DORA Metrics</h3><p>Deployment frequency with ELITE/HIGH/MEDIUM/LOW classification, change failure rate gauge, lead time stat, and MTTR stat. The time picker is hidden since DORA metrics are always measured over a fixed 30-day rolling window.</p><h3>Dashboard 5 — Unified Observability (Log &amp; Trace Correlation)</h3><p>The most important dashboard. A single view showing:</p><ul><li>Live endpoint health (UP/DOWN)</li><li>Current response time</li><li>CPU and memory usage</li><li>Current burn rate</li><li>Probe success history over time</li><li>Response time breakdown by phase</li><li>Application log stream (clinsight PM2 logs via Loki)</li><li>Traces panel (Tempo — ready for when the application is instrumented)</li></ul><p>The Loki datasource is configured with derived fields that detect trace_id= patterns in log lines and render them as clickable links to Tempo — enabling one-click drill-down from a log entry to the full request trace.</p><h3>Part 8: Alerting System</h3><h3>Alert Rules (Version Controlled)</h3><p>All alert rules live in prometheus/rules/ — never in Grafana&#39;s UI. Three rule files:</p><p><strong>infrastructure.yml</strong> — 7 rules covering CPU (warning &gt;80% for 5m, critical &gt;90% for 10m), memory, disk, and server downtime via Blackbox probe.</p><p><strong>slo.yml</strong> — 2 burn rate rules covering fast burn (14.4x over 1h, critical) and slow burn (5x over 6h, warning).</p><p><strong>cicd.yml</strong> — 2 DORA rules covering high change failure rate (&gt;15% over 30d) and high MTTR (&gt;60 minutes average).</p><h3>Alertmanager Routing</h3><p>Routes group alerts by alertname and severity. Critical alerts go to slack-notifications-critical receiver, warnings to slack-notifications-warning. Both send to #DevOps-Alerts.</p><p><strong>Inhibition rules</strong> prevent noise: when ServerDown fires for an instance, all CPU, Memory, Disk, and SLO alerts for that same instance are suppressed. One notification instead of twenty.</p><h3>Structured Slack Payloads</h3><p>Every alert notification includes:</p><ul><li>Alert name and severity</li><li>Host/instance affected</li><li>Current metric value</li><li>Direct link to the relevant Grafana dashboard</li><li>Direct link to the runbook</li><li>Firing/resolved status with timestamp</li></ul><p>Plain text notifications were explicitly rejected — structured payloads with dashboard and runbook links allow the responding engineer to go from notification to root cause without any additional context gathering.</p><h3>Part 9: Incident Management</h3><h3>Runbooks</h3><p>Eleven runbooks cover every alert rule. Each answers:</p><ol><li>What is this alert?</li><li>What are the likely causes?</li><li>First 3 investigation steps (with exact commands)</li><li>How to resolve</li><li>When and whether to roll back</li><li>When and to whom to escalate</li></ol><h3>Blameless Post-Incident Review</h3><p>A simulated incident (INC-001) documented a complete deployment failure where a missing environment variable caused a 47-minute outage, consuming 21.8% of the monthly error budget. Key findings:</p><ul><li>The observability stack detected the outage within 2 minutes</li><li>Slack notification was structured and actionable</li><li>Rollback decision was made quickly</li><li>Root cause was a process gap (no env var checklist), not an individual error</li></ul><p>Action items focused on automating the missing validation step — adding a post-deployment health check to GitHub Actions and an environment variable validation step to the CI pipeline.</p><h3>Part 10: Game Day — Chaos and Failure Simulation</h3><h3>Scenario 1 — Deployment Failure</h3><p>A broken commit was pushed to hngprojects/clinical-api triggering a failing GitHub Actions workflow. The DORA exporter detected the failure within 5 minutes, CFR increased in the dashboard. The HighChangeFailureRate alert was configured to fire when CFR exceeds 15% over 30 days.</p><p><strong>Timeline:</strong></p><ul><li>Broken commit pushed to test branch</li><li>GitHub Actions pipeline failed (visible in Actions UI)</li><li>DORA exporter updated CFR metric within 5 minutes</li><li>DORA dashboard reflected the change</li></ul><h3>Scenario 2 — Latency Injection</h3><p>Network latency was injected on the app server using tc netem:</p><pre>sudo tc qdisc add dev ens5 root netem delay 3000ms</pre><p>The Blackbox response time panels showed a spike from ~50ms to ~3000ms. To trigger a real burn rate alert, Nginx was temporarily stopped — probe_success dropped to 0, burn rate spiked above 14.4x, and the SloBurnRateFast critical alert fired in Slack within 2 minutes.</p><p><strong>Timeline:</strong></p><ul><li>3s latency injected — response time spiked in Blackbox dashboard</li><li>Nginx stopped — probe_success = 0</li><li>Burn rate spiked to &gt;14.4x</li><li>SloBurnRateFast fired in #DevOps-Alerts (2 minutes after first failure)</li><li>Nginx restarted — probe_success = 1</li><li>Burn rate recovered</li><li>Resolved notification sent to Slack</li></ul><h3>Scenario 3 — Resource Pressure</h3><p>CPU was stressed on the app server using stress-ng:</p><pre>sudo stress-ng --cpu 4 --timeout 360s</pre><p>The Node Exporter dashboard (app-server instance) showed CPU climbing above 80% and sustained above 90%.</p><p><strong>Timeline:</strong></p><ul><li>Baseline screenshot: CPU ~15% (normal)</li><li>stress-ng started</li><li>CPUUsageHigh (warning, &gt;80% for 5m) fired in Slack — 5 minutes after crossing threshold</li><li>CPUUsageCritical (critical, &gt;90% for 10m) fired in Slack — 10 minutes after crossing threshold</li><li>stress-ng stopped after 6 minutes</li><li>CPU recovered to baseline</li><li>Both alerts resolved, recovery notifications sent to Slack</li></ul><h3>Part 11: Key Lessons Learned</h3><p><strong>1. Loki 3.x OTLP requires </strong><strong>allow_structured_metadata: true.</strong> Without it, Loki silently discards OTLP data — no error, no warning. This took hours to debug.</p><p><strong>2. OpenTelemetry Collector runs as non-root by default.</strong> The otel/opentelemetry-collector-contrib image uses UID 10001. Mounting Docker log files (owned by root) requires user: &quot;0&quot; in the container configuration.</p><p><strong>3. Docker container networking and the host are isolated.</strong> SSH tunnels bound to localhost on the host are not reachable from Docker containers. Running the tunnel as a Docker container on the monitoring network eliminates this — containers reach each other by name, bypassing host networking entirely.</p><p><strong>4. SLO windows need real data.</strong> Using 30-day windows when the stack has only been running for hours produces meaningless (often negative) values. Using Grafana’s $__range variable makes dashboards useful from day one.</p><p><strong>5. Burn rate alerting is fundamentally different from threshold alerting.</strong> A threshold alert fires when something IS broken. A burn rate alert fires when you are CONSUMING YOUR RELIABILITY BUDGET too fast — even if individual requests mostly succeed. This catches gradual degradation that threshold alerts miss entirely.</p><h3>Conclusion</h3><p>Building this platform from scratch provided deep insight into how production reliability is actually managed at engineering organisations that take it seriously. The key insight is that reliability is not a binary — it is a budget. You are allowed to fail, but you must manage how much failure you permit and respond proportionally when the budget is threatened.</p><p>The LGTM stack provides the observability to answer any question about system behaviour. The SLO framework provides the structure to decide what matters and what does not. The DORA metrics provide the feedback loop to continuously improve the engineering process itself.</p><p>All code, configs, runbooks, and dashboards are available at:<br> <a href="https://github.com/carvanino/observability-platform"><strong>https://github.com/carvanino/observability-platform</strong></a></p><h3>Repository Structure</h3><pre>observability-platform/<br>├── terraform/          # IaC — one command deployment<br>├── prometheus/         # Scrape config + alert rules<br>├── loki/               # Log storage config<br>├── tempo/              # Trace storage config<br>├── alertmanager/       # Alert routing + Slack templates<br>├── otel/               # Log and trace shipping pipeline<br>├── grafana/            # Dashboards (JSON) + datasources<br>├── github-exporter/    # Custom DORA metrics exporter<br>├── ssh-tunnel/         # App server connectivity container<br>└── runbooks/           # 11 alert runbooks + PIR + error budget polic</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfeffb568861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building SwiftDeploy: A CLI That Writes Its Own Infrastructure, Enforces Policy, and Watches Itself]]></title>
            <link>https://medium.com/@akinolatofunmi/building-swiftdeploy-a-cli-that-writes-its-own-infrastructure-enforces-policy-and-watches-itself-97b12606695c?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b12606695c</guid>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Wed, 06 May 2026 20:52:10 GMT</pubDate>
            <atom:updated>2026-05-07T14:05:36.855Z</atom:updated>
            <content:encoded><![CDATA[<p>Most DevOps tutorials teach you how to configure infrastructure manually. You write a docker-compose.yml, an nginx.conf, maybe a health check — and you&#39;re done. But what happens when you have multiple environments? When thresholds change? When a new engineer joins and has no idea which files to edit?</p><p>In this post, I’ll walk you through how I built <strong>SwiftDeploy, </strong>a CLI tool that generates all its own infrastructure files from a single manifest, enforces deployment policies using Open Policy Agent, and provides live observability through a Prometheus metrics endpoint. By the end, you’ll understand every design decision and be able to build something similar yourself.</p><h3>What We’re Building</h3><p>SwiftDeploy has two parts:</p><p><strong>The Engine:</strong> A CLI that reads a manifest.yaml and generates nginx.conf and docker-compose.yml from templates. It manages the full container lifecycle with five subcommands: init, validate, deploy, promote, and teardown.</p><p><strong>The Eyes and Brain:</strong> The engine gains observability (a /metrics endpoint in Prometheus format), a policy enforcement layer using OPA, and two new commands: status (a live terminal dashboard) and audit (generates a markdown report from history).</p><p>The architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dgPdsdlgd6hsLFwYfo-1A.png" /></figure><h3>Part 1 — The Design: A Tool That Writes Its Own Files</h3><h4>The Core Idea: Declarative Infrastructure</h4><p>The problem with handwriting config files is that they become stale. Someone changes the port in docker-compose.yml but forgets to update nginx.conf. Or a new service gets added and the network config is wrong. When config files are written by hand, inconsistencies creep in.</p><p>The solution is to make manifest.yaml the single source of truth and have the tool generate everything else from it:</p><pre>services:<br>  image: swift-deploy-1-node:latest<br>  port: 3000<br>  mode: stable<br>  version: &quot;1.0.0&quot;<br><br>nginx:<br>  image: nginx:latest<br>  port: 8080<br>  proxy_timeout: 30<br><br>network:<br>  name: swiftdeploy-net<br>  driver_type: bridge</pre><p>This is the only file you ever touch. Everything else, nginx config, compose file, OPA policies data, derives from it.</p><h4>Templates with Jinja2</h4><p>The generated files come from Jinja2 templates. Instead of hardcoding values, templates have placeholders:</p><pre>server {<br>    listen {{ nginx_port }};<br>    <br>    location / {<br>        set $upstream http://app:{{ service_port }};<br>        proxy_pass $upstream;<br>    }<br>}</pre><p>When swiftdeploy init runs, it reads the manifest, builds a context dictionary, and renders each template:</p><pre>def cmd_init():<br>    manifest = load_manifest()<br>    context  = build_context(manifest)<br>    <br>    nginx_conf = render_template(&quot;nginx.conf.j2&quot;, context)<br>    with open(&quot;nginx.conf&quot;, &quot;w&quot;) as f:<br>        f.write(nginx_conf)</pre><p>The result is that deleting the generated files and re-running init always reproduces them identically — the manifest is the truth, not the generated files.</p><h4>An Interesting Nginx Problem</h4><p>When testing the generated nginx config with nginx -t, I hit an error:</p><pre>host not found in upstream &quot;app&quot;</pre><p>Nginx tries to resolve every hostname in proxy_pass directives at startup. But app only exists inside the Docker network, it is a service name, not a real hostname. Outside Docker, it does not resolve.</p><p>The fix is to use a variable for the upstream, which defers DNS resolution to request time:</p><pre>resolver 127.0.0.11 valid=30s;<br><br>location / {<br>    set $upstream http://app:{{ service_port }};<br>    proxy_pass $upstream;<br>}</pre><p>127.0.0.11 is Docker&#39;s built-in DNS server. The set $upstream tells Nginx to resolve the name only when a real request arrives, not at startup.</p><h4>The Promote Command</h4><p>The promote subcommand switches between stable and canary mode. The key design decision: instead of just setting an environment variable, it updates manifest.yaml in place, regenerates docker-compose.yml with the new MODE env var, and restarts only the app container.</p><p>This keeps the manifest as the source of truth even after a mode change.</p><h3>Part 2 — The Guardrails: OPA Policies</h3><h4>Why Not Just Write if/else in Python?</h4><p>The naive approach to pre-deploy checks looks like this:</p><pre>if disk_free_gb &lt; 10:<br>    print(&quot;Not enough disk&quot;)<br>    sys.exit(1)</pre><p>This works but has serious problems. Changing the threshold requires editing and redeploying the CLI. Different environments cannot have different policies. The decision logic is buried in application code with no structured reasoning attached.</p><p>OPA solves all of this. You move the decision logic into .rego files that OPA evaluates. The CLI just asks OPA a question — it never decides anything itself.</p><h4>How OPA Works</h4><p>OPA runs as a sidecar container and exposes a REST API. When the CLI wants a deployment decision, it POSTs the relevant context:</p><pre>resp = requests.post(<br>    &quot;http://localhost:8181/v1/data/infrastructure&quot;,<br>    json={&quot;input&quot;: {<br>        &quot;disk_free_gb&quot;: 8.5,<br>        &quot;cpu_load&quot;: 1.2<br>    }}<br>)<br>result = resp.json()[&quot;result&quot;]<br># {&quot;allow&quot;: false, &quot;violations&quot;: [&quot;Disk free (8.5 GB) below minimum (10.0 GB)&quot;]}</pre><p>OPA returns a structured decision with reasoning, never just a boolean.</p><h4>The Infrastructure Policy</h4><pre>package infrastructure<br><br>default allow = false<br><br>allow if { count(violations) == 0 }<br><br>violations contains msg if {<br>    input.disk_free_gb &lt; data.thresholds.min_disk_free_gb<br>    msg := sprintf(&quot;Disk free (%.1f GB) is below minimum (%.1f GB)&quot;,<br>                   [input.disk_free_gb, data.thresholds.min_disk_free_gb])<br>}<br><br>violations contains msg if {<br>    input.cpu_load &gt; data.thresholds.max_cpu_load<br>    msg := sprintf(&quot;CPU load (%.2f) exceeds maximum (%.2f)&quot;,<br>                   [input.cpu_load, data.thresholds.max_cpu_load])<br>}</pre><p>Now the actual threshold numbers live in data.json:</p><pre>{<br>  &quot;thresholds&quot;: {<br>    &quot;min_disk_free_gb&quot;: 10.0,<br>    &quot;max_cpu_load&quot;: 2.0<br>  }<br>}</pre><p>Change the threshold by editing data.json. The policy logic never needs to change.</p><h4>Why Policy Isolation Matters</h4><p>Each policy domain is completely independent. The infrastructure policy knows nothing about canary metrics. The canary policy knows nothing about disk space. This means the team responsible for infrastructure thresholds never needs to touch the canary policy file, and vice versa.</p><p>The canary safety policy blocks promotion if the canary has been unhealthy:</p><pre>package canary<br><br>default allow = false<br><br>allow if { count(violations) == 0 }<br><br>violations contains msg if {<br>    input.error_rate &gt; data.thresholds.max_error_rate<br>    msg := sprintf(&quot;Error rate (%.2f%%) exceeds maximum (%.2f%%)&quot;,<br>                   [input.error_rate * 100, data.thresholds.max_error_rate * 100])<br>}<br><br>violations contains msg if {<br>    input.p99_latency_ms &gt; data.thresholds.max_p99_latency_ms<br>    msg := sprintf(&quot;P99 latency (%dms) exceeds maximum (%dms)&quot;,<br>                   [input.p99_latency_ms, data.thresholds.max_p99_latency_ms])<br>}</pre><h4>Graceful OPA Failure Handling</h4><p>The CLI must never crash when OPA is unavailable. Three distinct failure modes each produce a different outcome:</p><pre>except requests.ConnectionError:<br>    return &quot;unavailable&quot;   # OPA container is down<br>except requests.Timeout:<br>    return &quot;timeout&quot;       # OPA did not respond in time</pre><p>For all three cases, the CLI warns the operator and proceeds. Failing open is a deliberate choice — a deployment tool should not block deployments because a policy engine is temporarily down.</p><h3>Part 3 — The Metrics Endpoint</h3><p>The /metrics endpoint uses Prometheus text format. Every request automatically updates counters and histograms via Flask middleware:</p><pre>@app.after_request<br>def track_metrics(response):<br>    duration = time.time() - request._start_time<br>    http_requests_total.labels(<br>        method=request.method,<br>        path=request.path,<br>        status_code=str(response.status_code)<br>    ).inc()<br>    http_request_duration_seconds.labels(<br>        method=request.method,<br>        path=request.path<br>    ).observe(duration)<br>    return response</pre><p>Five metrics are tracked: total requests with labels, request duration histogram, uptime, mode (0=stable, 1=canary), and chaos state (0=none, 1=slow, 2=error).</p><h3>Part 4 — What Happened When I Injected Chaos</h3><h4>Slow Mode</h4><p>After promoting to canary, I injected a 3 second delay:</p><pre>curl -X POST http://localhost:8080/chaos \<br>  -d &#39;{&quot;mode&quot;: &quot;slow&quot;, &quot;duration&quot;: 3}&#39;</pre><p>The swiftdeploy status dashboard immediately captured the impact:</p><pre>  Mode:          canary<br>  Chaos:         slow<br>  Error rate:    0.00%<br>  P99 latency:   3024ms<br><br>  Policy Compliance:<br>    ✔ infrastructure<br>    ✘ canary<br>        • P99 latency (3024ms) exceeds maximum (500ms)</pre><p>Attempting to promote to stable was blocked:</p><pre>  ✘  Policy FAILED: canary/pre-promote<br>       • P99 latency (3024ms) exceeds maximum (500ms)<br><br>  ✘  Promotion blocked by policy.</pre><h4>Error Mode</h4><p>Injecting a 50% error rate:</p><pre>curl -X POST http://localhost:8080/chaos \<br>  -d &#39;{&quot;mode&quot;: &quot;error&quot;, &quot;rate&quot;: 0.5}&#39;</pre><p>The dashboard showed the error rate climbing and the canary policy failing. Promotion remained blocked until recovery.</p><h4>Recovery</h4><pre>curl -X POST http://localhost:8080/chaos \<br>  -d &#39;{&quot;mode&quot;: &quot;recover&quot;}&#39;</pre><p>Within one status scrape cycle, both policies showed passing and promotion succeeded cleanly.</p><h3>Part 5 — Lessons Learned</h3><p><strong>Separation of concerns at the tool level matters.</strong> The CLI orchestrates. OPA decides. The app serves. When each component has exactly one responsibility, failures are isolated and changes are safe.</p><p><strong>Templates beat handwritten configs.</strong> Being able to delete generated files and regenerate them identically from a manifest means the manifest is always the truth, not whatever someone last edited by hand.</p><p><strong>Policy as data, not code.</strong> Keeping thresholds in data.json rather than hardcoded in Rego means anyone can change limits without touching policy logic. Policies become readable contracts rather than opaque code.</p><p><strong>Observability is not optional.</strong> Without the /metrics endpoint and the status command, the chaos injection would have been invisible. Real-time metrics turned a black box into a transparent system.</p><h3>Running It Yourself</h3><pre>git clone https://github.com/carvanino/hng14-stage2-devops<br>cd stage-4a<br><br>pip install -r requirements.txt<br>chmod +x swiftdeploy<br>docker build -t swift-deploy-1-node:latest .<br><br>./swiftdeploy validate<br>./swiftdeploy deploy<br>./swiftdeploy promote canary<br><br># Inject chaos<br>curl -X POST http://localhost:8080/chaos \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;mode&quot;: &quot;error&quot;, &quot;rate&quot;: 0.5}&#39;<br><br># Watch the dashboard<br>./swiftdeploy status<br><br># Try to promote — policy blocks it<br>./swiftdeploy promote stable<br><br># Recover and promote cleanly<br>curl -X POST http://localhost:8080/chaos \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;mode&quot;: &quot;recover&quot;}&#39;<br>./swiftdeploy promote stable<br><br># Generate audit report<br>./swiftdeploy audit</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b12606695c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Anomaly Detection Engine for a Cloud Server]]></title>
            <link>https://medium.com/@akinolatofunmi/building-a-detection-engine-for-a-cloud-server-0b20429081b4?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b20429081b4</guid>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 23:39:48 GMT</pubDate>
            <atom:updated>2026-05-04T19:30:46.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbitGSfGekHkX7k1s3RNNA.png" /><figcaption>Full Architecture of Detector Daemon</figcaption></figure><p>The moment a server comes up on the internet, whether open for TCP connections or SSH connections, it almost immediately starts receiving ‘unexpected’ requests — Bots, attackers, scanners constantly probe the server trying to take it down. This form of attack is known as <strong>DDoS — Distributed Denial of Service</strong>.</p><p>Cloud platforms like AWS, GCP and Azure have services that generally secure users’ provisioned cloud servers from this form of attack on their platform. For example, with AWS, we have AWS Shield, which is usually combined with or used alongside AWS WAF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjGgAUm2Z_lWQGvlI_57Xw.png" /><figcaption>A simple description of what a DDoS attack looks like</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvIdk4icPERSXiuJKeX6CA.png" /><figcaption>AWS Shield protects Web Services on AWS.</figcaption></figure><p>But what if we were not provisioning our resources on any of the very popular cloud platforms? Think of <strong>Hetzner</strong>, we get a good virtual machine on which we want to deploy a web server. How do we protect this server from DDoS attacks? This project walks you through understanding how this can easily be done in order to securely protect our servers.</p><p>The tool simply monitors all incoming requests in real time, understands what looks normal at a given time and automatically blocks attackers before their presence becomes noticeable.</p><h4>Our Current Use Case and What This Tool Does.</h4><p>We have a NextCloud Server, a cloud storage platform that is publicly accessible over the internet, with a virtual machine on Hetzner (CCX23 (Dedicated vCPU)). Because this server is publicly accessible, it is exposed to various forms of attack.</p><ul><li><strong>Volumetric attacks </strong>— An attacker sends a high volume of requests within a short time to a server to overwhelm the server.</li><li><strong>Brute force</strong> — An attacker probes access points, like login endpoints, repeatedly trying to guess passwords.</li><li><strong>Reconnaissance</strong> — An attacker scans for vulnerable paths, generating a series of 404 errors.</li></ul><p>Without any form of protection on this server, we are susceptible to these attacks, which could make the server very slow for real-time users, and in some cases, completely unreachable.</p><p>Our tool, the detector, sits between this server(NextCloud) and the internet, monitoring every request until it finds something abnormal. This could be a single IP sending 50 requests per second (req/s) when normal traffic has been 2 req/s. It immediately blocks that IP at the firewall level and sends an alert to Slack in real-time, or an overall overwhelm of the system where several request from different IPs floods the system beyond the current normal. In this case, we don’t know how to say this is the IP that is an attacker on the system, so we just send an alert to Slack about a Global Anomaly on the server.</p><h4><strong>The Architecture</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9dPSikKLvNFvKpYTpOXCw.png" /><figcaption>The Big Picture for the Detector</figcaption></figure><p>We place NGINX as a proxy server to the NextCloud cloud server. What this means is that every request from the internet comes in through the Nginx web server, which then forwards these requests to our real server, NextCloud. With this, we are able to set up our detector on a bridge network with access to the traffic flowing through NGINX, without directly interfering with the application itself. The bridge network is essentially a private virtual network within the host machine (VM) that allows multiple services to communicate with each other as though they’re on the same local network, providing shared data access — in our case, the NGINX logs and low-latency coordination across the various services.</p><h4><strong>Part 1 — How the Sliding Window Works</strong></h4><p>With NGINX as a reverse proxy server, we can easily read the log files from its path.</p><pre>import json<br><br>def tail_log(path):<br>    &quot;&quot;&quot;<br>    Generator function to read a log file in real-time.<br>    &quot;&quot;&quot;<br><br>    with open(path, &quot;r&quot;) as file:<br>        # Moves the cursor to the end of the file<br>        file.seek(0, 2)<br><br>        while True:<br>            line = file.readline()<br>            if not line:<br>                time.sleep(0.05)  # Sleep briefly to avoid busy waiting<br>                continue<br>            line = line.strip()<br>            if line: <br>                try:<br>                    # Attempt to parse the line as JSON<br>                    data = json.loads(line)<br>                    yield data<br>                except json.JSONDecodeError:<br>                    continue</pre><p>But how do we know how many requests came from an IP within the last 60 seconds? We could keep a list of every request and scan through it for each IP to know how many requests we have received within a specific time, but that can become really slow as the list grows. The right approach is to use a <strong>fixed</strong> <strong>sliding window</strong>, a data structure that allows us to manage the amount of data we keep at a time. So we store only timestamps for each request within a window frame, and remove any timestamp that is over our window frame. We also check the count and calculate the rate. Our chosen window frame is 60 seconds. We use a <em>deque —</em> a double-ended queue, as it allows us to append new data to the right, giving an O(1) on insertion and removal from the left as well.</p><pre>from collections import deque<br>import time<br><br>class SlidingWindow:<br>    def __init__(self, window_seconds=60):<br>        self.window_seconds = window_seconds<br>        self.timestamps = deque()   # double-ended queue<br><br>    def add(self, timestamp):<br>        # Add new timestamp to the right<br>        self.timestamps.append(timestamp)<br><br>        # Evict old timestamps from the left<br>        cutoff = timestamp - self.window_seconds<br>        while self.timestamps and self.timestamps[0] &lt; cutoff:<br>            self.timestamps.popleft()<br><br>    def count(self):<br>        return len(self.timestamps)<br><br>    def rate(self):<br>        return self.count() / self.window_seconds</pre><p>Two windows run in parallel; one per IP and one global, so we can detect both a single aggressive IP and a distributed flood from many IPs simultaneously.</p><pre>Time: 12:00:05<br>Window: [12:59:05, 12:59:08, 12:59:12, ... 12:00:04]<br><br>Time: 12:00:06<br>Window: [12:59:06, 12:59:08, 12:59:12, ... 12:00:06]<br>         ↑ 12:59:05 evicted                ↑ new entry added</pre><h4><strong>Part 2 — How the Baseline Learns From Traffic</strong></h4><p>With the Sliding Window, we’re able to know the rate of request on a global level and on an IP level, but this information is not very useful for us or the system, if we set a hard limit on the system to say when the request rate is for example greater than 3 <em>req/s</em> we should act, on some days that could be what is normal for the system based on the traffic being received. We can think about it like a shopping complex, if the security system sets a hard limit to prevent customers from getting in if we have more than 50 customers come in within 1 minute. What this implies is that during a festive period, we would unduly prevent customers from getting access to the complex. So the system needs to learn what is normal for this period of the day and only acts when something is not.</p><p>This is what the baseline solves: it provides context, building a historical picture of what is happening currently within the system.</p><p>The baseline records the <em>number of requests </em>that hit our server every second, for a chosen period of 30 minutes. This builds us a data point of 1,800. With these, we calculate;</p><ul><li><strong>Mean</strong> — The average requests per second, which gives us the idea of what a typical second looks like</li><li><strong>Standard Deviation</strong> — This helps us understand how much traffic varies.</li></ul><pre>import math<br><br>counts = [2, 1, 3, 2, 4, 1, 2, 3, ...]    # 1800 per-second counts<br><br>mean = sum(counts) / len(counts)          # e.g. 2.5 req/s<br>variance = sum((x - mean)**2 for x in counts) / len(counts)<br>stddev = math.sqrt(variance)              # e.g. 0.8</pre><p>Another very important detail is that we keep an hourly bucket (slot) specifically for request counts for each hour of the day (0–23). The reason why we do this is to prevent noise during the hourly transitions. For example, our server gets 2 <em>req/s </em>at 3 am and then 40 <em>req/s </em>at 4 am. The 30-minute windows from our baseline will create a false alarm when looking at the period from 3:30–4 am when we perform our calculations. To prevent this, when the current hour has enough data (at least 5 minutes worth), we prefer it over the full 30-minute window. This helps us to keep the baseline more accurate, even during traffic transitions within the day.</p><h4><strong>Part 3 — How the Detection Logic Makes a Decision</strong></h4><p>The sliding window gives us the current rate (<em>req/s</em>) and the baseline, getting us the context of what’s normal at the moment. The job of the detector is then to compare the current rate and the baseline standard deviation, answering the question of how many standard deviations above normal is this rate?</p><pre>z = (current_rate - mean) / stddev<br><br># For example<br>mean   = 2 req/s<br>stddev = 0.8 req/s<br>current = 40 req/s<br><br>z = (40 - 2) / 0.8 = 47.5 # Extremely high z-score <br># z-score &gt; 3 is statistically impossible to occur naturally</pre><p>The detector runs two checks for every request:</p><ul><li><strong>Check 1 </strong>— flag as anomalous if z-score is greater than 3.0 (z-score &gt; 3.0)</li><li><strong>Check 2 </strong>— flag as anomalous if current_rate &gt; (5 * mean). This check acts as a safety net when the baseline is still building, and the standard deviation is still low.</li><li><strong>Check 3 </strong>— This is where we check for a reconnaissance attack by checking if an IP’s 4xx and 5xx error rate is more than 3 times the baseline error rate. Once an IP breaches this, we tighten the z-score for that IP by applying a 30% deduction (For example, an IP with a z-score of 3.0 becomes 2.1 (3.0 * 0.7)</li></ul><h4><strong>Part 4 — How iptables Blocks an IP</strong></h4><p>Now that we have cleared everything, we need to define what actions we take when we detect an anomaly on an IP and also globally. For this part, our focus is on the IPs and as already discussed, we block any IP that we suspect is malicious via the detector. For this, we use <strong>iptables</strong> — Linux’s built-in firewall.</p><p>iptables works by matching incoming network packets against a list of rules. When a packet matches a rule, the specified action is taken. The <strong>DROP</strong> action silently discards the packet, so that the sender never even gets an error back.</p><p>To block an IP:</p><pre>iptables -A INPUT -s 192.168.1.100 -j DROP</pre><p>What this means is;</p><ul><li>A INPUT — append a rule to the INPUT chain (rules for incoming traffic)</li><li>-s 192.168.1.100 — specifies the source IP to match packets from</li><li>j DROP — silently discard the packets</li></ul><p><strong>Auto-unban with escalating backoff</strong></p><pre>| Offence | Duration  |<br>|---------|-----------|<br>| 1st     | 10 minutes|<br>| 2nd     | 30 minutes|<br>| 3rd     | 2 hours   |<br>| 4th+    | Permanent |</pre><p>We implement a temporary ban until a specific IP keeps offending before permanently banning the address.</p><p>To remove a ban, we have to delete the rule that we set initially on the IP, and to do that we run;</p><pre>iptables -D INPUT -s 192.168.1.100 -j DROP</pre><p>The -D flag deletes a matching rule instead of appending one. We have a background thread running that also checks every 30 seconds whether any bans have expired and removes them automatically. When an already offended IP reoffends, we escalates it’s level until permanently banning the address.</p><h4><strong>Part 5 — The Full Pipeline</strong></h4><p>At this point, we already have all the pieces laid out, we should be able to put it together. Let’s start from the moment an attack starts to the moment the attacker is blocked:</p><pre>1. Attacker sends 500 req/s from IP 192.168.1.100<br>   <br>2. Nginx logs each request as a JSON line to hng-access.log<br><br>3. monitor.py reads the new lines in real time<br>   → extracts source_ip, status, timestamp<br><br>4. detector.py updates the sliding windows<br>   → global window count increases<br>   → per-IP window for 192.168.1.100 spikes<br><br>5. Baseline comparison<br>   → current rate: 8.3 req/s<br>   → baseline mean: 2.5 req/s<br>   → z-score: (8.3 - 2.5) / 0.8 = 7.25  ← exceeds 3.0<br><br>6. Alert fires: type=ip, ip=192.168.1.100<br><br>7. blocker.py runs iptables -A INPUT -s 192.168.1.100 -j DROP<br><br>8. notifier.py sends Slack message:<br>   🚨 IP BANNED<br>   IP: 192.168.1.100<br>   Condition: z-score exceeded<br>   Rate: 8.33 req/s<br>   Baseline: 2.50 req/s<br>   Duration: 10 minutes<br><br>9. audit.py writes to /var/log/detector/audit.log:<br>   [2026-04-29 12:34:05 UTC] BAN  ip=192.168.1.100 | ...<br><br>10. 10 minutes later — unbanner.py removes the rule<br>    → Slack: ✅ IP UNBANNED 192.168.1.100</pre><h4>What I Learned</h4><p>Threading was a very crucial part of this build. There are multiple things happening at the same time, from the logs to checking bans, and then the sliding windows, as well as the baseline. Being able to make sure that no process is stuck within another was a crucial part of this tool.</p><p>Also, the baseline, this is a core part of the application because it allows the system to learn and only react based on what’s currently happening, no hard-coded values. The system collects data and based on this data it decides what looks good and what does not. That is an intelligent system!</p><h4><strong>Links</strong></h4><ul><li>GitHub Repository: <a href="https://github.com/carvanino/hng14-stage2-devops">https://github.com/carvanino/hng14-stage2-devops</a> (<em>Access is available in stage-3/</em>)</li><li>Live Dashboard: <a href="http://hng-akinola.duckdns.org/">http://hng-akinola.duckdns.org</a> (<em>This domain will only be up for 2 weeks after the publish date</em>)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b20429081b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Scheduled Events to Webhooks: Building a Resilient Event-Driven Notification System]]></title>
            <link>https://medium.com/@akinolatofunmi/from-scheduled-events-to-webhooks-building-a-resilient-event-driven-notification-system-34f710a878ee?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/34f710a878ee</guid>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 20:24:24 GMT</pubDate>
            <atom:updated>2025-12-13T20:24:24.481Z</atom:updated>
            <content:encoded><![CDATA[<p>Building financial services infrastructure requires solving a fundamental challenge: how do one reliably notify external systems about time-sensitive events at scale? This is the story of how I evolved a notification system from a scheduled reminder service to a generic webhook platform, and how I optimised it from polling-based retries to an event-driven architecture using AWS <strong>EventBridge</strong> <strong>Scheduler</strong>.</p><p>This isn’t just about technology choices, it’s about understanding constraints, making deliberate trade-offs, and evolving architecture based on real-world feedback.</p><h3><strong>Part 1: The Foundation — Scheduled Payment Link Reminders</strong></h3><p>Our platform, PCXPay, processes loans for financial organisations, helping organisations collect payment from around the world. Here’s a typical scenario:</p><ul><li>A client borrows £10,000 from an organisation</li><li>Repayment terms: £15,000 over 10 monthly instalments (£1,500/month)</li><li>The system needs to remind clients when their payment is due</li><li>Timing must be precise: send the reminder at the exact scheduled_at timestamp</li><li><strong>Scale requirement</strong>: thousands of scheduled reminders across multiple organisations</li></ul><p><strong>Architectural Decision:</strong> Before diving into what was built, let’s have a look at options that we did not take and why.</p><p><strong>Cron jobs on EC2:</strong></p><ul><li>Requires maintaining long-running servers</li><li>Complex state management</li><li>Doesn’t scale horizontally without coordination</li><li>Higher operational overhead</li></ul><p>We prioritise serverless application over unmananged services…so we went with</p><p><strong>EventBridge + SQS Delays + Lambda:</strong></p><ul><li>Serverless, scales automatically</li><li>SQS provides precise delays (up to 15 minutes)</li><li>Pay only for actual usage</li><li>Built-in retry mechanisms</li></ul><p><strong>Core Scheduler Architecture — The Foundation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IT8Q-V5bxTRVaUI564u53A.png" /><figcaption>Scheduler Architecture</figcaption></figure><p>The system has three key components;</p><pre># payment_link_scheduler.py - Discovery Lambda<br>def handler(event, context):<br>    &quot;&quot;&quot;<br>    Runs every 10 minutes via EventBridge<br>    Queries payment links scheduled in next 15 minutes<br>    Sends each to SQS with calculated delay<br>    &quot;&quot;&quot;<br>    now = datetime.now(timezone.utc)<br>    <br>    # Query window: 15 minutes ahead<br>    data = ScheduledPaymentLinkDTO(<br>        scheduled_at=now.isoformat(),<br>        period=15  # minutes<br>    )<br>    <br>    payment_links = payment_link_usecases.get_payment_links(data)<br>    <br>    for link in payment_links:<br>        scheduled_time = datetime.fromisoformat(link.scheduled_at)<br>        <br>        # Calculate delay: when should SQS deliver this message?<br>        delay_seconds = int((scheduled_time - now).total_seconds())<br>        <br>        # Constrain to SQS limits: 0-900 seconds (15 minutes)<br>        delay_seconds = max(0, min(delay_seconds, 900))<br>        <br>        # Send to SQS<br>        sqs.send_message(<br>            QueueUrl=queue_url,<br>            MessageBody=json.dumps(link.dict()),<br>            DelaySeconds=delay_seconds<br>        )</pre><pre># payment_link_email_sender.py - Execution Lambda<br>def handler(event, context):<br>    &quot;&quot;&quot;<br>    Triggered by SQS when delay expires<br>    Sends email at exact scheduled time<br>    &quot;&quot;&quot;<br>    for record in event[&#39;Records&#39;]:<br>        link_data = json.loads(record[&#39;body&#39;])<br>        <br>        # Reconstruct entity<br>        payment_link = PaymentLink(**link_data)<br>        <br>        # Send via SES<br>        payment_link_usecases.send_payment_link_email(<br>            payment_link, <br>            email_template<br>        )</pre><p>Why run the payment_link_scheduler every 10 Minutes?</p><p>Known constraints:<br>- SQS maximum delay: 900 seconds (15 minutes)<br>- Need to catch all scheduled events<br>- Minimise cost (fewer Lambda invocations)</p><p>The calculation:<br>- If scheduler runs every 15 minutes and queries 15 minutes ahead: <strong>No overlap</strong> → Events could be missed<br>- If scheduler runs every 5 minutes: <strong>Too frequent</strong> → Higher costs, wasted invocations<br>- If scheduler runs every 10 minutes and queries 15 minutes ahead: 5-minute overlap → <strong>Perfect</strong></p><h3><strong>Part 2: Evolution to Generic Webhooks</strong></h3><h4>The Business Requirement Changes</h4><p>After launching the payment link reminder system, we received feedback from one of our partner organisation: “We want emails to come from our domain, not yours”. They also wanted to send reminders more consistently, and manage reconciliation on our system and theirs, they needed more than just a reminder system. They wanted to be notified of events and handle communication themselves. We realised our direct email approach was too <em>opinionated</em>. Organisations wanted <strong><em>control</em></strong> and <strong><em>visibility.</em></strong></p><p><strong>The Solution: Webhook Notifications</strong></p><p>Instead of sending direct emails, we would;</p><ul><li>Send webhooks to organisations when events occur</li><li>Let organisations handle email delivery, logging, and customer communication</li><li>Support any event type: loan.created, payment.received, payment.due, etc.</li></ul><p>What we had already;</p><ul><li><strong>SQS for buffering</strong>: Queue events before processing</li><li><strong>Retry with DLQ</strong>: Immediate retries, then long-term handling</li></ul><p><strong>Webhook System Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYembpWQf7qrEoaTw5NVfQ.png" /><figcaption>Webhook System Architecture — Reusing Scheduler Patterns</figcaption></figure><p>Any PCX service can now send webhook notifications:</p><pre># In any service (payment, transaction, loan, etc.) via lambda invocation calls<br><br># When a significant event occurs<br>send_webhook_notification(<br>    org_id=&quot;org_123&quot;,<br>    event_type=&quot;payment.completed&quot;,<br>    event_data={<br>        &quot;payment_id&quot;: &quot;pay_456&quot;,<br>        &quot;amount&quot;: 1500,<br>        &quot;currency&quot;: &quot;NGN&quot;,<br>        &quot;transaction_id&quot;: &quot;txn_789&quot;<br>    },<br>    metadata={<br>        &quot;user_id&quot;: &quot;user_001&quot;,<br>        &quot;timestamp&quot;: datetime.now(timezone.utc).isoformat()<br>    }<br>)</pre><p><strong>The flow:</strong></p><ol><li>Event occurs in any PCX service</li><li>Service calls send_webhook_notification()</li><li>Event queued in SQS with event_id, org_id, event_type, event_data</li><li>Webhook handler Lambda triggered</li><li>Fetches org webhook config from DynamoDB (webhook_url, secret, timeout)</li><li>Builds payload with HMAC signature for security</li><li>POSTs to organisation’s webhook endpoint</li><li>Success: Delete from queue / Failure: Retry (3 attempts) → DLQ</li></ol><h3>Part 3: The Retry Optimization — From Polling to Event-Driven</h3><h4>The Problem with the Initial Retry Approach</h4><p>The initial webhook retry strategy used <strong>EventBridge Rules</strong> with periodic polling. See diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTZ5-M0B7aYwAdiNPebdWA.png" /><figcaption>The pooling problem on webhook architecture</figcaption></figure><pre># Initial approach: webhook_retry_handler.py (Polling version)<br>def handler(event, context):<br>    &quot;&quot;&quot;<br>    Triggered by EventBridge Rule EVERY HOUR<br>    Checks webhook_failures table for retries that are due<br>    &quot;&quot;&quot;<br>    now = int(datetime.now(timezone.utc).timestamp())<br>    <br>    # Query ALL records from webhook_failures<br>    response = failures_table.scan(<br>        FilterExpression=Attr(&#39;next_retry_at&#39;).lte(now) &amp; <br>                        Attr(&#39;status&#39;).eq(&#39;retrying&#39;)<br>    )<br>    <br>    for item in response[&#39;Items&#39;]:<br>        # Retry the webhook<br>        # Update next_retry_at for next attempt<br>        pass</pre><p><strong>The Problem:</strong></p><ol><li><strong>Wasted Lambda invocations</strong>: Lambda runs every hour even when there are zero pending retries</li><li><strong>Table scans</strong>: Queries entire webhook_failurestable every hour</li><li><strong>Not scalable</strong>: As failures increase, scan becomes expensive</li><li><strong>Higher costs</strong>: Pay for Lambda invocations that do no useful work</li></ol><h4>The Solution: EventBridge Scheduler (Event-Driven)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H9Jmp-9AwqbsgwFIeoUwQ.png" /><figcaption>optimised retry system on webhook architecture</figcaption></figure><p>Instead of polling, we create <strong>one-time schedules</strong> for each failed webhook:</p><pre># webhook_dlq_processor.py<br>def handler(event, context):<br>    &quot;&quot;&quot;<br>    Triggered when webhook moves to DLQ after 3 SQS failures<br>    Stores failure and creates EventBridge Schedule<br>    &quot;&quot;&quot;<br>    for record in event[&#39;Records&#39;]:<br>        message_data = json.loads(record[&#39;body&#39;])<br>        <br>        now = int(datetime.now(timezone.utc).timestamp())<br>        next_retry = now + 60  # Retry in 1 minute<br>        failure_id = f&quot;{now}_{message_data[&#39;event_id&#39;]}&quot;<br>        <br>        # Store in webhook_failures table<br>        failures_table.put_item(Item={<br>            &#39;failure_id&#39;: failure_id,<br>            &#39;org_id&#39;: message_data[&#39;org_id&#39;],<br>            &#39;event_type&#39;: message_data[&#39;event_type&#39;],<br>            &#39;payload&#39;: message_data,<br>            &#39;attempt_count&#39;: 3,  # Already tried 3 times in SQS<br>            &#39;next_retry_at&#39;: next_retry,<br>            &#39;status&#39;: &#39;retrying&#39;,<br>            &#39;ttl&#39;: now + (3 * 24 * 3600)  # 3 days<br>        })<br>        <br>        # Create one-time EventBridge Schedule<br>        schedule_retry(failure_id, next_retry)<br><br>def schedule_retry(failure_id, retry_timestamp):<br>    &quot;&quot;&quot;Create one-time schedule for exact retry time&quot;&quot;&quot;<br>    retry_datetime = datetime.fromtimestamp(retry_timestamp, tz=timezone.utc)<br>    schedule_expression = f&quot;at({retry_datetime.strftime(&#39;%Y-%m-%dT%H:%M:%S&#39;)})&quot;<br>    <br>    scheduler.create_schedule(<br>        Name=f&quot;webhook-retry-{failure_id}&quot;,<br>        ScheduleExpression=schedule_expression,<br>        Target={<br>            &#39;Arn&#39;: RETRY_LAMBDA_ARN,<br>            &#39;RoleArn&#39;: SCHEDULER_ROLE_ARN,<br>            &#39;Input&#39;: json.dumps({&#39;failure_id&#39;: failure_id})<br>        },<br>        FlexibleTimeWindow={&#39;Mode&#39;: &#39;OFF&#39;}  # Exact time, no flexibility<br>    )</pre><p>Now the retry handler is <strong>event-driven</strong>:</p><pre># webhook_retry_handler.py (Scheduler version)<br>def handler(event, context):<br>    &quot;&quot;&quot;<br>    Triggered by EventBridge Scheduler at EXACT retry time<br>    Receives specific failure_id, no table scanning needed<br>    &quot;&quot;&quot;<br>    failure_id = event.get(&#39;failure_id&#39;)<br>    <br>    # Get specific record<br>    response = failures_table.get_item(Key={&#39;failure_id&#39;: failure_id})<br>    item = response[&#39;Item&#39;]<br>    <br>    # Attempt webhook retry<br>    success = retry_webhook(item)<br>    <br>    if success:<br>        # Delete record and schedule<br>        failures_table.delete_item(Key={&#39;failure_id&#39;: failure_id})<br>        delete_schedule(failure_id)<br>    else:<br>        # Still failing - exponential backoff<br>        schedule_next_retry(item, now)</pre><h4>Side-by-Side Comparison</h4><p><strong>Polling approach (1 day):</strong></p><ul><li>EventBridge Rule triggers: 24 times (hourly)</li><li>Lambda invocations: 24</li><li>Table scans: 24</li><li>Useful work: Maybe 5–6 retries</li><li><strong>Waste: ~75%</strong></li></ul><p><strong>Event-driven approach (1 day):</strong></p><ul><li>EventBridge Schedules created: 5–6 (only when needed)</li><li>Lambda invocations: 5–6 (only when scheduled)</li><li>DynamoDB queries: 5–6 (targeted GetItem, no scans)</li><li>Useful work: 5–6 retries</li><li><strong>Waste: 0%</strong></li></ul><p><strong>Exponential Backoff Strategy</strong></p><pre># Retry schedule in seconds<br>RETRY_SCHEDULE = [60, 300, 900, 3600, 21600, 86400, 172800, 259200]<br># That&#39;s: 1min, 5min, 15min, 1hr, 6hr, 24hr, 48hr, 72hr<br><br>def schedule_next_retry(item, now):<br>    &quot;&quot;&quot;Schedule next retry with exponential backoff&quot;&quot;&quot;<br>    attempt_count = item[&#39;attempt_count&#39;] + 1<br>    <br>    if attempt_count &gt;= 11:<br>        # Mark as permanently failed after 11 total attempts (3 SQS + 8 Scheduler)<br>        failures_table.update_item(<br>            Key={&#39;failure_id&#39;: item[&#39;failure_id&#39;]},<br>            UpdateExpression=&#39;SET #status = :status&#39;,<br>            ExpressionAttributeNames={&#39;#status&#39;: &#39;status&#39;},<br>            ExpressionAttributeValues={&#39;:status&#39;: &#39;permanently_failed&#39;}<br>        )<br>        delete_schedule(item[&#39;failure_id&#39;])<br>        return<br>    <br>    # Calculate next retry with exponential backoff<br>    backoff_index = min(attempt_count - 3, len(RETRY_SCHEDULE) - 1)<br>    delay = RETRY_SCHEDULE[backoff_index]<br>    next_retry = now + delay<br>    <br>    # Update DynamoDB<br>    failures_table.update_item(<br>        Key={&#39;failure_id&#39;: item[&#39;failure_id&#39;]},<br>        UpdateExpression=&#39;SET attempt_count = :count, next_retry_at = :next&#39;,<br>        ExpressionAttributeValues={&#39;:count&#39;: attempt_count, &#39;:next&#39;: next_retry}<br>    )<br>    <br>    # Delete old schedule and create new one<br>    delete_schedule(item[&#39;failure_id&#39;])<br>    schedule_retry(item[&#39;failure_id&#39;], next_retry)</pre><p><strong>Why this backoff schedule?</strong></p><ul><li><strong>1 minute</strong>: Quick recovery for transient issues</li><li><strong>5–15 minutes</strong>: Organisation’s service might be restarting</li><li><strong>1–6 hours</strong>: Gives time for org to fix issues and deploy</li><li><strong>24–72 hours</strong>: Last resort, likely requires manual intervention</li></ul><p>After 3 days (11 total attempts), we mark as permanently failed and alert our operations team.</p><h3>Part 4: The Complete System</h3><h4>Final Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nFlwzNfqtU7G7dyTr9_7A.png" /><figcaption>Final webhook architecture after optimising retry mechanism</figcaption></figure><p>The complete flow from event to delivery:</p><ol><li><strong>Event Generation</strong>: Any PCX service triggers a webhook</li><li><strong>Immediate Processing</strong>: SQS retries 3 times with exponential backoff (~90 seconds total)</li><li><strong>DLQ Processing</strong>: After 3 failures, DLQ processor stores in webhook_failures and creates EventBridge Schedule</li><li><strong>Long-term Retries</strong>: EventBridge Scheduler triggers retries at exact times with exponential backoff (1min → 72hr)</li><li><strong>Success or Failure</strong>: Either succeeds (delete record + schedule) or permanently fails (alert ops)</li></ol><h4>Evolution &gt; Perfection</h4><p>We didn’t build the optimal system on day one. We started with a focused solution (payment links), learned from usage (organisations wanted control), generalised (webhooks), and optimised (EventBridge Scheduler). Iterative improvement beats big-bang redesigns.</p><h4>Event-Driven &gt; Polling (Always)</h4><p>The shift from EventBridge Rules (polling) to EventBridge Scheduler (event-driven) eliminated:</p><ul><li>~75% wasted Lambda invocations</li><li>Expensive table scans</li><li>Imprecise timing</li><li>Scaling bottlenecks</li></ul><p><strong>👍🏾</strong>: If you’re polling for work, you’re doing it wrong. Create events instead.</p><h3>Results &amp; Impact</h3><h4>Quantitative Improvements</h4><p><strong>Cost savings:</strong></p><ul><li>Eliminated ~18 hours/day of wasted Lambda invocations (polling approach)</li><li>Reduced DynamoDB read capacity by ~75% (no more table scans)</li><li>EventBridge Scheduler: $1.00 per million schedules vs continuous polling</li></ul><p><strong>Reliability improvements:</strong></p><ul><li>11 total retry attempts over 3 days: 99.9%+ eventual delivery</li><li>Zero missed events due to 5-minute overlap window</li></ul><p><strong>Scalability:</strong></p><ul><li>Scheduler handles 10,000+ scheduled events per hour</li><li>Event-driven retry scales independently per failure</li></ul><h3>Qualitative Improvements</h3><p><strong>Developer Experience:</strong></p><ul><li>Clean separation of concerns (easier debugging)</li></ul><p><strong>Organisation Experience:</strong></p><ul><li>Full control over customer communications</li><li>Real-time event notifications for any PCX event</li><li>Built-in reliability (don’t need to implement retries)</li></ul><h3>What’s Next?</h3><p>Future enhancements we’re considering:</p><ul><li><strong>Webhook event replay</strong>: Organisations can request replay of events</li></ul><h3>Conclusion</h3><p>Building resilient event notification systems is about more than choosing the right AWS services. It’s about:</p><ul><li>Understanding constraints and working with them</li><li>Decoupling concerns for independent scaling and failure isolation</li><li>Evolving architecture based on real-world usage</li><li>Optimising continuously (polling → event-driven)</li><li>Making systems easy to reason about and debug</li></ul><p>The journey from payment link reminders to a generic webhook platform taught us that good architecture isn’t static, it adapts, evolves, and improves as requirements change and patterns become clear.</p><p>I’m Akinola, a software architect and engineer building financial infrastructure at PCXPay. I’m passionate about distributed systems, clean architecture, and solving real-world problems at scale. Connect with me on <a href="https://linkedin.com/in/oluwatofunmi-ac">LinkedIn</a> or check out more of my work on <a href="https://github.com/carvanino">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34f710a878ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Bridges and Namespaces — VPC’s and subnets]]></title>
            <link>https://medium.com/@akinolatofunmi/linux-bridges-and-namespaces-vpcs-and-subnets-5d951b0aceb2?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d951b0aceb2</guid>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 22:48:38 GMT</pubDate>
            <atom:updated>2025-11-13T12:22:46.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Linux Bridges and Namespaces — VPC’s and subnets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJDd5NllDpSUxaiHlD5pDg.png" /><figcaption>VPC architectural diagram</figcaption></figure><h3>Introduction</h3><p>Ever wondered how cloud providers like AWS and GCP create isolated virtual networks? In this tutorial, we’ll build a fully functional VPC system from scratch using only Linux networking primitives. By the end, you’ll understand the fundamental concepts behind cloud networking and have a working CLI tool to create, manage, and peer virtual networks.</p><p><strong>What you’ll learn:</strong></p><ul><li>Network namespaces and virtual ethernet (veth) pairs</li><li>Linux bridges as virtual switches</li><li>NAT gateway implementation with iptables</li><li>VPC isolation and peering</li><li>Firewall rules (Security Groups)</li></ul><p><strong>Prerequisites:</strong></p><ul><li>A Linux machine (Ubuntu 20.04+ recommended) with root access</li><li>Basic understanding of networking concepts (IP addresses, subnets, routing)</li><li>Python 3.8+ installed</li></ul><p>vpcctl is a command-line tool that recreates AWS VPC functionality using native Linux networking. It supports the following:</p><ul><li>Creating isolated VPCs with custom CIDR blocks</li><li>Adding public and private subnets</li><li>NAT gateway for internet access (on public subnets)</li><li>VPC peering for controlled cross-VPC communication</li><li>Firewall rules (Security Groups) using iptables</li><li>Complete resource cleanup</li></ul><h3>Architecture Overview</h3><p>Here’s what we’re building:</p><pre>HOST (192.168.1.0)<br>│<br>├── VPC-1 (172.16.0.0/16)<br>│   ├── VPC Bridge (br-vpc-1: 172.16.0.1/16)<br>│   ├── snt-1 (Private) → 172.16.1.0/24<br>│   │   └── veth-snt-1 ↔ veth-snt-1-br → br-vpc-1<br>│   └── snt-2 (Public) → 172.16.2.0/24<br>│       └── veth-snt-2 ↔ veth-snt-2-br → br-vpc-1 → NAT → Internet<br>│<br>└── VPC-2 (172.20.0.0/16)<br>    ├── VPC Bridge (br-vpc-2: 172.20.0.1/16)<br>    ├── snt-3 (Private) → 172.20.1.0/24<br>    └── snt-4 (Public) → 172.20.2.0/24<br>        └── NAT → Internet</pre><pre>Peering: veth-vpc-1 ↔ veth-vpc-2 (when enabled)</pre><h3>Core Networking Concepts</h3><p>Before diving into the CLI commands, let’s understand the fundamental building blocks:</p><h3>1. Network Namespaces — Isolated Network Stacks</h3><p><strong>What are they?</strong> Network namespaces provide complete isolation of network resources. Each namespace has its own:</p><ul><li>Network interfaces</li><li>IP addresses</li><li>Routing tables</li><li>iptables rules</li><li>Network sockets</li></ul><p>Think of a namespace as a completely separate computer’s network stack, but running on the same physical machine.</p><p><strong>Example:</strong></p><pre># Create a namespace<br>sudo ip netns add my-namespace<br># List namespaces<br>sudo ip netns list<br># Execute commands inside namespace<br>sudo ip netns exec my-namespace ip addr show</pre><p>In our VPC implementation, <strong>each subnet is a separate network namespace</strong>, providing complete isolation between subnets.</p><h3>2. Veth Pairs — Virtual Ethernet Cables</h3><p><strong>What are they?</strong> A veth (virtual ethernet) pair is like a virtual network cable with two ends. Whatever goes into one end comes out the other end. They always come in pairs.</p><p><strong>How they work:</strong></p><pre>[Namespace A] &lt;-- veth-a &lt;==&gt; veth-b --&gt; [Namespace B]</pre><p>Data sent to veth-a appears on veth-b, and vice versa.</p><p><strong>Example:</strong></p><pre># Create a veth pair<br>sudo ip link add veth0 type veth peer name veth1<br># Put one end in a namespace<br>sudo ip link set veth0 netns my-namespace<br># The other end stays in the host<br>sudo ip link set veth1 up<br># Now veth0 (in namespace) and veth1 (on host) are connected</pre><p>In our VPC, veth pairs connect each subnet (namespace) to the VPC bridge.</p><h3>3. Linux Bridges — Virtual Switches/Routers</h3><p><strong>What are they?</strong> A Linux bridge is a virtual network switch that connects multiple network interfaces together. It operates at Layer 2 (like a physical switch) but can also route packets at Layer 3 when assigned an IP address.</p><p><strong>Example:</strong></p><pre># Create a bridge<br>sudo ip link add name br0 type bridge<br># Assign IP to bridge (makes it a router)<br>sudo ip addr add 192.168.1.1/24 dev br0<br># Connect interfaces to bridge<br>sudo ip link set veth1 master br0<br>sudo ip link set veth2 master br0<br># Bridge now forwards packets between veth1 and veth2</pre><p>In our VPC, the bridge acts as the <strong>VPC router</strong> — all subnets connect to it and it routes traffic between them.</p><h3>4. iptables — Firewall and NAT</h3><p><strong>What is it?</strong> iptables is Linux’s packet filtering framework. It can:</p><ul><li><strong>Filter</strong>: Accept or drop packets based on rules</li><li><strong>NAT</strong>: Translate IP addresses (MASQUERADE, SNAT, DNAT)</li><li><strong>Mangle</strong>: Modify packet headers</li></ul><p><strong>Key chains:</strong></p><ul><li><strong>INPUT</strong>: Packets destined for this machine</li><li><strong>OUTPUT</strong>: Packets originating from this machine</li><li><strong>FORWARD</strong>: Packets being routed through this machine</li><li><strong>PREROUTING</strong>: Alter packets before routing</li><li><strong>POSTROUTING</strong>: Alter packets after routing (NAT happens here)</li></ul><p><strong>Example:</strong></p><pre># Block incoming SSH<br>sudo iptables -A INPUT -p tcp --dport 22 -j DROP<br># Allow HTTP<br>sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT<br># NAT (masquerade) outgoing traffic<br>sudo iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -j MASQUERADE</pre><p>In our VPC:</p><ul><li><strong>NAT</strong> allows private IPs to access internet</li><li><strong>FORWARD rules</strong> control traffic between subnets and VPCs</li><li><strong>INPUT rules</strong> implement Security Groups</li></ul><h3>5. Routing — Traffic Flow</h3><p><strong>What is it?</strong> Routing determines where packets go. Linux maintains a routing table that matches destination IPs to interfaces or gateways.</p><p><strong>Example:</strong></p><pre># View routing table<br>ip route show<br><br># Output:<br>default via 192.168.1.1 dev eth0          # Default gateway<br>10.0.0.0/24 dev br-vpc-1 scope link       # Direct route to bridge</pre><p><strong>How routing decisions are made:</strong></p><ol><li>Check if destination matches a specific route (most specific first)</li><li>If no match, use default route</li><li>Send packet to appropriate interface or gateway</li></ol><p>In our VPC, each subnet has a <strong>default route pointing to the VPC bridge</strong>, allowing inter-subnet communication.</p><h3>Installation &amp; Setup</h3><h3>1. Clone the Repository</h3><pre>git clone https://github.com/carvanino/hng13-stage0-devops.git<br>cd hng13-stage0-devops</pre><h3>2. Install the CLI Tool</h3><pre># Create wrapper script<br>sudo nano /usr/local/bin/vpcctl<br># Add this content:<br>#!/bin/bash<br>python3 /path/to/your/vpcctl.py &quot;$@&quot;<br># Make executable<br>sudo chmod +x /usr/local/bin/vpcctl<br># Verify installation<br>vpcctl --help</pre><h3>3. Required Python Dependencies</h3><pre>pip install click</pre><h3>CLI Commands — Detailed Breakdown</h3><h3>Command 1: create-vpc</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl create-vpc &lt;vpc-name&gt; &lt;cidr-block&gt;</pre><p><strong>Example:</strong></p><pre>sudo vpcctl create-vpc vpc-1 172.16.0.1/16</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Creates a Linux bridge:</strong></li></ol><pre>sudo ip link add name br-vpc-1 type bridge</pre><p>This creates a virtual network switch named br-vpc-1.</p><ol><li><strong>Assigns IP address to bridge:</strong></li></ol><pre>sudo ip addr add 172.16.0.1/16 dev br-vpc-1</pre><p>The bridge gets IP 172.16.0.1 with netmask /16, making it the <strong>gateway</strong> for all subnets in this VPC. This IP can route to any address in the 172.16.0.0/16 range.</p><ol><li><strong>Brings the bridge up:</strong></li></ol><pre>sudo ip link set br-vpc-1 up</pre><p>Activates the interface so it can pass traffic.</p><ol><li><strong>Kernel automatically adds route:</strong></li></ol><pre># Automatically created by kernel:<br>172.16.0.0/16 dev br-vpc-1 proto kernel scope link src 172.16.0.1</pre><p>This tells the host: “Any traffic for 172.16.0.0/16 should go through br-vpc-1.&quot;</p><p><strong>Result:</strong></p><ul><li>A virtual router (bridge) ready to connect subnets</li><li>Gateway IP assigned for subnet communication</li><li>Host can route to this VPC network</li></ul><p><strong>Verification:</strong></p><pre># Check bridge exists<br>ip link show br-vpc-1<br># Check IP assigned<br>ip addr show br-vpc-1<br># Check route added<br>ip route show | grep 172.16</pre><p><strong>Command 2: </strong><strong>add-subnet</strong></p><p><strong>Usage:</strong></p><pre>sudo vpcctl add-subnet &lt;vpc-name&gt; &lt;subnet-name&gt; &lt;cidr-block&gt; --type &lt;public|private&gt;</pre><p><strong>Example — Private Subnet:</strong></p><pre>sudo vpcctl add-subnet vpc-1 snt-1 172.16.1.0/24 --type private</pre><p><strong>Example — Public Subnet:</strong></p><pre>sudo vpcctl add-subnet vpc-1 snt-2 172.16.2.0/24 --type public</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Creates a network namespace (isolated network stack):</strong></li></ol><pre>sudo ip netns add snt-1</pre><p>Creates a completely isolated network environment. It’s like creating a separate virtual machine’s network, but lightweight.</p><ol><li><strong>Creates a veth pair (virtual ethernet cable):</strong></li></ol><pre>sudo ip link add veth-snt-1 type veth peer name veth-snt-1-br</pre><p>Creates two connected virtual interfaces:</p><ul><li>veth-snt-1: Will go inside the namespace (subnet)</li><li>veth-snt-1-br: Will connect to the bridge (VPC)</li></ul><ol><li><strong>Moves one veth end into the namespace:</strong></li></ol><pre>sudo ip link set veth-snt-1 netns snt-1</pre><p>veth-snt-1 now belongs to the snt-1 namespace and can only be seen/used inside it.</p><ol><li><strong>Connects other veth end to VPC bridge:</strong></li></ol><pre>sudo ip link set veth-snt-1-br master br-vpc-1</pre><p>Plugs veth-snt-1-br into the bridge, creating the connection: [Namespace] &lt;-veth-&gt; [Bridge]</p><ol><li><strong>Brings interfaces up:</strong></li></ol><pre>sudo ip link set veth-snt-1-br up<br>sudo ip netns exec snt-1 ip link set veth-snt-1 up<br>sudo ip netns exec snt-1 ip link set lo up</pre><p>Activates all interfaces so they can pass traffic.</p><ol><li><strong>Assigns IP address inside namespace:</strong></li></ol><pre>sudo ip netns exec snt-1 ip addr add 172.16.1.1/24 dev veth-snt-1</pre><p>The subnet gets the first usable IP (172.16.1.1) from its CIDR range.</p><ol><li><strong>Adds default route pointing to VPC gateway:</strong></li></ol><pre># First, add route to gateway itself<br>sudo ip netns exec snt-1 ip route add 172.16.0.1 dev veth-snt-1<br># Then set it as default gateway<br>sudo ip netns exec snt-1 ip route add default via 172.16.0.1 dev veth-snt-1</pre><p>This tells the subnet: “For any traffic going outside, send it to 172.16.0.1 (the VPC bridge).&quot;</p><ol><li><strong>If PUBLIC subnet, configure NAT:</strong></li></ol><pre># Enable MASQUERADE (NAT) for outbound traffic<br>sudo iptables -t nat -A POSTROUTING -s 172.16.2.0/24 ! -o br-vpc-1 -j MASQUERADE<br><br># Allow forwarding for this subnet<br>sudo iptables -A FORWARD -s 172.16.2.0/24 -j ACCEPT<br>sudo iptables -A FORWARD -d 172.16.2.0/24 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT</pre><p><strong>MASQUERADE explained:</strong> When a packet from 172.16.2.1 goes to the internet:</p><ul><li>Original: SRC=172.16.2.1, DST=8.8.8.8</li><li>After NAT: SRC=&lt;host-public-ip&gt;, DST=8.8.8.8</li><li>Return packet automatically translated back</li></ul><p><strong>If PRIVATE subnet, block internet:</strong></p><pre># Allow only VPC-internal traffic<br>sudo iptables -A FORWARD -s 172.16.1.0/24 -d 172.16.0.0/16 -j ACCEPT<br>sudo iptables -A FORWARD -d 172.16.1.0/24 -s 172.16.0.0/16 -j ACCEPT<br><br># Drop everything else<br>sudo iptables -A FORWARD -s 172.16.1.0/24 ! -d 172.16.0.0/16 -j DROP</pre><p><strong>Result:</strong></p><ul><li>Isolated subnet namespace created</li><li>Connected to VPC bridge via veth pair</li><li>Can communicate with other subnets in VPC</li><li>Public: Can access internet via NAT</li><li>Private: Blocked from internet</li></ul><p><strong>Verification:</strong></p><pre># Check namespace exists<br>sudo ip netns list<br><br># Check interfaces inside namespace<br>sudo ip netns exec snt-1 ip addr<br># Check routing inside namespace<br>sudo ip netns exec snt-1 ip route<br># Test connectivity to VPC gateway<br>sudo ip netns exec snt-1 ping -c 2 172.16.0.1</pre><h3>Command 3: peer-vpcs</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl peer-vpcs &lt;vpc-a&gt; &lt;vpc-b&gt;</pre><p><strong>Example:</strong></p><pre>sudo vpcctl peer-vpcs vpc-1 vpc-2</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Creates veth pair for peering:</strong></li></ol><pre>sudo ip link add veth-vpc-1 type veth peer name veth-vpc-2</pre><p>Creates a virtual cable to connect the two VPC bridges.</p><ol><li><strong>Connects veth ends to respective bridges:</strong></li></ol><pre>sudo ip link set veth-vpc-1 master br-vpc-1<br>sudo ip link set veth-vpc-2 master br-vpc-2</pre><p>Plugs each end into its VPC bridge:</p><pre>[br-vpc-1] &lt;-- veth-vpc-1 &lt;==&gt; veth-vpc-2 --&gt; [br-vpc-2]</pre><ol><li><strong>Brings interfaces up:</strong></li></ol><pre>sudo ip link set veth-vpc-1 up<br>sudo ip link set veth-vpc-2 up</pre><ol><li><strong>Assigns peering IPs:</strong></li></ol><pre>sudo ip addr add 192.168.255.1/30 dev veth-vpc-1<br>sudo ip addr add 192.168.255.2/30 dev veth-vpc-2</pre><p>Uses a small /30 network just for the peering link.</p><ol><li><strong>Adds static routes between VPCs:</strong></li></ol><pre># On host: traffic for VPC-2 goes via veth-vpc-2<br>sudo ip route add 172.20.0.0/16 via 192.168.255.2 dev veth-vpc-1<br><br># On host: traffic for VPC-1 goes via veth-vpc-1<br>sudo ip route add 172.16.0.0/16 via 192.168.255.1 dev veth-vpc-2</pre><ol><li><strong>Removes isolation rules in iptables:</strong></li></ol><pre># Remove DROP rules between VPCs<br>sudo iptables -D FORWARD -s 172.16.0.0/16 -d 172.20.0.0/16 -j DROP<br>sudo iptables -D FORWARD -s 172.20.0.0/16 -d 172.16.0.0/16 -j DROP<br><br># Add ACCEPT rules for peering<br>sudo iptables -A FORWARD -i br-vpc-1 -o br-vpc-2 -j ACCEPT<br>sudo iptables -A FORWARD -i br-vpc-2 -o br-vpc-1 -j ACCEPT</pre><ol><li><strong>Adds routes in each subnet to reach peer VPC:</strong></li></ol><pre># In snt-1 (VPC-1): add route to VPC-2 via local gateway<br>sudo ip netns exec snt-1 ip route add 172.20.0.0/16 via 172.16.0.1 dev veth-snt-1<br><br># In snt-3 (VPC-2): add route to VPC-1 via local gateway<br>sudo ip netns exec snt-3 ip route add 172.16.0.0/16 via 172.20.0.1 dev veth-snt-3</pre><p><strong>Packet flow after peering (snt-1 → snt-3):</strong></p><pre>[snt-1: 172.16.1.1] <br>    ↓ (via gateway 172.16.0.1)<br>[veth-snt-1] → [veth-snt-1-br] <br>    ↓<br>[br-vpc-1: 172.16.0.1]<br>    ↓ (route: 172.20.0.0/16 via 192.168.255.2)<br>[veth-vpc-1] &lt;==&gt; [veth-vpc-2]<br>    ↓<br>[br-vpc-2: 172.20.0.1]<br>    ↓<br>[veth-snt-3-br] → [veth-snt-3]<br>    ↓<br>[snt-3: 172.20.1.1] ✓</pre><p><strong>Result:</strong></p><ul><li>Two VPCs can now communicate</li><li>Routes configured at host and subnet level</li><li>Firewall rules allow peered traffic</li></ul><p><strong>Verification:</strong></p><pre># Check peering link<br>ip link show | grep veth-vpc</pre><pre># Check routes<br>ip route show | grep -E &quot;172.16|172.20&quot;</pre><pre># Test connectivity<br>sudo ip netns exec snt-1 ping -c 2 172.20.1.1</pre><h3>Command 4: apply-firewall</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl apply-firewall &lt;policy-file.json&gt;</pre><p><strong>Example:</strong></p><pre># Create policy file<br>cat &gt; firewall.json &lt;&lt;EOF<br>{<br>  &quot;subnet&quot;: &quot;172.16.1.0/24&quot;,<br>  &quot;ingress&quot;: [<br>    {&quot;port&quot;: 80, &quot;protocol&quot;: &quot;tcp&quot;, &quot;action&quot;: &quot;allow&quot;},<br>    {&quot;port&quot;: 22, &quot;protocol&quot;: &quot;tcp&quot;, &quot;action&quot;: &quot;deny&quot;},<br>    {&quot;port&quot;: 443, &quot;protocol&quot;: &quot;tcp&quot;, &quot;action&quot;: &quot;allow&quot;}<br>  ]<br>}<br>EOF</pre><pre>sudo vpcctl apply-firewall firewall.json</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Parses JSON policy file:</strong></li></ol><pre>with open(&quot;firewall.json&quot;) as f:<br>    policy = json.load(f)</pre><ol><li><strong>Finds target namespace from CIDR:</strong></li></ol><pre># Matches 172.16.1.0/24 → snt-1 namespace<br>namespace = get_namespace_by_subnet(&quot;172.16.1.0/24&quot;)</pre><ol><li><strong>Flushes existing rules:</strong></li></ol><pre>sudo ip netns exec snt-1 iptables -F INPUT</pre><p>Clears any previous firewall rules.</p><ol><li><strong>Adds rules for each policy entry:</strong></li></ol><pre># Allow TCP port 80<br>sudo ip netns exec snt-1 iptables -A INPUT -p tcp --dport 80 -j ACCEPT<br># Deny TCP port 22<br>sudo ip netns exec snt-1 iptables -A INPUT -p tcp --dport 22 -j DROP<br># Allow TCP port 443<br>sudo ip netns exec snt-1 iptables -A INPUT -p tcp --dport 443 -j ACCEPT</pre><ol><li><strong>Adds default policies:</strong></li></ol><pre># Allow established connections (return traffic)<br>sudo ip netns exec snt-1 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT<br><br># Allow loopback<br>sudo ip netns exec snt-1 iptables -A INPUT -i lo -j ACCEPT<br># Default: DROP everything else<br>sudo ip netns exec snt-1 iptables -P INPUT DROP</pre><p><strong>Rule evaluation order:</strong></p><pre>Packet arrives → Check rules in order:<br>1. Allow established/related connections<br>2. Allow loopback (lo)<br>3. Allow port 80<br>4. Drop port 22<br>5. Allow port 443<br>6. Default DROP (catches everything else)</pre><p><strong>Result:</strong></p><ul><li>Port 80: Accessible ✓</li><li>Port 443: Accessible ✓</li><li>Port 22: Blocked ✗</li><li>All other ports: Blocked (default DROP)</li></ul><p><strong>Verification:</strong></p><pre># Check rules inside namespace<br>sudo ip netns exec snt-1 iptables -L INPUT -v -n<br># Test allowed port<br>sudo ip netns exec snt-2 curl http://172.16.1.1:80<br># Test blocked port (should timeout)<br>sudo ip netns exec snt-2 nc -zv 172.16.1.1 22 -w 2</pre><h3>Command 5: deploy-workloads</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl deploy-workloads &lt;subnet-name&gt; &lt;port&gt;</pre><p><strong>Example:</strong></p><pre>sudo vpcctl deploy-workloads snt-1 8080</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Gets subnet IP address:</strong></li></ol><pre># Find the IP assigned to veth inside namespace<br>sudo ip netns exec snt-1 ip -4 addr show | grep &quot;inet &quot;<br># Returns: 172.16.1.1/24</pre><ol><li><strong>Starts HTTP server bound to subnet IP:</strong></li></ol><pre>sudo ip netns exec snt-1 python3 -m http.server 8080 --bind 172.16.1.1</pre><ol><li><strong>Server listens on namespace’s network stack:</strong></li></ol><pre>[snt-1 namespace]<br>    ↓<br>[veth-snt-1: 172.16.1.1]<br>    ↓ (listening on port 8080)<br>[Python HTTP Server]</pre><p><strong>Result:</strong></p><ul><li>HTTP server running inside subnet namespace</li><li>Accessible from other subnets in VPC</li><li>Accessible from peered VPCs (if peering enabled)</li><li>NOT accessible from internet (private subnet)</li></ul><p><strong>Verification:</strong></p><pre># From another subnet in same VPC<br>sudo ip netns exec snt-2 curl http://172.16.1.1:8080<br><br># Should see directory listing</pre><h3>Command 6: list-vpcs</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl list-vpcs</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Lists all bridge interfaces:</strong></li></ol><pre>sudo ip link show type bridge</pre><ol><li><strong>Filters for VPC bridges:</strong></li></ol><pre># Looks for bridges named &quot;br-vpc-*&quot;<br>if &quot;br-&quot; in line and &quot;docker&quot; not in line:<br>    vpc_name = line.split(&quot;br-&quot;)[1].split(&quot;:&quot;)[0]</pre><ol><li><strong>Gets CIDR for each VPC:</strong></li></ol><pre>sudo ip addr show br-vpc-1 | grep &quot;inet &quot;<br># Returns: 172.16.0.1/16</pre><ol><li><strong>Lists subnets attached to each VPC:</strong></li></ol><pre>sudo ip link show master br-vpc-1<br># Shows all interfaces connected to this bridge</pre><p><strong>Result:</strong></p><ul><li>Complete list of VPCs</li><li>CIDR blocks for each VPC</li><li>Subnets in each VPC</li></ul><h3>Command 7: show-vpc</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl show-vpc &lt;vpc-name&gt;</pre><p><strong>Example:</strong></p><pre>sudo vpcctl show-vpc vpc-1</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Checks VPC exists:</strong></li></ol><pre>sudo ip link show br-vpc-1</pre><ol><li><strong>Shows detailed bridge info:</strong></li></ol><pre>sudo ip addr show br-vpc-1</pre><ol><li><strong>Lists all subnets with IPs:</strong></li></ol><pre># For each subnet connected to bridge<br>sudo ip netns exec snt-1 ip addr show<br>sudo ip netns exec snt-2 ip addr show</pre><ol><li><strong>Shows routing table:</strong></li></ol><pre>ip route show | grep br-vpc-1</pre><p><strong>Result:</strong></p><ul><li>VPC details (CIDR, interfaces)</li><li>All subnets and their IPs</li><li>Routing information</li></ul><h3>Command 8: delete-vpc</h3><p><strong>Usage:</strong></p><pre>sudo vpcctl delete-vpc &lt;vpc-name&gt;</pre><p><strong>Example:</strong></p><pre>sudo vpcctl delete-vpc vpc-1</pre><p><strong>What happens under the hood:</strong></p><ol><li><strong>Gets list of all subnets:</strong></li></ol><pre>sudo ip link show master br-vpc-1</pre><ol><li><strong>For each subnet, deletes namespace:</strong></li></ol><pre># Delete veth pair (automatically removes both ends)<br>sudo ip link del veth-snt-1-br</pre><pre># Delete namespace (removes all interfaces inside)<br>sudo ip netns del snt-1</pre><ol><li><strong>Removes iptables rules:</strong></li></ol><pre># Remove NAT rules<br>sudo iptables -t nat -D POSTROUTING -s 172.16.1.0/24 ! -o br-vpc-1 -j MASQUERADE<br># Remove FORWARD rules<br>sudo iptables -D FORWARD -s 172.16.1.0/24 -j ACCEPT<br>sudo iptables -D FORWARD -d 172.16.1.0/24 -j ACCEPT<br># Remove isolation rules<br>sudo iptables -D FORWARD -s 172.16.0.0/16 -d 172.20.0.0/16 -j DROP</pre><ol><li><strong>Removes peering connections:</strong></li></ol><pre>sudo ip link del veth-vpc-1  # Also deletes veth-vpc-2</pre><ol><li><strong>Deletes the bridge:</strong></li></ol><pre>sudo ip link del br-vpc-1</pre><ol><li><strong>Kernel removes routes automatically:</strong></li></ol><pre># Route is automatically deleted when bridge is removed<br># 172.16.0.0/16 dev br-vpc-1 ← GONE</pre><p><strong>Result:</strong></p><ul><li>All namespaces deleted</li><li>All veth pairs removed</li><li>Bridge deleted</li><li>iptables rules cleaned up</li><li>Routes removed</li><li>System back to clean state</li></ul><p><strong>Verification:</strong></p><pre># Check no namespaces remain<br>sudo ip netns list | grep snt-<br># Check no bridge<br>sudo ip link show br-vpc-1  # Should error<br># Check routes clean<br>ip route show | grep 172.16  # Should be empty<br># Check iptables<br>sudo iptables -L FORWARD -v -n | grep 172.16  # Should be empty</pre><h3>Complete Demo Walkthrough</h3><p>Let’s build a complete two-VPC setup and test all scenarios.</p><h3>Step 1: Create Infrastructure</h3><pre># Create VPC 1 with private and public subnets<br>sudo vpcctl create-vpc vpc-1 172.16.0.1/16<br>sudo vpcctl add-subnet vpc-1 snt-1 172.16.1.0/24 --type private<br>sudo vpcctl add-subnet vpc-1 snt-2 172.16.2.0/24 --type public</pre><pre># Create VPC 2 with private and public subnets<br>sudo vpcctl create-vpc vpc-2 172.20.0.1/16<br>sudo vpcctl add-subnet vpc-2 snt-3 172.20.1.0/24 --type private<br>sudo vpcctl add-subnet vpc-2 snt-4 172.20.2.0/24 --type public</pre><pre># Verify<br>sudo vpcctl list-vpcs</pre><h3>Step 2: Testing Connectivity Within VPC</h3><p><strong>Deploy a test server in snt-1 (Terminal 1):</strong></p><pre>sudo vpcctl deploy-workloads snt-1 8080</pre><p><strong>Test from snt-2 (Terminal 2):</strong></p><pre># Should SUCCEED - same VPC communication<br>sudo ip netns exec snt-2 curl http://172.16.1.1:8080</pre><p><strong>Expected Result:</strong> Connection successful — subnets within same VPC can communicate.</p><h3>Step 3: Testing Internet Access</h3><pre># Public subnet - should SUCCEED<br>sudo ip netns exec snt-2 ping -c 4 8.8.8.8<br>sudo ip netns exec snt-2 curl -I https://google.com</pre><pre># Private subnet - should FAIL<br>sudo ip netns exec snt-1 ping -c 4 8.8.8.8</pre><p><strong>Expected Results:</strong></p><ul><li>snt-2 (public) can reach internet</li><li>snt-1 (private) blocked from internet (timeout)</li></ul><p><strong>Why?</strong></p><ul><li>Public subnets have NAT MASQUERADE rules enabling internet access</li><li>Private subnets have explicit DROP rules for non-VPC traffic</li></ul><h3>Step 4: Testing VPC Isolation</h3><pre># Try to reach VPC-2 from VPC-1 (no peering)<br>sudo ip netns exec snt-2 ping -c 4 172.20.2.1</pre><p><strong>Expected Result:</strong> Connection timeout — VPCs are isolated by default.</p><p><strong>Why?</strong> The default FORWARD policy is DROP, and there are no ACCEPT rules between VPCs.</p><h3>Step 5: Testing VPC Peering</h3><pre># Enable peering<br>sudo vpcctl peer-vpcs vpc-1 vpc-2</pre><pre># Now test again<br>sudo ip netns exec snt-2 ping -c 4 172.20.2.1<br>sudo ip netns exec snt-1 ping -c 4 172.20.1.1</pre><p><strong>Expected Result:</strong> Both tests succeed — peering allows cross-VPC communication.</p><h3>Step 6: Testing Firewall Rules</h3><p><strong>Create firewall policy:</strong></p><pre>cat &gt; /tmp/firewall-snt1.json &lt;&lt;EOF<br>{<br>  &quot;subnet&quot;: &quot;172.16.1.0/24&quot;,<br>  &quot;ingress&quot;: [<br>    {&quot;port&quot;: 8080, &quot;protocol&quot;: &quot;tcp&quot;, &quot;action&quot;: &quot;allow&quot;},<br>    {&quot;port&quot;: 22, &quot;protocol&quot;: &quot;tcp&quot;, &quot;action&quot;: &quot;deny&quot;}<br>  ]<br>}<br>EOF</pre><pre>sudo vpcctl apply-firewall /tmp/firewall-snt1.json</pre><p><strong>Test allowed port:</strong></p><pre># Terminal 1: Server already running on port 8080<br># (from Step 2)</pre><pre># Terminal 2: Should SUCCEED<br>sudo ip netns exec snt-2 curl <a href="http://172.16.1.1:8080/">http://172.16.1.1:8080</a></pre><p><strong>Test blocked port:</strong></p><pre># Should TIMEOUT<br>sudo ip netns exec snt-2 nc -zv 172.16.1.1 22 -w 2</pre><p><strong>Expected Results:</strong></p><ul><li>Port 8080 accessible</li><li>Port 22 blocked</li></ul><h3>Testing Summary</h3><p>Test Scenario Command Expected Result Same VPC communication</p><p>sudo ip netns exec snt-2 curl http://172.16.1.1:8080 ✅ Success Public subnet → Internet</p><p>sudo ip netns exec snt-2 ping 8.8.8.8 ✅ Success Private subnet → Internet</p><p>sudo ip netns exec snt-1 ping 8.8.8.8 ❌ Timeout (blocked) Cross-VPC (no peering)</p><p>sudo ip netns exec snt-2 ping 172.20.2.1 ❌ Timeout (isolated) Cross-VPC (after peering)</p><p>sudo ip netns exec snt-2 ping 172.20.2.1 ✅ Success Firewall - Allowed port</p><p>sudo ip netns exec snt-2 curl http://172.16.1.1:8080 ✅ Success Firewall - Blocked port</p><p>sudo ip netns exec snt-2 nc -zv 172.16.1.1 22 ❌ Timeout (blocked)</p><h3>Cleanup</h3><p>After testing, clean up all resources:</p><pre># Delete VPC 1 (automatically removes all subnets)<br>sudo vpcctl delete-vpc vpc-1</pre><pre># Delete VPC 2<br>sudo vpcctl delete-vpc vpc-2</pre><pre># Verify cleanup<br>sudo vpcctl list-vpcs<br>sudo ip netns list<br>sudo iptables -L FORWARD -v -n</pre><p><strong>Expected Output:</strong></p><pre>No VPCs found</pre><h3>How It Works: Architecture Deep Dive</h3><h3>Packet Flow: Private Subnet to Private Subnet (Same VPC)</h3><p>When snt-1 (172.16.1.1) pings snt-2 (172.16.2.1):</p><pre>1. [snt-1 namespace]<br>   Source: 172.16.1.1<br>   Destination: 172.16.2.1<br>   <br>2. Check routing table in snt-1:<br>   172.16.2.1 → default via 172.16.0.1<br>   <br>3. Packet sent through veth-snt-1<br>   <br>4. Arrives at veth-snt-1-br (on bridge)<br>   <br>5. [br-vpc-1 bridge]<br>   Bridge sees: DST=172.16.2.1<br>   Looks at connected interfaces<br>   Finds: veth-snt-2-br leads to 172.16.2.0/24<br>   <br>6. Forwards to veth-snt-2-br<br>   <br>7. Packet goes through veth pair to veth-snt-2<br>   <br>8. [snt-2 namespace]<br>   Receives packet<br>   Sends reply back same path</pre><h3>Packet Flow: Public Subnet to Internet</h3><p>When snt-2 (172.16.2.1) accesses google.com (142.250.185.46):</p><pre>1. [snt-2 namespace]<br>   SRC: 172.16.2.1<br>   DST: 142.250.185.46<br>   <br>2. Routing: default via 172.16.0.1<br>   <br>3. Packet → veth-snt-2 → veth-snt-2-br<br>   <br>4. [br-vpc-1]<br>   DST not in 172.16.0.0/16<br>   Forward to host<br>   <br>5. [Host iptables - FORWARD chain]<br>   Check rules for 172.16.2.0/24<br>   ACCEPT (public subnet rule)<br>   <br>6. [Host iptables - NAT POSTROUTING]<br>   Match: -s 172.16.2.0/24 -j MASQUERADE<br>   Rewrite: SRC=172.16.2.1 → SRC=&lt;host-eth0-IP&gt;<br>   <br>7. [Host routing]<br>   DST=142.250.185.46<br>   Route via default gateway (internet)<br>   <br>8. Packet sent to internet with host&#39;s public IP<br>   <br>9. Reply comes back to host<br>   <br>10. [Conntrack]<br>    Remembers: 142.250.185.46 → was originally 172.16.2.1<br>    Rewrites: DST=&lt;host-IP&gt; → DST=172.16.2.1<br>    <br>11. Packet routed back through br-vpc-1 → snt-2</pre><h3>Packet Flow: Cross-VPC After Peering</h3><p>When snt-1 (172.16.1.1) in VPC-1 pings snt-3 (172.20.1.1) in VPC-2:</p><pre>1. [snt-1 namespace]<br>   SRC: 172.16.1.1<br>   DST: 172.20.1.1<br>   <br>2. Routing table:<br>   172.20.0.0/16 via 172.16.0.1<br>   <br>3. veth-snt-1 → veth-snt-1-br<br>   <br>4. [br-vpc-1]<br>   DST=172.20.1.1<br>   <br>5. [Host routing table]<br>   172.20.0.0/16 via 192.168.255.2 dev veth-vpc-1<br>   <br>6. Packet → veth-vpc-1 &lt;==&gt; veth-vpc-2<br>   <br>7. [br-vpc-2]<br>   DST=172.20.1.1 (in 172.20.0.0/16)<br>   Forward to veth-snt-3-br<br>   <br>8. veth-snt-3-br → veth-snt-3<br>   <br>9. [snt-3 namespace]<br>   Receives packet<br>   Reply follows reverse path</pre><h3>Key Takeaways</h3><ol><li><strong>Network Namespaces</strong> provide complete network isolation, allowing multiple isolated network stacks on one machine</li><li><strong>Veth pairs</strong> are virtual cables that connect isolated namespaces to the host or bridges</li><li><strong>Linux bridges</strong> act as virtual routers, forwarding traffic between connected interfaces</li><li><strong>iptables NAT (MASQUERADE)</strong> translates private IPs to public IPs, enabling internet access</li><li><strong>Default DROP policy + explicit rules</strong> ensures security by design — nothing is allowed unless explicitly permitted</li><li><strong>VPC peering</strong> requires coordination at multiple levels: veth connections, routing tables, and firewall rules</li><li><strong>Routing tables</strong> at both host and namespace level determine packet paths</li><li><strong>Connection tracking (conntrack)</strong> enables stateful firewalls and NAT return traffic</li></ol><h3>Conclusion</h3><p>Hey! You’ve just built a VPC system using only Linux primitives! This is fundamentally how cloud providers implement their networking — they just do it at massive scale with additional abstractions and features.</p><p>Understanding these concepts gives you deep insight into:</p><ul><li><strong>Container networking</strong> — How Docker and Kubernetes network containers</li><li><strong>Cloud VPCs</strong> — What’s really happening behind AWS, GCP, and Azure VPCs</li><li><strong>Network security</strong> — Defense-in-depth with multiple isolation layers</li><li><strong>Linux kernel networking</strong> — The powerful capabilities built into Linux</li></ul><p>The skills you’ve learned here apply directly to:</p><ul><li>DevOps and cloud engineering roles</li><li>Container orchestration platforms</li><li>Network security implementations</li><li>Infrastructure automation</li><li>Cloud architecture design</li></ul><h3>Full Project Code</h3><p><strong>Repository:</strong> [<a href="https://github.com/carvanino/hng13-stage0-devops.git">Github</a>]</p><p>The complete implementation includes:</p><ul><li>vpcctl.py - Main CLI tool</li><li>utils.py - Networking utility functions</li><li>firewalls.json - Example firewall policies</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d951b0aceb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing My First Web App as a Software Developer]]></title>
            <link>https://medium.com/@akinolatofunmi/designing-my-first-web-app-as-a-software-developer-db288b8e9ee3?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/db288b8e9ee3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-devlopment]]></category>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 13:20:37 GMT</pubDate>
            <atom:updated>2023-03-09T13:20:37.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="ClibSync Banner" src="https://cdn-images-1.medium.com/max/1024/0*SONNtkebj3Ast-kn" /><figcaption>ClibSync</figcaption></figure><p>In May 2021, I enrolled in the alx_africa Software Engineering 12-month Training program powered by Holberton School and the Mastercard Scholarship Foundation. As a student, I quickly discovered my passion for programming in C and Python, which led me to specialize as a backend developer. Eight months into the program, I successfully deployed my first web app, ClibSync.</p><p><strong>What is ClibSync?</strong></p><p>ClibSync is a clipboard-syncing application allowing users to seamlessly copy and paste content across multiple devices, such as texts and documents. The app provides a centralized point for storing and accessing copied data across all devices with just a single copy-and-paste operation.</p><p>As a student and software developer, I often found myself needing to move files or code snippets between two devices. My only options were to use a cloud storage service or send the content to a social media platform I was signed in on both devices. ClibSync aims to provide a service for users who want to streamline their workflow and improve productivity by accessing their clipboard content on all devices in a secure and seamless manner.</p><figure><img alt="ClibSync User Interface" src="https://cdn-images-1.medium.com/max/1024/0*scOZKqh4PnaySXiF" /><figcaption>User Interface</figcaption></figure><p>I worked on this project as a software developer alongside my team member Ibrahim Ibrahim, who worked as a product engineer. We both decided to build this app because it was a problem we both encountered and wanted to solve. The deployment of the first version of ClibSync has been successful, and I’m excited to continue refining the project so that each feature works properly.</p><p><strong>Technologies</strong></p><p>We used HTML, CSS, and JS to build the landing page of the website. For the front-end framework, we used VueJS to make the application more sophisticated and scalable. REST API was used for communication between the front-end and back-end, and we used a Firebase real-time database for the database. User authentication was also hosted on Firebase.</p><p><strong>Challenges and Current Features</strong></p><p>As my first hands-on project, I encountered some challenges. Web responsiveness in the project was a challenge, but it was a worthwhile experience.</p><p>During the testing phase of our project, we encountered a challenge with data duplication on iOS devices while using the Safari browser. Initially, we thought that there might have been a conflict between the iOS clipboard-sharing utility and the clipboard API, but after extensive research on the error message returned from the console,</p><blockquote>‘the request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission’</blockquote><p>we discovered that as a security feature on iOS devices, sending content to the clipboard has to be done with the user’s permission. Therefore, the sending of data could not happen automatically except when initiated by the user, which was preventing us from collecting the copied content from the user’s clipboard and sending a POST request to the database.</p><p>To address this issue, we added a button to the user interface for iOS-webkit devices to manually push data from the user’s clipboard to the user’s database. However, we are not entirely satisfied with this fix as it takes away from the seamless transfer of copied data to the user’s database and affects the overall user experience on Safari. We are continuing to explore alternative solutions to this issue and hope to find a better solution soon.</p><p>In the version of the project released for deployment, we have integrated the following features:</p><ul><li>Web responsiveness across all devices</li><li>Realtime data synchronization</li><li>Data protection</li><li>A functioning app to get text-like copied data across devices</li></ul><p>We are currently working on adding a functioning app to get other forms of copied data across devices.</p><p>Overall, working on this project has been an exciting and challenging experience, and I’ve enjoyed working with my partner Ibrahim. As my first hands-on project, I learned a lot about web development, front-end frameworks, and Firebase.</p><p>In retrospect, if I were to start this project again, I would have liked to do all the hard coding myself, even though Firebase made it easier to meet our deadline of one month. As a software engineer, I have come to understand the importance of every aspect of software development, from designing the web architecture and the user interface to the development stages. Nothing is too simple or too difficult in software engineering; it just takes time and careful research. I have also come to appreciate the importance of improving my front-end development skills, as every aspect of software development is equally essential and should not be undermined.</p><p>In conclusion, this project has reinforced my interest in the back-end development of web applications, but it has also made me realize the need to improve my front-end development skills. Although JavaScript is an extremely powerful language that can be used for anything, I still prefer Python.</p><p>For those interested in checking out the project, you can find the GitHub repository <a href="https://github.com/Isquare007/ClipSync">here</a>. The deployed project can be accessed <a href="https://clip-sync-sandy.vercel.app/">here</a>. Your welcomed feedback is desired.</p><p>As for me, I am a passionate software engineer who enjoys working on innovative solutions with a keen interest in developing high-quality software that meets the needs of users. I have experience in both front-end and back-end development, and I am always looking for opportunities to expand my skillset and tackle new challenges. Also, please feel free to connect with me on <a href="https://www.linkedin.com/in/oluwatofunmi-ac/">LinkedIn</a> to learn more about my background and experience as a software engineer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db288b8e9ee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What happens when you type ‘https://www.google.com’ in your browser and press "Enter"]]></title>
            <link>https://medium.com/@akinolatofunmi/what-happens-when-you-type-https-www-google-com-in-your-browser-and-press-enter-e766a4ae80d0?source=rss-5fed123f13e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e766a4ae80d0</guid>
            <category><![CDATA[the-web]]></category>
            <category><![CDATA[webstuff]]></category>
            <category><![CDATA[internet-and-technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Akinola Oluwatofunmi]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 21:55:20 GMT</pubDate>
            <atom:updated>2023-03-25T16:42:33.582Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Curiosity may have killed the cat, but it’s important to be curious and want to understand how things work. It’s interesting that you are curious about what happens behind the scenes when you use a web browser and visit a website. Not many people care to know these things, so you are special in that regard</em>.</p><figure><img alt="Curious cat" src="https://cdn-images-1.medium.com/max/1024/1*tVDtg-PDj0V8pnAOkO4blg.jpeg" /><figcaption>You, the curious cat! Let’s ride!</figcaption></figure><p>Let’s create a scenario to help you better understand the process. Imagine you just bought a new HP Spectre and installed the latest version of Windows on it. You are excited to get started and decide to install your favourite web browser (Google Chrome for me). After installation, you sign in and are ready to start using it.</p><p>You open your web browser and type “https://www.google.com&quot; into the search bar, then hit <strong>enter</strong>. As you type the web address into the browser, your computer searches through its cache using indexes to see if it has the URL(Uniform Resource Locator) stored. It wants to know if you have visited that particular address before. However, since this is a new computer and you have never used it to access the web, it doesn’t find anything in the cache or host file.</p><blockquote>It’s important to remember that computers and other devices use Internet Protocol (IP) addresses to communicate with each other on the internet. It’s easier for humans to use text addresses (URLs) instead of IP addresses, so we have something called the Domain Name System (DNS) to link a web address to an IP address.</blockquote><blockquote>When you type “<a href="https://www.google.com/">https://www.google.com</a>&quot; into the web browser, you are trying to access a web server owned by Google. This web server has a unique IP address, which both you nor the browser know at this point. There are two types of IP addresses: IPv4 and IPv6. IPv4 addresses have a 32-bit address length and are divided into four fields separated by dots (e.g., 192.132.5.62). IPv6 addresses have a 128-bit address length and are divided into eight fields separated by colons (e.g., 3ffe:1900:fe21:4545::).</blockquote><p>Your computer strips the domain name from the URL and checks with the operating system (OS) to see if it can retrieve the IP address of the domain name “google.com”. Since this is the first time you are accessing this web address from your computer, the OS doesn’t find anything in its cache or host file. Therefore, it sends a request to the DNS resolver.</p><p><strong>THE DNS LOOKUP</strong></p><p>The DNS resolver is the first stop in the DNS lookup process. It is responsible for receiving DNS queries from web browsers and other applications and is usually operated by the client’s local network or an Internet Service Provider (ISP). The resolver looks into its cache, if the resolver does not find the address in its cache, it sends a request to the root server. The root server then locates the Top Level Domain (TLD) server address which is responsible for the domain’s TLD (e.g., .com, .org, .net), in our case the .com TLD server address. The root server also saves this address so that when the same query is received, fewer queries are needed. The resolver sends the same request to the .com TLD server, but this server does not have the IP address for the domain name google.com. However, it does return the domain’s authoritative name server. The resolver then sends the request to the domain name server, which returns the IP address for the domain name google.com to be 216.58.223.206. The resolver saves this address in its cache and also gives the information to the OS to do the same. Now, when the user wants to access the web address <a href="https://www.google.com/">https://www.google.com</a>, fewer queries are needed.”</p><p><strong>TCP/IP</strong></p><p>Transport Control Protocol is one of the main protocols on the internet protocol suite. It is located between the Application and Network Layers in the OSI Network model. In simple terms, Transport Control Protocol is a transport protocol that sits on top of the Internet Protocol to ensure the reliable transfer of data packets.</p><p><strong>FIREWALL</strong></p><p>The firewall is a security measure at the network layer that monitors both incoming and outgoing traffic, allowing or blocking the transmission of data packets based on predetermined rules and regulations. Firewalls guard traffic at entry points called ports on a computer. For example, if we were using our new computer in the office and accessing the internet through the office’s network, when we type <a href="https://www.google.com/">https://www.google.com</a> into the address bar of our web browser, our browser will first retrieve the IP address of the google.com domain from the operating system through the DNS lookup. When the IP address is retrieved, HTTPS specifies the port number to be used when accessing the IP address, which is port 443. This means that the IP address 216.58.223.206 must be accessed through port 443. If for some reason, our corporate network does not allow employees to visit any search engine except <a href="https://bing.com/">https://bing.com</a> (204.79.197.200) when using the company’s internet, and we try to access 216.58.223.206, we will receive an “access denied” response from our browser. This is because it has been specified on the network layer that only 204.79.197.200 can be accessed.</p><p><strong>HTTPS/SSL</strong></p><p>Hyper Text Transfer Protocol Secure is a secure version of HTTP that uses SSL/TSL (Secure Socket Layer/Transport Layer Security) to encrypt data packets sent and received over the internet. HTTPS is used on websites that require sensitive information to be transmitted, such as online banking and online shopping. A website like google.com will have an SSL certificate on the server where it is hosted. The certificate contains a public key and the identity of the website. When our web browser tries to connect to the google.com website using the address, the browser sends a request for the server to identify itself. The server then sends its SSL certificate to the browser. Once the authenticity of the address can be verified by the browser using the SSL certificate, the browser and the web server create an encrypted session using the public key of the SSL certificate. Any data or information exchanged between the website and the user becomes encrypted and secure.</p><p><strong>LOAD BALANCER</strong></p><p>A load balancer is a device that helps to balance the load on a server by distributing network traffic across multiple servers. This improves the performance and reliability of a network. For example, a website like google.com with millions of users sending different requests at the same time would not be able to handle the load on a single server. If a single server were used, the website would frequently crash because there is a single point of failure in the entire system. If something were to happen to the server at any time, it would result in global downtime, which is not desirable. This is where load balancers come in handy. When a user sends a request to a server, the load balancer receives the request and, based on its algorithm, sends the request to one of the available servers. The server receives the request and sends it back to the load balancer. The load balancer keeps track of the user’s IP address and sends the response back to the user.</p><p><strong>WEB SERVER</strong></p><p>A web server is a combination of software and hardware that uses the HTTP protocol to respond to user requests. The hardware part of a web server is connected to the internet and allows data exchange with other devices, as well as storing the website files that are delivered to your web browser. The software controls how users access files on the web server, processing and answering incoming requests. In our case, when we send a GET request to a web server using secured HTTP, we are requesting to get the index page (index.html) file for the domain name google.com. This page is hosted on the web server. The server receives the request and sends a corresponding response back to your web browser.</p><p><strong>APPLICATION SERVER</strong></p><p>When a web page becomes dynamic, you can think of your request reaching an application server, which feeds you the content you receive on your web browser. An application server is used to update web files that are hosted on a web server before they are sent. For example, Now that we have been served the google.com webpage when you search “Askew” or “Do a barrel roll” on Google, the application server is responsible for updating the web page to show the results.</p><p><strong>DATABASE</strong></p><p>A database is a collection of data that is organized and can be easily accessed, managed, and updated. It is used to store, retrieve, and manipulate data. In the scenario we have been following, we would only access the database servers when we try to use the Google search engine. When you search for something on <a href="https://www.google.com/">https://www.google.com</a> in your browser, your request is sent as a query to one of the Google servers. The server processes the query and retrieves a list of relevant web pages from its database. Google has a very large database that stores all the web pages that have been crawled and indexed by Google’s web crawlers. The database system searches through its stored web pages to find the ones that are most relevant to your search query and returns a list of these web pages to the Google server. The server ranks the web pages based on relevance and returns a list of the web pages to your web browser. These are what is displayed to you in the search results.</p><p>Understanding how the web stack works is a deep dive and we’ve only scratched the surface by touching specific content. All of the concept described above happens within a second or less. It’s so interesting to see the beauty of Software Engineering. I hope you learnt something today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e766a4ae80d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>