<?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 Oluwatobiloba Olamide on Medium]]></title>
        <description><![CDATA[Stories by Oluwatobiloba Olamide on Medium]]></description>
        <link>https://medium.com/@oluwateezzy03?source=rss-99f5ff9a805b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sRQqafno2BSR6WqYDFzz2A.jpeg</url>
            <title>Stories by Oluwatobiloba Olamide on Medium</title>
            <link>https://medium.com/@oluwateezzy03?source=rss-99f5ff9a805b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:14:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oluwateezzy03/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[Java Learning Journey: Classes, Objects and Its Members]]></title>
            <link>https://oluwateezzy03.medium.com/java-learning-journey-classes-objects-and-its-members-ff1c316e0f80?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff1c316e0f80</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 15:28:18 GMT</pubDate>
            <atom:updated>2026-07-05T15:28:18.358Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A walkthrough of one of the most foundational ideas in Java and in Object-Oriented Programming.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ipf2c5jLvc3jyxodRN67fA.jpeg" /></figure><p>If you’re new to Java, you will hear the words “class” and “object” before you hear almost anything else. And for good reason they’re the backbone of how Java organizes code. In this Articles, I want to walk through what I learned about classes, objects, and their members, using real code examples to make the ideas concrete rather than abstract.</p><p><strong>By the end, you should understand:</strong></p><ul><li>What a class is (and how it differs from an object)</li><li>Instance variables vs. static (class) variables</li><li>Constructors, and how constructor overloading and chaining work</li><li>Instance methods vs. static methods, and how method overloading works</li><li>Varargs — Java’s way of accepting a flexible number of arguments</li><li>How Java actually passes data to methods (pass-by-value, explained properly)</li><li>Where objects live in memory, and why that matters</li></ul><h3>Classes and Objects</h3><p>Object-Oriented Programming (OOP) is Java’s way of modeling real-world scenarios in a natural way. The core idea is simple once you find the right analogy:</p><blockquote>A class is like a blueprint. An object is the actual house built from that blueprint.</blockquote><p>A blueprint describes what a house <em>can</em> have rooms, doors, windows but it is not a house itself. You can’t live in a blueprint. Once you build a house from it, though, you have something real, with its own address, its own furniture, its own occupants.<br>In Java terms:</p><pre>public class CustomerOrder {<br>    // define static variable<br>    static int orderNumber = 1000;<br>    static double seniorDiscount = 2;<br>    static double price = 10.0;<br><br>    // define instance variable<br>    int quantity = 1;<br>    double orderAmount;<br>    boolean seniorCitizen;<br><br>    void generateOrderBill(){<br>        orderNumber = orderNumber + 1;<br>        orderAmount = price * quantity;<br><br>        if (seniorCitizen) {<br>            orderAmount = orderAmount - seniorDiscount;<br>        }<br>    }<br>}</pre><p>CustomerOrder is the blueprint. Every time we write new CustomerOrder(), Java builds a new &quot;house&quot; a new object based on that blueprint:</p><pre>CustomerOrder order1 = new CustomerOrder();<br>order1.quantity = 2;<br>order1.seniorCitizen = true;<br>order1.generateOrderBill();</pre><p>order1 is an object (also called an <em>instance</em>) of the class CustomerOrder. It has its own quantity, its own orderAmount, and its own seniorCitizen flag separate from any other CustomerOrder object we create.</p><h3>Instance Variables vs. Static (Class) Variables</h3><p>This is one of the trickiest distinctions for beginners, so let’s slow down here. Instance variables belong to each individual object. Every object gets its <em>own copy</em>. Static variables (also called class variables) belong to the <em>class itself</em>. There is only one copy, shared by every object of that class.<br>Look again at CustomerOrder:</p><pre>static int orderNumber = 1000;   // shared across ALL orders<br>int quantity = 1;                 // unique to EACH order</pre><p>Now watch what happens across three orders:</p><pre>CustomerOrder order1 = new CustomerOrder();<br>order1.quantity = 2;<br>order1.seniorCitizen = true;<br>order1.generateOrderBill();<br>System.out.println(&quot;Order Number: &quot; + CustomerOrder.orderNumber); // 1001<br><br>CustomerOrder order2 = new CustomerOrder();<br>order2.quantity = 3;<br>order2.generateOrderBill();<br>System.out.println(&quot;Order Number: &quot; + CustomerOrder.orderNumber); // 1002<br><br>CustomerOrder order3 = new CustomerOrder();<br>order3.seniorCitizen = true;<br>order3.generateOrderBill();<br>System.out.println(&quot;Order Number: &quot; + CustomerOrder.orderNumber); // 1003</pre><p>Every time generateOrderBill() runs, it increments orderNumber. Because orderNumber is static, that increment is visible to <em>every</em> object, it&#39;s the same variable being shared, not three separate copies. That&#39;s why we access it as CustomerOrder.orderNumber (via the class name) rather than through a specific order. Contrast that with quantity, which is an instance variable — order1.quantity, order2.quantity, and order3.quantity are three completely independent values.<br>A more elaborate example of this shows up in Student5:</p><pre>public class Student5 {<br>    static int computeCount;   // shared counter across ALL students<br>    String name;<br>    String gender;<br>    int age;<br>    boolean international;<br><br>    void compute() {<br>        computeCount = computeCount + 1;<br>        // ...<br>    }<br>}</pre><p>Every time <em>any</em> Student5 object calls compute(), the shared computeCount ticks up, it&#39;s tracking how many times compute() has run across <em>all</em> students, not per student.</p><p><strong>Rule of thumb:</strong> if a value should be unique to each object, make it an instance variable. If it should be shared and tracked across the whole class, make it static.</p><h3>Constructors: Setting Up an Object’s Initial State</h3><p>A constructor is a special block of code that runs when you create an object with new. Its job is to initialize the object&#39;s state.</p><pre>public class Book {<br>    public String title;<br><br>    public Book(String title) {<br>        this.title = title;<br>    }<br><br>    public void setTitle(String title) {<br>        this.title = title;<br>    }<br><br>    public String getTitle() {<br>        return title;<br>    }<br>}</pre><p>Notice this.title = title;. The parameter is named title, and so is the instance variable this tells Java &quot;I mean the instance variable, not the parameter.&quot; Without this, Java would assume you meant the parameter, and the instance variable would never get set.</p><h4>Constructor Overloading</h4><p>Just like methods, constructors can be overloaded meaning a class can have multiple constructors, as long as their parameter lists differ (in number or type of parameters).</p><p>Instructor is a great example:</p><pre>public class Instructor {<br>    public long id;<br>    public String name;<br>    public String title;<br>    public String department;<br>    public Book[] books;<br><br>    public Instructor(long id, String name, String title, String department, Book[] books) {<br>        this.id = id;<br>        this.name = name;<br>        this.title = title;<br>        this.department = department;<br>        this.books = books;<br>    }<br><br>    public Instructor(long id, String name, String title, String department) {<br>        this(id, name, title, department, new Book[0]);<br>    }<br><br>    public Instructor(long id, String name, String title) {<br>        this(id, name, title, title, null);<br>    }<br><br>    public Instructor(long id, String name) {<br>        this(id, name, null);<br>    }<br>}</pre><p>Four different constructors, each accepting a different combination of arguments. This gives whoever uses the Instructor class flexibility they can provide as much or as little detail as they have available at the time.</p><h4>Constructor Chaining</h4><p>Look closely at how each constructor above calls this(...) that&#39;s constructor chaining. Instead of repeating initialization logic in every constructor, the simpler constructors delegate to the more complete one.</p><p><strong>Two important rules govern this:</strong></p><ol><li>The this(...) call must be the first statement in the constructor.</li><li>You can only have one such chaining call per constructor.</li></ol><p>Student6 shows this pattern too:</p><pre>Student6(int id, String name, String gender, int age, long phone, double gpa, char degree) {<br>    this(id, name, gender, age, phone, gpa, degree, false);<br>}<br><br>Student6(int id, String name, String gender, int age, long phone, double gpa,<br>          char degree, boolean international) {<br>    this.id = id;<br>    this.name = name;<br>    // ... full initialization happens here<br>}</pre><p>The shorter constructor just calls the longer one, passing false as a sensible default for international. This avoids duplicating the entire initialization block a small thing, but it keeps code clean and easier to maintain.</p><p><strong>One more rule worth knowing:</strong> constructors cannot call themselves recursively, directly or indirectly Java’s compiler will catch that.</p><h3>Instance Methods vs. Static Methods</h3><p>Just like variables, methods can be instance methods (operate on a specific object) or static methods (belong to the class itself, often used as utility functions).</p><pre>boolean updateProfile(String name) {<br>    this.name = name;<br>    return true;<br>}</pre><p>This is an instance method, it needs a specific Student6 object to operate on, because it changes <em>that</em> object&#39;s name.</p><p>Compare that to a static method like go in the Test class:</p><pre>static int go(byte a, byte b){<br>    return a + b;<br>}</pre><p>You don’t need an object to call this, you call it directly on the class: Test.go(b1, b2). It doesn&#39;t depend on or modify any particular object&#39;s state.</p><h4>Method Overloading</h4><p>Method overloading means having multiple methods with the <em>same name</em> but <em>different parameter lists</em> in the same class. Java figures out which one to call based on the arguments you pass.</p><pre>static void go(int[] array) {<br>    System.out.println(&quot;array[0] &quot; + array[0]);<br>}<br><br>static void go(int i) {<br>    System.out.println(&quot;array i&quot;);<br>}<br><br>static void go(short s) {<br>    System.out.println(&quot;short s&quot;);<br>}</pre><p>Three methods, all named go, but each accepts something different, an array, an int, or a short. Java resolves which one to invoke by matching the argument type at compile time.</p><p><strong>A subtlety worth remembering:</strong> changing only the return type does not count as overloading. The parameter list has to differ. This is why Java rejects code where two methods share a name and parameter list but differ only in return type.</p><p>Another subtlety, shown in the Test class comments: Java does not perform implicit narrowing conversions during method or constructor invocation even though it <em>does</em> allow that during a plain assignment. For example:</p><pre>byte b = 65; // works fine — implicit narrowing on assignment is allowed<br><br>static int go(byte a, byte b){ return a + b; }<br>// go(65, 65);  // this would NOT compile — int literal can&#39;t implicitly narrow to byte here</pre><p>Java’s designers made this choice deliberately, to avoid extra ambiguity when the compiler is deciding which overloaded method to call.</p><h3>Varargs: Flexible Argument Counts</h3><p>Sometimes you don’t know in advance how many arguments a method should accept. That’s where varargs (variable-length arguments) come in, denoted by three dots (...):</p><pre>static void varargsOverload(boolean b, int... list) {<br>    System.out.println(&quot;list.length: &quot; + list.length);<br>}</pre><p>You can now call this with any number of int arguments:</p><pre>varargsOverload(true, 1, 2, 3);<br>varargsOverload(true, 1, 2, 3, 4, 5, 6, 7, 8);<br>varargsOverload(true); // zero ints is fine too</pre><p><strong>Two rules to remember:</strong></p><ol><li>A varargs parameter must be the last parameter in the method signature.</li><li>A method can have only one varargs parameter.</li></ol><p>Under the hood, Java treats the varargs parameter as an array, so you could just as easily call varargsOverload(true, new int[]{1,2,3}).</p><h3>Pass-by-Value: How Java Actually Passes Data</h3><p>This trips up a lot of people coming from other languages, so it’s worth stating clearly:</p><blockquote><em>Java is always pass-by-value even when you’re passing objects.</em></blockquote><p>For primitives, this is intuitive: the actual value gets copied into the method parameter.</p><p>For objects, what gets copied is the value of the reference, essentially, the object’s memory address. The method doesn’t get a brand-new object; it gets a copy of the address pointing to the <em>same</em> object on the heap.</p><p>This is why a method <em>can</em> change an object’s internal state:</p><pre>static void go(int[] array) {<br>    array[1] = 22; // this changes the actual array the caller has<br>}</pre><p>But it <em>cannot</em> make the caller’s variable point to a completely different object, because the method only has a copy of the reference, not the original variable itself.</p><p>The swap method in StudentTest demonstrates this nicely, it swaps which array <em>slots</em> point to which student objects, without needing to alter the objects themselves:</p><pre>static void swap(Student6[] studentsData, int firstIndex, int secondIndex){<br>    Student6 student4 = studentsData[firstIndex];<br>    studentsData[firstIndex] = studentsData[secondIndex];<br>    studentsData[secondIndex] = student4;<br>}</pre><h3>Where Do Objects Actually Live?</h3><p>When you write:</p><pre>Student s = new Student();</pre><p><strong>Two things happen:</strong></p><ol><li>Space is allocated for the reference variable s.</li><li>Space is allocated for the actual Student object.</li></ol><p>The object itself lives on the heap, and s simply holds the object&#39;s address. If s hasn&#39;t been assigned yet, its default value is null.</p><p>This distinction the variable versus the object it points to, is exactly why pass-by-value works the way it does, and it’s worth sitting with until it clicks.</p><h3>Conclusion</h3><p>Classes and objects aren’t just syntax to memorize, they’re a way of thinking about your program. A class describes <em>what something can be</em>; an object is <em>an actual instance of that thing</em>, living in memory with its own state.</p><p><strong>Link to Repo:</strong> <a href="https://github.com/Oluwateezzy/java-tutorial-series">https://github.com/Oluwateezzy/java-tutorial-series</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff1c316e0f80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your CloudFront CDN Is Serving Stale Data And How to Fix It With S3 Cache-Control Headers]]></title>
            <link>https://medium.com/charisol-pulse/why-your-cloudfront-cdn-is-serving-stale-data-and-how-to-fix-it-with-s3-cache-control-headers-e1d0e6cfd2e2?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1d0e6cfd2e2</guid>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Mon, 04 May 2026 14:59:46 GMT</pubDate>
            <atom:updated>2026-05-04T15:01:21.109Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A real-world debugging story from building a design system platform on AWS</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*NjZEMluzUzJKmiO8vYDNcw.png" /></figure><h3>Introduction</h3><p>If you’re using <strong>Amazon CloudFront</strong> to serve files from an <strong>S3</strong> bucket, there’s a silent problem that will bite you eventually: you upload a new version of a file, but your users keep seeing the old one sometimes for up to 24 hours. This is not a bug. It’s a feature you didn’t know you were using.</p><p>I ran into this exact issue while building <a href="https://strata.charisol.io/"><strong>Strata</strong></a>, a design system platform that lets teams manage design tokens and publish them as consumable assets (CSS variables, JSON, Tailwind configs, etc.) via a CDN. Every time a designer updated a color token or spacing variable, the published strata.json and variables.css files on CloudFront stubbornly kept returning the old values.</p><h3>The Architecture</h3><p>The setup is straightforward and common in the AWS ecosystem:</p><pre>User updates design token<br>       ↓<br>Express API (Lambda)<br>       ↓<br>Writes files to S3<br>       ↓<br>CloudFront serves files from S3<br>       ↓<br>React SDK polls CloudFront for updates</pre><p>When a user saves a change, the backend generates multiple format files (strata.json, variables.css, tokens.ts, etc.) and uploads them to S3 at two paths:</p><ol><li><strong>Latest path (mutable):</strong> snapshots/{projectId}/strata.json overwritten on every publish</li><li><strong>Versioned path (immutable):</strong> snapshots/{projectId}/versions/v20260415.../strata.json a permanent archive</li></ol><p><strong>CloudFront</strong> sits in front of the <strong>S3</strong> bucket with a behavior matching /snapshots/*, and consumer SDKs fetch from the CloudFront URL.</p><h3>The Problem</h3><h4>Layer 1: S3 Objects Had No Cache-Control Header</h4><p>The original upload function:</p><pre>// utils/s3.js — BEFORE (the problematic version)<br><br>const { PutObjectCommand } = require(&quot;@aws-sdk/client-s3&quot;);<br><br>async function uploadProjectData({ bucket, key, body, contentType }) {<br>  const command = new PutObjectCommand({<br>    Bucket: bucket,<br>    Key: key,<br>    Body: body,<br>    ContentType: contentType ?? &quot;application/json&quot;,<br>    // No CacheControl property — S3 object has no cache metadata<br>  });<br><br>  await s3.send(command);<br>}</pre><p>When you upload an object to <strong>S3</strong> without setting CacheControl, <strong>S3</strong> doesn&#39;t add a Cache-Control header to GET responses. This means when <strong>CloudFront</strong> fetches the file from <strong>S3</strong> (the &quot;origin&quot;), it receives no caching instruction from the origin.</p><h4>Layer 2: CloudFront’s CACHING_OPTIMIZED Default TTL</h4><p>When there’s no Cache-Control header from the origin, <strong>CloudFront</strong> doesn&#39;t just skip caching. It falls back to the Default TTL defined in its cache policy.</p><p>In the CDK infrastructure code, the snapshot behavior used the AWS-managed CACHING_OPTIMIZED policy:</p><pre>// cdk/lib/stack.ts — BEFORE<br><br>distribution.addBehavior(&quot;/snapshots/*&quot;, s3Origin, {<br>  cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,<br>});</pre><p>What <strong>CACHING_OPTIMIZED</strong> actually means: <strong>CACHING_OPTIMIZED</strong> means content is cached very aggressively starting from as little as 1 second, typically 24 hours by default, and up to 1 year for maximum performance.</p><p><strong>The combined effect was</strong>:</p><ol><li>Backend uploads new strata.json to <strong>S3</strong></li><li><strong>CloudFront</strong> checks its edge cache: <em>“I have a copy from 3 minutes ago, and my policy says cache for 24 hours. Serving cached version.”</em></li><li>User sees stale data for up to 24 hours</li></ol><p>The file was correctly updated in <strong>S3</strong>. <strong>CloudFront</strong> just didn’t know it should check.</p><h4>Understanding CloudFront’s TTL Decision Logic</h4><p><strong>CloudFront</strong> uses this logic to decide how long to cache a response:</p><pre>IF origin sends Cache-Control header:<br>    effective_ttl = clamp(origin_max_age, min_ttl, max_ttl)<br>ELSE:<br>    effective_ttl = default_ttl</pre><p>With CACHING_OPTIMIZED and no origin header:</p><pre>effective_ttl = default_ttl = 86,400 seconds = 24 hours</pre><p>This is the key insight: if you don’t set Cache-Control on your <strong>S3</strong> objects, <strong>CloudFront&#39;s</strong> default TTL becomes your caching strategy whether you intended it or not.</p><h3>The Solution</h3><h4>1. Add Cache-Control Support to S3 Uploads</h4><pre>// utils/s3.js — AFTER<br><br>async function uploadProjectData({ bucket, key, body, contentType, cacheControl }) {<br>  const params = {<br>    Bucket: bucket,<br>    Key: key,<br>    Body: body,<br>    ContentType: contentType ?? &quot;application/json&quot;,<br>  };<br><br>  if (cacheControl) {<br>    params.CacheControl = cacheControl;<br>  }<br><br>  const command = new PutObjectCommand(params);<br>  await s3.send(command);<br>}</pre><p>The <strong>CacheControl</strong> property on PutObjectCommand sets the Cache-Control metadata on the <strong>S3</strong> object. When <strong>CloudFront</strong> (or any HTTP client) fetches this object, <strong>S3</strong> returns this as a standard Cache-Control HTTP header.</p><h4>2. Set Different Cache Strategies for Mutable vs. Immutable Files</h4><p>This is where the real design decision lives. Not all files should be cached the same way:</p><pre>// utils/publishSnapshot.js — AFTER<br><br>async function publishProjectSnapshot(projectId, store, project) {<br>  const prefix = `snapshots/${projectId}`;<br>  const versionId = createSnapshotVersionId(); // e.g., &quot;v20260415073842-a8f3k2&quot;<br>  const versionPrefix = `${prefix}/versions/${versionId}`;<br><br>  // Mutable &quot;latest&quot; files — overwritten on every publish.<br>  // CloudFront must ALWAYS check S3 for the newest version.<br>  const CACHE_LATEST = &quot;no-cache, no-store, must-revalidate&quot;;<br><br>  // Immutable versioned files — content at this path never changes.<br>  // Safe to cache aggressively at every layer.<br>  const CACHE_VERSIONED = &quot;public, max-age=31536000, immutable&quot;;<br><br>  const uploads = [<br>    { file: &quot;strata.json&quot;, body: strataContent, contentType: &quot;application/json&quot; },<br>    { file: &quot;variables.css&quot;, body: cssContent, contentType: &quot;text/css&quot; },<br>    // ... other formats<br>  ];<br><br>  await Promise.all(uploads.flatMap((item) =&gt; ([<br>    // Versioned copy — permanent archive, cache forever<br>    uploadProjectData({<br>      bucket,<br>      key: `${versionPrefix}/${item.file}`,<br>      body: item.body,<br>      contentType: item.contentType,<br>      cacheControl: CACHE_VERSIONED,<br>    }),<br>    // Latest copy — mutable, never cache<br>    uploadProjectData({<br>      bucket,<br>      key: `${prefix}/${item.file}`,<br>      body: item.body,<br>      contentType: item.contentType,<br>      cacheControl: CACHE_LATEST,<br>    }),<br>  ])));<br>}</pre><p><strong>Why two different strategies?</strong></p><ul><li>The latest path (snapshots/{projectId}/strata.json) is the one consumer SDKs poll. It gets overwritten on every publish. If <strong>CloudFront</strong> caches it, users see stale data.</li><li>The versioned path (snapshots/{projectId}/versions/v20260415.../strata.json) is a permanent archive. The content at that path will never change — the version ID is unique. Caching it for a year saves <strong>S3</strong> costs and reduces latency for anyone fetching a specific version.</li></ul><h4>3. Replace the CloudFront Cache Policy</h4><p>The CDK cache policy needs to change so <strong>CloudFront</strong> actually respects the Cache-Control headers we&#39;re now sending:</p><pre>// cdk/lib/stack.ts — AFTER<br><br>// Custom policy that defers to origin&#39;s Cache-Control headers<br>const snapshotCachePolicy = new cloudfront.CachePolicy(<br>  this, &quot;snapshot-cache-policy&quot;, {<br>    defaultTtl: cdk.Duration.seconds(0),   // Don&#39;t cache unless origin says to<br>    minTtl: cdk.Duration.seconds(0),       // Respect no-cache / no-store<br>    maxTtl: cdk.Duration.days(365),        // Allow immutable files to cache for 1yr<br>    enableAcceptEncodingGzip: true,<br>    enableAcceptEncodingBrotli: true,<br>  }<br>);<br><br>distribution.addBehavior(&quot;/snapshots/*&quot;, s3Origin, {<br>  cachePolicy: snapshotCachePolicy,<br>});</pre><h4>Wait Won’t no-cache Kill Performance?</h4><p><strong>A common concern:</strong> if <strong>CloudFront</strong> always goes back to <strong>S3</strong>, doesn’t that defeat the purpose of a CDN?</p><p>Not exactly. no-cache doesn&#39;t mean &quot;never cache&quot;. It means &quot;revalidate before serving&quot;. <strong>CloudFront</strong> will send a conditional request (If-None-Match with the ETag) to <strong>S3</strong>.</p><p>If the file hasn&#39;t changed, <strong>S3</strong> returns a 304 Not Modified response (no body, just headers) which is incredibly fast and costs virtually nothing. You only pay the full <strong>S3</strong> GET cost when the file has actually changed. And for a design system that updates maybe a few times per day, this is negligible.</p><p>For the versioned files, <strong>CloudFront</strong> serves them directly from the edge cache without ever contacting <strong>S3</strong> which is the best-case CDN performance.</p><h4>Note: Cache Invalidation</h4><p>If you’ve already deployed and have stale files cached at <strong>CloudFront</strong> edge locations, you can’t wait for code changes to propagate. You need an invalidation:</p><pre>aws cloudfront create-invalidation \<br>  --distribution-id E1A2B3C4D5E6F7 \<br>  --paths &quot;/snapshots/your-project-id/*&quot;</pre><p>This tells <strong>CloudFront</strong> to discard all cached copies matching that path pattern across all global edge locations. The next request will fetch fresh data from <strong>S3</strong>.</p><h3>Conclusion</h3><p>In summary, effective caching with <strong>CloudFront</strong> comes down to being intentional: always define Cache-Control headers at the origin, tailor caching strategies based on whether content is mutable or immutable, and avoid relying on CACHING_OPTIMIZED for dynamic data. Understanding how <strong>CloudFront</strong> calculates TTL helps you debug issues, while invalidations should only be a last resort not your primary approach since well-configured caching policies make your system faster, more predictable, and easier to manage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1d0e6cfd2e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/charisol-pulse/why-your-cloudfront-cdn-is-serving-stale-data-and-how-to-fix-it-with-s3-cache-control-headers-e1d0e6cfd2e2">Why Your CloudFront CDN Is Serving Stale Data And How to Fix It With S3 Cache-Control Headers</a> was originally published in <a href="https://medium.com/charisol-pulse">Charisol Pulse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Learning Journey: Introduction and Overview of Java]]></title>
            <link>https://oluwateezzy03.medium.com/java-learning-journey-introduction-and-overview-of-java-dcb730a756b3?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcb730a756b3</guid>
            <category><![CDATA[interpreters]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[java-internals]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-programming]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 17:53:15 GMT</pubDate>
            <atom:updated>2026-04-26T17:53:15.072Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Java Internals</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ipf2c5jLvc3jyxodRN67fA.jpeg" /></figure><h3>Introduction</h3><p>If you’ve ever wondered how apps like Spotify, LinkedIn, or even your banking app were built, there’s a good chance <strong>Java</strong> had something to do with it. <strong>Java</strong> is one of the most widely used programming languages in the world and for good reason. It’s powerful, flexible, beginner-friendly, and runs virtually everywhere.</p><h3>Programming Language</h3><p>Before we get into Java specifically, it helps to understand the landscape of programming languages because not all languages are created equal</p><h4>Low-Level Languages</h4><p>Low-level languages speak the computer’s native tongue. They deal directly with hardware things like memory locations and allocation.</p><p><strong>There are two types:</strong></p><ul><li><strong>Machine language</strong>: pure binary (0s and 1s). It’s the only language a CPU truly understands. Every program, no matter what language it was written in, eventually becomes machine language.</li><li><strong>Assembly language</strong>: a step up from machine language. Instead of raw binary, you write short symbolic codes (like MOV, ADD, JMP). An assembler then converts this into machine language.</li></ul><pre>Assembly Language → Assembler → Machine Language</pre><p>Low-level languages give you a lot of control and speed, but they are tedious and difficult to write. They’re not practical for large, complex applications.</p><h4>High-Level Languages</h4><p>High-level languages are much closer to how humans think and communicate. They use English-like words, mathematical notation, and clear structure hiding away all the messy low-level details like memory management.</p><p><strong>Examples include:</strong> Fortran, C, C++, Java, and C#.</p><p>With a high-level language, you can focus on <em>what</em> you want the computer to do, rather than <em>how</em> it should do it at the hardware level. That’s a huge productivity win.</p><p>To run a high-level program, it must first be translated into machine language. This brings us to compilation.</p><h4>Compilation</h4><p>When you write code in a high-level language, a special program called a compiler translates your source code into a target language.</p><pre>Source Code → Compiler → Target Language</pre><p>That target language can be:</p><ul><li><strong>Machine code</strong> (<strong>binary</strong> — runs directly on hardware)</li><li><strong>Bytecode</strong> (<strong>an intermediate form</strong> — more on this shortly)</li><li><strong>Another programming language</strong> (when this happens, the compiler is called a <em>transpiler</em> or <em>source-to-source compiler</em>)</li></ul><p><strong>Java</strong> uses a fascinating combination of compilation and interpretation which is a big part of what makes it so powerful.</p><h3>What is Java?</h3><p><strong>Java</strong> is a general-purpose, high-level programming language created by Sun Microsystems in 1995 (now owned by Oracle). It was built with a simple but ambitious philosophy:</p><p><em>“Write Once, Run Anywhere.”</em></p><h4>Core Characteristics Of Java</h4><ul><li><strong>General purpose:</strong> Used for web apps, mobile, enterprise software, and more</li><li><strong>Object-oriented:</strong> Organises code into reusable “objects”</li><li><strong>Platform independent:</strong> The same Java code runs on Windows, Mac, Linux</li><li><strong>Concurrent:</strong> Can handle multiple tasks at the same time</li><li><strong>Very fast:</strong> Optimised execution through JIT compilation</li><li><strong>Automatic memory management:</strong> Java handles memory cleanup for you</li></ul><h4>Java’s Core Goals</h4><p>When <strong>Java</strong> was designed, the engineers had clear goals in mind:</p><ul><li><strong>Consume less memory:</strong> efficient use of system resources</li><li><strong>Delivery of software components:</strong> modular, reusable code</li><li><strong>Platform independence:</strong> code runs everywhere without modification</li><li><strong>Security:</strong> built-in protection mechanisms</li><li><strong>Multithreading:</strong> efficient handling of concurrent operations</li></ul><h3>Platform Independence</h3><p>This is where <strong>Java</strong> gets really interesting. How exactly does the same Java code run on a Windows PC, a Mac, a Linux server, or an Android phone?</p><p>The answer is the <strong>Java Virtual Machine (JVM)</strong>.</p><h4>The Problem: Platform Dependency</h4><p>Different operating systems and hardware have their own quirks:</p><ul><li>Operating systems differ in executable file formats and system calls (e.g. how Linux opens a file is different from how Windows does it)</li><li>Hardware differs in instruction sets (e.g. Intel’s x86 architecture vs ARM used in smartphones)</li></ul><p>A program compiled for Windows won’t just run on Linux. Traditionally, developers had to rewrite or recompile their code for each platform.</p><h4>The Solution: Bytecode + JVM</h4><p><strong>Java</strong> solves this with a two-step approach:</p><pre>Java Source Code (.java)<br>        ↓<br>Java Compiler<br>        ↓<br>Bytecode (.class) ← Platform independent<br>        ↓<br>JVM (platform-specific) ← Runs the bytecode<br>        ↓<br>Program executes</pre><ol><li>Your <strong>Java</strong> source code is compiled into bytecode a compact, optimised, intermediate format. Bytecode is platform independent, meaning it’s the same .class file whether you&#39;re on Mac or Windows.</li><li>The <strong>JVM</strong> (which is platform-specific and installed separately for each OS) reads and executes the bytecode.</li></ol><p><em>Think of </em><strong><em>bytecode</em></strong><em> as a universal script, and the </em><strong><em>JVM</em></strong><em> as a translator that speaks the local language of whatever computer it’s installed on.</em></p><p><strong>Point to remember:</strong></p><ul><li><strong>Java</strong> bytecode is platform <em>independent</em></li><li>The <strong>JVM</strong> is platform <em>dependent</em></li></ul><p>This also means <strong>bytecode</strong> is compact enough to transfer quickly across a network which was a major design consideration when the internet was young.</p><h3>The JVM (Java Virtual Machine)</h3><p>The <strong>JVM</strong> is an abstract computing machine a software-based CPU that runs Java bytecode. It’s the heart of Java’s “run anywhere” promise.</p><h4>What the JVM Does</h4><ul><li>Loads and interprets Java bytecode</li><li>Manages memory automatically (garbage collection)</li><li>Enforces security</li><li>Optimises performance</li></ul><h4>JVM Architecture</h4><pre>┌─────────────────────────────────────────┐<br>│              JVM                        │<br>│                                         │<br>│  ┌─────────────┐  ┌──────────────────┐  │<br>│  │ Class Loader│  │ Bytecode Verifier│  │<br>│  └─────────────┘  └──────────────────┘  │<br>│                                         │<br>│  ┌──────────────────────────────────┐   │<br>│  │      Runtime Data Area           │   │<br>│  │         (JVM Memory)             │   │<br>│  └──────────────────────────────────┘   │<br>│                                         │<br>│  ┌──────────────────────────────────┐   │<br>│  │       Execution Engine           │   │<br>│  │  ┌──────────────┐ ┌───────────┐  │   │<br>│  │  │ Interpreter  │ │  JIT      │  │   │<br>│  │  │              │ │ Compiler  │  │   │<br>│  │  └──────────────┘ └───────────┘  │   │<br>│  └──────────────────────────────────┘   │<br>│                                         │<br>│  ┌──────────────┐  ┌─────────────────┐  │<br>│  │  Garbage     │  │ Security Manager│  │<br>│  │  Collector   │  │                 │  │<br>│  └──────────────┘  └─────────────────┘  │<br>└─────────────────────────────────────────┘</pre><ul><li><strong>Class Loader:</strong> loads .class files (bytecode) into memory</li><li><strong>Bytecode Verifier:</strong> checks bytecode is valid and safe before execution</li><li><strong>Runtime Data Area:</strong> the JVM’s memory workspace</li><li><strong>Execution Engine:</strong> runs the bytecode (using the interpreter and JIT compiler)</li><li><strong>Garbage Collector:</strong> automatically reclaims memory no longer in use</li><li><strong>Security Manager:</strong> enforces Java’s security policies</li></ul><h3>The Interpreter and JIT Compiler</h3><p>The <strong>JVM’s</strong> execution engine has two weapons for running bytecode: the Interpreter and the <strong>JIT</strong> <strong>Compiler</strong>. Together, they balance speed and platform independence.</p><h4>The Interpreter</h4><p>The interpreter works like a virtual CPU it simulates the fetch-and-execute cycle:</p><ol><li><strong>Fetch</strong>: get the next program statement</li><li><strong>Understand</strong>: decode what the statement means</li><li><strong>Execute:</strong> run precompiled machine code from its library</li></ol><p>The interpreter runs every statement line by line. It’s flexible but can be slow, because it re-reads and re-translates the same code every time it runs.</p><p><strong>Advantages of interpretation:</strong></p><ul><li>Platform independence (same bytecode, different interpreters per OS)</li><li>No separate compilation step needed at runtime</li><li>Easier to update and deploy</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Slower execution</li><li>Higher memory cost (interpreter itself must be loaded into memory)</li><li>Source/bytecode is re-interpreted on every run</li></ul><h4>Just-In-Time (JIT) Compilation</h4><p>The <strong>JIT</strong> compiler is <strong>Java’s</strong> performance booster.</p><ol><li>It monitors the running program to identify “hot spots” sections of bytecode that are executed frequently</li><li>It compiles those hot spots directly into native machine code</li><li>That machine code is cached, so next time the same section runs, it executes at full native speed no interpretation needed</li></ol><p>This is also called dynamic compilation, because it happens at runtime, not before the program runs.</p><p><em>The </em><strong><em>JIT</em></strong><em> compiler is why </em><strong><em>Java</em></strong><em> is described as “very fast” despite being interpreted. You get the portability of </em><strong><em>bytecode</em></strong><em> and the performance of compiled code.</em></p><h3>Structure of a Java Program</h3><p>Now that we understand how <strong>Java</strong> works, let’s look at how a Java program is actually organised.</p><h4>Everything Lives in a Class</h4><p>In <strong>Java</strong>, all code is written inside a class. A class is a blueprint — a container that holds related data and behaviour together.</p><p>A class can contain:</p><ul><li><strong>Variable declarations:</strong> data the class stores</li><li><strong>Constructors:</strong> special methods that set up the object when it’s created</li><li><strong>Statements:</strong> individual instructions</li><li><strong>Method statements:</strong> blocks of reusable code (functions)</li><li><strong>Nested classes:</strong> classes defined inside another class</li></ul><h4>The main() Method</h4><p>Every <strong>Java</strong> application has a starting point: the main() method. When you run a <strong>Java</strong> program, the JVM:</p><ol><li>Loads the bytecode of your .class file into memory</li><li>Locates the main() method</li><li>Begins executing from there</li><li>The program ends when main() finishes</li></ol><pre>public class HelloWorld {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello, World!&quot;);<br>    }<br>}</pre><h4>Rules for main() Method</h4><p>The main() method has strict rules it must be declared as:</p><ul><li><strong>public:</strong>accessible from anywhere (the JVM needs to call it)</li><li><strong>static</strong>:can be called without creating an object of the class</li><li><strong>void:</strong> it doesn&#39;t return any value</li></ul><pre>public static void main(String[] args) { ... }</pre><p>From inside main(), you invoke all the other code in your program. The program starts with main() and ends with it too.</p><h3>Conclusion</h3><p>Learning a programming language is an investment and Java is one that pays dividends for years.</p><p>Java isn’t just another language you study for a course and forget. It powers some of the largest systems on the planet from Android apps used by billions, to the backend of enterprise banking platforms, to massive distributed systems at companies like Amazon and LinkedIn. When you learn Java, you’re learning a skill that is actively in demand across industries, geographies, and specialisations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcb730a756b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design Learning Journey: Why Your AI Chatbot Takes 3 Minutes to Respond]]></title>
            <link>https://oluwateezzy03.medium.com/system-design-learning-journey-why-your-ai-chatbot-takes-3-minutes-to-respond-f124cd816212?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f124cd816212</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 22:16:15 GMT</pubDate>
            <atom:updated>2026-04-17T22:16:15.122Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical breakdown of LLM response latency, and four concrete strategies to bring it under control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjsVbz2QsFVcmI1kJ5KyHQ.png" /></figure><h3>Introduction</h3><p>Imagine asking your AI Agent a question and then… waiting. Three full minutes of silence before the first word appears. That’s not a thought experiment it’s the real-world experience many users face when AI systems are not optimized for latency. In this article, we break down exactly why this happens, and what you can do about it at each layer of your stack.</p><p><em>“The biggest mistake teams make is optimizing the wrong layer first. Speed perception and actual throughput are two different problems.”</em></p><h3>The root causes</h3><p>High latency in LLM-backed applications almost always traces back to one of three culprits: how responses are sent, what model is being used, and how much context the model is processing. Understanding these separately is the key to choosing the right fix.</p><ul><li><strong>Synchronous execution</strong> is the most common and most impactful problem. Most backend servers wait for the entire LLM response to be generated before sending a single byte to the frontend. If the model takes 120 seconds to generate its full answer, the user sees nothing until second 120. This is not a model problem, it’s an architecture problem.</li><li><strong>Infrastructure bottlenecks</strong> compound the issue. If your Ollama instance is running on CPU-only hardware, or on a machine that’s undersized for the model being loaded, generation speed suffers regardless of any other optimizations. A 7B parameter model on a CPU might generate 3–5 tokens per second. The same model with GPU acceleration can push 50–80 tokens per second.</li><li><strong>Context overhead</strong> is the silent killer. Every time a user sends a message, the full conversation history all prior turns is prepended to the prompt. By message 20 of a session, the model may be processing 10,000+ tokens before generating a single output token. Token processing isn’t free; it adds seconds with every turn.</li></ul><h3>Four approaches: Ranked by impact</h3><p><strong>Response streaming</strong><br><strong>Use Server-Sent Events (SSE)</strong> to stream tokens from Ollama to the browser in real time. The user sees the first word within 1–2 seconds, even if the full response takes minutes. This doesn’t speed up generation it changes the perception of speed entirely. Requires changes to both your backend controller and your frontend API service, but the payoff is a “premium” feel that users associate with OpenAI and Claude.</p><p><strong>Model selection &amp; quantization</strong><br><strong>Switching from llama3 (8B) to phi3 (3.8B) or a Q4_K_M</strong> quantized variant cuts generation time roughly in half on the same hardware, with modest quality tradeoffs. For counseling-style use cases, smaller models often perform surprisingly well they are instruction-tuned and fast. Quantized models use 4-bit weights instead of 16-bit, meaning 4× less memory and significantly faster inference.</p><p><strong>Context &amp; history management<br></strong>Limit the conversation history passed to the model to the last 5–10 messages. Older turns can be replaced with a brief summary. This is a one-line change in most backends and can shave 15–40% off response time in long sessions. The tradeoff: the AI may lose memory of very early conversation context usually acceptable for counseling flows.</p><p><strong>GPU acceleration &amp; infrastructure tuning</strong><br>Before any code changes, verify that Ollama is actually using your GPU. Run ollama ps and check the &quot;Processor&quot; column. If it says CPU, you&#39;re leaving 10–20× speed on the table. Enable CUDA (Nvidia) or Metal (Apple Silicon), tune Ollama&#39;s concurrency settings, and confirm the model fits in VRAM. This is a zero-code, high-leverage check.</p><h3>Recommended path forward</h3><h4>Environment audit</h4><p>Confirm GPU usage with ollama ps. Enable CUDA or Metal if missing. Takes 30 minutes, zero code.</p><h4>Short term: Context limiting</h4><p>Slice conversation history to the last 8 messages before each API call. Measure before/after token counts and response times.</p><h4>Medium term: Implement SSE streaming</h4><p>Refactor your backend to stream responses via SSE. Update your frontend service to consume the stream and render tokens incrementally. This is the single highest-impact change for perceived performance.</p><p>The order matters. The environment audit costs nothing and might reveal that Ollama is running on CPU fixing that alone could cut response time from 176s to under 20s. Context limiting is a low-risk quick win. Streaming is the crown jewel, but it takes engineering time. Do them in sequence and measure at each step.</p><p><em>“Streaming doesn’t make the model faster. It makes the wait invisible. That’s often more valuable.”</em></p><h3>Conclusion</h3><p>A 176-second response time is not a death sentence for your AI feature, it is a signal that the architecture hasn’t been tuned yet. The good news is that the highest-impact fixes (GPU enablement, context trimming, streaming) are well-understood problems with known solutions. You don’t need better hardware or a bigger model. You need to use what you already have, better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f124cd816212" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design Learning Journey: Understanding Javascript Event Loop (Node Internals)]]></title>
            <link>https://oluwateezzy03.medium.com/system-design-learning-journey-understanding-javascript-event-loop-node-internals-919af1b4584f?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/919af1b4584f</guid>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 12:55:42 GMT</pubDate>
            <atom:updated>2026-03-22T12:55:42.841Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The concepts of System Design become much clearer when you see them in action</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94dGeJUkJvJPgPSmXuDemw.png" /></figure><h3>Introduction</h3><p>The <strong>Event Loop</strong> is a coordination mechanism. It is the secret bridge that allows JavaScript to be “single-threaded” (doing one thing at a time) while also being “non-blocking” (handling thousands of concurrent network requests or timers without freezing).</p><p>Imagine an office with only one employee (<strong>the Call Stack</strong>). This employee handles every piece of work that comes in. However, some tasks like waiting for a file to download or a timer to finish take a long time. If the employee just sat there waiting, the entire office would grind to a halt. This is what we call “blocking.”</p><p>The Event Loop solves this by offloading those long-running tasks to the system’s background helpers. When those tasks are finished, they are placed in a waiting room (<strong>the</strong> <strong>Task Queues</strong>). The Event Loop’s entire job is to watch the main employee. The moment the employee is free, the Event Loop grabs the next most urgent task from the waiting room and hands it to them.</p><h3>How does it work in Node?</h3><p>In Node.js, the event loop is powered by a library called <strong>libuv</strong>. While our simulation is a simplified model, Node handles a complex set of “phases” during every tick:</p><ul><li><strong>Timers</strong>: Handles setTimeout and setInterval.</li><li><strong>Pending Callbacks</strong>: Executes I/O callbacks deferred to the next loop iteration.</li><li><strong>Idle/Prepare</strong>: Internal use only.</li><li><strong>Poll</strong>: Retrieves new I/O events.</li><li><strong>Check</strong>: Handles setImmediate.</li><li><strong>Close Callbacks</strong>: Handles socket closures.</li></ul><p>Between every phase, Node.js checks the <strong>Microtask Queue</strong> (Promises and process.nextTick). If it&#39;s not empty, it drains it <em>completely</em> before moving to the next phase.</p><h3>The feature of Event Loop</h3><p>The JavaScript Event Loop has several unique features that make it powerful:</p><ol><li><strong>Single-Threaded</strong>: It only executes one task at a time on the main thread, avoiding complex synchronization issues like deadlocks.</li><li><strong>Non-Blocking</strong>: It offloads heavy tasks (like reading a file or making a network request) to the system kernel or a thread pool, allowing the loop to keep running.</li><li><strong>Priority-Based</strong>: Not all tasks are created equal. Microtasks (Promises) always take precedence over Macrotasks (Timers).</li><li><strong>The “Run-to-Completion” Rule</strong>: Once a function starts, it cannot be interrupted until it finishes.</li></ol><h3>Hands On Experiment</h3><p>Let’s build our own simulation! We’ll create a MiniEventLoop class that manages a <strong>Call Stack</strong>, a <strong>Microtask Queue</strong>, and a <strong>Macrotask Queue</strong>.</p><h4>Step 1: Defining the Foundation</h4><pre>class MiniEventLoop {<br>  constructor() {<br>    this.callStack = [];<br>    this.microtaskQueue = [];<br>    this.macrotaskQueue = [];<br>  }<br><br>  pushToStack(fn, args = []) {<br>    this.callStack.push({ name: fn.name, args });<br>    console.log(`[STACK] Pushed: ${fn.name}`);<br>    <br>    // Execute the function immediately<br>    fn(...args);<br>    <br>    this.callStack.pop();<br>    console.log(`[STACK] Popped: ${fn.name}`);<br>  }<br>}</pre><h4>Step 2: The Scheduler</h4><p>We need a tick method that decides what to execute next, prioritizing microtasks.</p><pre>  processMicrotasks() {<br>    console.log(`--- Processing Microtasks ---`);<br>    while(this.microtaskQueue.length &gt; 0) {<br>      const task = this.microtaskQueue.shift();<br>      console.log(`[MICROTASK] Executing: ${task.name}`);<br>      task.fn();<br>    }<br>  }<br><br>  processMacrotask() {<br>    console.log(`--- Processing ONE Macrotask ---`);<br>    if(this.macrotaskQueue.length &gt; 0) {<br>      const task = this.macrotaskQueue.shift();<br>      console.log(`[MACROTASK] Executing: ${task.name}`);<br>      task.fn();<br>    }<br>  }<br><br>  tick() {<br>    console.log(`--- Processing Tick ---`);<br>    this.processMicrotasks();<br>    this.processMacrotask();<br>  }</pre><h3>Step 3: Simulating Async APIs</h3><p>Finally, we add methods to mimic setTimeout and Promise.</p><pre>  setTimeoutSimulation(fn, name = &#39;setTimeout&#39;) {<br>    this.macrotaskQueue.push({ name, fn });<br>  }<br><br>  promiseResolveSimulation(fn, name = &#39;Promise.then&#39;) {<br>    this.microtaskQueue.push({ name, fn });<br>  }<br><br>  run() {<br>    console.log(&#39;=== Event Loop Started ===&#39;);<br>    while(this.microtaskQueue.length &gt; 0 || this.macrotaskQueue.length &gt; 0) {<br>      this.tick();<br>    }<br>    console.log(&#39;=== Event Loop Finished ===&#39;);<br>  }</pre><h3>Conclusion</h3><p>Building this simulation is more than a coding exercise; it’s about developing the mental model required for high-performance engineering. By understanding the Event Loop, you move beyond syntax to understand the execution models that power your tools, enabling you to strategically schedule tasks based on urgency, proactively identify performance bottlenecks, and debug complex race conditions with precision.</p><p><strong><em>Github Repo: </em></strong><a href="https://github.com/Oluwateezzy/node_event_loop">https://github.com/Oluwateezzy/node_event_loop</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=919af1b4584f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design Learning Journey: Rebuilding JavaScript Promises (Node Internals)]]></title>
            <link>https://oluwateezzy03.medium.com/system-design-learning-journey-rebuilding-javascript-promises-node-internals-692d09fff670?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/692d09fff670</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[thread-scheduling]]></category>
            <category><![CDATA[javascript-promise]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 11:20:39 GMT</pubDate>
            <atom:updated>2026-03-01T11:20:39.214Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The concepts of System Design become much clearer when you see them in action</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3N1-biCOUbAOWf5czHCjQ.png" /></figure><h3>Introduction</h3><p>Imagine you’re in a high-stakes technical interview. The CTO leans in and says: <em>“Take out the </em><em>Promise object from JavaScript. Now, solve &#39;callback hell&#39; without it. You can use any systems-level concept you want like thread scheduling, concurrency models, runtime guarantees but you cannot use a native Promise.&quot;</em></p><p>This actually happened to trench_techie ⚡️, and it’s one of the best ways to test if someone actually understands the JavaScript runtime or is just “writing syntax.”</p><p>In this article, we’re going to do exactly that. We’ll rebuild MyPromise from the ground up, explaining the why behind every line. By the end, you’ll understand how JavaScript manages to be non-blocking while remaining single-threaded.</p><h3>The Core Architecture: The State Machine</h3><p>A <strong>Promise</strong> is, at its heart, a State Machine. It manages a transition that can only happen once.</p><h4>The Concepts:</h4><ul><li><strong>PENDING</strong>: The default state. Like a meal being cooked in a kitchen.</li><li><strong>FULFILLED</strong>: Success. The meal is ready to be served.</li><li><strong>REJECTED</strong>: Failure. We ran out of ingredients.</li><li><strong>Settlement</strong>: <em>Once a promise moves to Fulfilled or Rejected, it is “</em><strong><em>Settled</em></strong><em>.” It can never change again.</em></li></ul><h4>The Implementation:</h4><p>We start by defining these states as constants.</p><pre>const PENDING = &quot;pending&quot;;<br>const FULFILLED = &quot;fulfilled&quot;;<br>const REJECTED = &quot;rejected&quot;;</pre><h3>The Bridge: Producer vs. Consumer</h3><p>A <strong>Promise</strong> connects two people:</p><ol><li><strong>The Producer</strong>: The code doing the work (e.g., fetching data from an API).</li><li><strong>The Consumer</strong>: The code waiting for the result (e.g., updating the UI).</li></ol><p>In our constructor, we provide the Producer with two functions: resolve and reject.</p><h4>The Logic:</h4><pre>class MyPromise {<br>    constructor(executor) {<br>        this.state = PENDING;<br>        this.result = null;<br>        this.onFulfilledCallbacks = [];<br>        this.onRejectedCallbacks = [];<br><br>        const resolve = (value) =&gt; {<br>            if (this.state === PENDING) {<br>                this.state = FULFILLED;<br>                this.result = value;<br>                // We&#39;ll handle the &quot;later&quot; part in the next section<br>            }<br>        };<br>        // ... (reject is similar)<br>        <br>        try {<br>            executor(resolve, reject);<br>        } catch (error) {<br>            reject(error);<br>        }<br>    }<br>}</pre><h3>The Microtask Queue</h3><p>This is where most people fail. If you call resolve(10), and then immediately call .then(), does the callback run instantly?</p><p>In real JavaScript, the answer is NO. Promise callbacks always run after the current script finishes, but before the next event loop tick.</p><h4>Why queueMicrotask()?</h4><p>If we ran callbacks synchronously, we’d get unpredictable behavior depending on whether the data was cached or fetched live. queueMicrotask() ensures the callback is always decoupled from the current stack.</p><pre>const resolve = (value) =&gt; {<br>    if (this.state === PENDING) {<br>        this.state = FULFILLED;<br>        this.result = value;<br>        // Schedule execution for the next microtask!<br>        queueMicrotask(() =&gt; {<br>            this.onFulfilledCallbacks.forEach(callback =&gt; callback(value));<br>        });<br>    }<br>};</pre><h3>The Chaining</h3><p>The reason Promises solved “callback hell” is because they can be chained. p.then().then().then()</p><p>To make this work, .then() must return a brand new MyPromise. This new promise is resolved with whatever the callback in the previous .then returns.</p><h4>The Implementation of .then():</h4><pre>then(onFulfilled, onRejected) {<br>    // Default handlers to allow values to &quot;bubble through&quot;<br>    onFulfilled = typeof onFulfilled === &quot;function&quot; ? onFulfilled : (v) =&gt; v;<br>    onRejected = typeof onRejected === &quot;function&quot; ? onRejected : (e) =&gt; { throw e };<br><br>    return new MyPromise((resolve, reject) =&gt; {<br>        const handleCallback = (callback) =&gt; {<br>            try {<br>                const result = callback(this.result);<br>                resolve(result); // Pass the result to the NEXT promise in the chain<br>            } catch (error) {<br>                reject(error);<br>            }<br>        };<br><br>        if (this.state === FULFILLED) {<br>            queueMicrotask(() =&gt; handleCallback(onFulfilled));<br>        } else if (this.state === PENDING) {<br>            this.onFulfilledCallbacks.push(() =&gt; handleCallback(onFulfilled));<br>        }<br>        // ... handle REJECTED<br>    });<br>}</pre><h3>Putting It All Together: Complete Code</h3><p>Here is the full implementation of MyPromise. You can copy this into a file named index.js and run it in Node.js.</p><pre>/* MyPromise: A Custom Implementation */<br><br>const PENDING = &quot;pending&quot;<br>const FULFILLED = &quot;fulfilled&quot;<br>const REJECTED = &quot;rejected&quot;<br><br>class MyPromise {<br>    constructor(executor) {<br>        this.state = PENDING<br>        this.result = null<br>        this.onFulfilledCallbacks = []<br>        this.onRejectedCallbacks = []<br><br>        const resolve = (value) =&gt; {<br>            if (this.state === PENDING) {<br>                this.state = FULFILLED<br>                this.result = value<br>                <br>                // Asynchronous execution via Microtask Queue<br>                queueMicrotask(() =&gt; {<br>                    this.onFulfilledCallbacks.forEach(callback =&gt; callback(value))<br>                })<br>            }<br>        }<br><br>        const reject = (reason) =&gt; {<br>            if (this.state === PENDING) {<br>                this.state = REJECTED<br>                this.result = reason<br><br>                queueMicrotask(() =&gt; {<br>                    this.onRejectedCallbacks.forEach(callback =&gt; callback(reason))<br>                })<br>            }<br>        }<br><br>        try {<br>            executor(resolve, reject);<br>        } catch (error) {<br>            reject(error);<br>        }<br>    }<br><br>    then(onFulfilled, onRejected) {<br>        // Identity functions to allow value/error bubbling<br>        onFulfilled = typeof onFulfilled === &quot;function&quot; ? onFulfilled : (value) =&gt; value<br>        onRejected = typeof onRejected === &quot;function&quot; ? onRejected : (reason) =&gt; { throw reason }<br>        <br>        return new MyPromise((resolve, reject) =&gt; {<br>            const handleCallback = (callback) =&gt; {<br>                try {<br>                    const result = callback(this.result)<br>                    resolve(result)<br>                } catch (error) {<br>                    reject(error)<br>                }<br>            }<br><br>            if (this.state === FULFILLED) {<br>                queueMicrotask(() =&gt; handleCallback(onFulfilled))<br>            }<br>            else if (this.state === REJECTED) {<br>                queueMicrotask(() =&gt; handleCallback(onRejected))<br>            }<br>            else if (this.state === PENDING) {<br>                this.onFulfilledCallbacks.push(() =&gt; handleCallback(onFulfilled))<br>                this.onRejectedCallbacks.push(() =&gt; handleCallback(onRejected))<br>            }<br>        })<br>    }<br><br>    catch(onRejected) {<br>        return this.then(null, onRejected)<br>    }<br>}<br><br>module.exports = MyPromise</pre><h3>How to Practice (Test Your Own)</h3><p>Create a test.js file and run this:</p><pre>const MyPromise = require(&#39;./index&#39;);<br><br>const p = new MyPromise((resolve) =&gt; {<br>    console.log(&quot;1. Starting...&quot;);<br>    setTimeout(() =&gt; resolve(&quot;Success!&quot;), 500);<br>});<br><br>p.then(val =&gt; {<br>    console.log(&quot;3. Chain 1:&quot;, val);<br>    return &quot;Next result&quot;;<br>})<br>.then(val =&gt; {<br>    console.log(&quot;4. Chain 2:&quot;, val);<br>})<br>.catch(err =&gt; console.error(err));<br><br>console.log(&quot;2. Script continuing...&quot;);</pre><p>Expected Console Output:</p><ol><li>1. Starting...</li><li>2. Script continuing...</li><li>(Wait 500ms)</li><li>3. Chain 1: Success!</li><li>4. Chain 2: Next result</li></ol><h3>Conclusion</h3><p>Why go through all this trouble just to recreate something that already exists?</p><p>Because it changes how you see code. You stop seeing await as a magic keyword and start seeing it as a scheduler. You stop fearing &quot;callback hell&quot; because you understand the abstraction that solved it.</p><p>In high-level roles, companies don’t just want to know if you can <em>use</em> a framework. They want to know if you can reason about the system. Understanding algorithm complexity, thread scheduling, and runtime guarantees is what separates a coder from a computer scientist.</p><p>Next time you use a Promise, remember the microtask queue waiting patiently for its turn. You’re not just writing JS; you’re orchestrating a system.</p><p><strong><em>Github Repo:</em></strong><em> </em><a href="https://github.com/Oluwateezzy/node_promise.git"><em>https://github.com/Oluwateezzy/node_promise.git</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=692d09fff670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling DynamoDB for Muzingo Real-Time Multiplayer Games]]></title>
            <link>https://medium.com/charisol-pulse/scaling-dynamodb-for-muzingo-real-time-multiplayer-games-8cd70b3fc557?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd70b3fc557</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 15:01:02 GMT</pubDate>
            <atom:updated>2026-02-16T15:01:02.517Z</atom:updated>
            <content:encoded><![CDATA[<h4>Overcoming the 400KB Limit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRQ32cRETwzK1EnctvvuKQ.png" /></figure><p>Building real-time multiplayer games is exhilarating, but scaling them brings a unique set of challenges. One of the most common hurdles developers face when using <strong>NoSQL</strong> databases like <strong>DynamoDB</strong> is managing data size limits while maintaining high performance.</p><p>In our recent project, <strong>Muzingo (a music-based bingo game)</strong>, we encountered a critical scalability bottleneck that threatened the stability of our “Fastest Finger” game mode.</p><p>This post details how we identified the problem, the architecture of our solution, and the results of our optimization.</p><h3>The Problem</h3><p><strong>DynamoDB</strong> has a hard limit of <strong>400KB</strong> per item. Initially, our data model stored the entire state of a game, including all connected players and their individual game boards, in a single Game document.</p><h4>The “Fat Item” Anti-Pattern</h4><p>For reliable gameplay, each player needed a unique board configuration. In our “Fastest Finger” mode, a single player’s board data (including song metadata, positions, and selection states) could be around 20KB.</p><p>The math was unforgiving:</p><blockquote><strong>25 players x 20KB/player = 500KB</strong></blockquote><p>As soon as a game exceeded ~20 players, the Game document size breached the 400KB limit. This resulted in 500 Internal Server Errors During game initialization, it effectively crashes the game for everyone. We were hitting a ceiling that no amount of vertical scaling could fix.</p><h3>The Solution</h3><p>To solve this, we moved from <strong>embedding data</strong> to a n<strong>ormalized relational pattern</strong> within DynamoDB.</p><h4>Data Normalization</h4><p>We stripped the Game document of its heaviest payload: the player boards. Instead of storing them in the players array, we created a dedicated table called GamePatterns.</p><p><strong>Old Architecture (Embedded):</strong></p><pre>// Table: Games<br>{<br>  &quot;gameCode&quot;: &quot;XYZ123&quot;,<br>  &quot;status&quot;: &quot;active&quot;,<br>  &quot;players&quot;: [<br>    { &quot;id&quot;: &quot;user1&quot;, &quot;board&quot;: [ ...20KB data... ] },<br>    { &quot;id&quot;: &quot;user2&quot;, &quot;board&quot;: [ ...20KB data... ] }<br>  ]<br>}</pre><p><strong>New Architecture (Normalized):</strong></p><pre>// Table: Games (Lightweight &lt; 1KB)<br>{<br>  &quot;gameCode&quot;: &quot;XYZ123&quot;,<br>  &quot;status&quot;: &quot;active&quot;,<br>  &quot;playerIds&quot;: [&quot;user1&quot;, &quot;user2&quot;]<br>}<br><br>// Table: GamePatterns (Partition Key: gameCode, Sort Key: userId)<br>{ &quot;gameCode&quot;: &quot;XYZ123&quot;, &quot;userId&quot;: &quot;user1&quot;, &quot;patternData&quot;: [ ... ] }<br>{ &quot;gameCode&quot;: &quot;XYZ123&quot;, &quot;userId&quot;: &quot;user2&quot;, &quot;patternData&quot;: [ ... ] }</pre><h4>Implementation</h4><p>We implemented a dedicated <strong>Data Access Layer </strong>to handle this new table.</p><pre>// src/utils/dynamodb/gamePatternDataAccess.js<br>class GamePatternDataAccess {<br>    constructor() {<br>        this.tableName = process.env.DYNAMODB_GAME_PATTERNS_TABLE_NAME;<br>        this.dynamoClient = getDocumentClient();<br>    }<br><br>    async savePattern(gameCode, userId, patternData) {<br>        const item = {<br>            gameCode,<br>            userId,<br>            patternData,<br>            updatedAt: Date.now()<br>        };<br><br>        const command = new PutCommand({<br>            TableName: this.tableName,<br>            Item: item<br>        });<br><br>        await this.dynamoClient.send(command);<br>        return item;<br>    }<br>}</pre><p>In our <strong>GraphQL</strong> resolver, instead of pushing data into a massive array, we simply run an asynchronous save operation for each player.</p><p>This allows us to scale horizontally. 100 players means 100 small write operations, which DynamoDB handles effortlessly, rather than one massive (and failing) write operation.</p><pre>// src/containers/game/resolver.js<br>await Promise.all(<br>  gameInView.players.map(async (player) =&gt; {<br>    const userGameObject = generateBoardForPlayer(player);<br>    <br>    // Offload the heavy data to the new table<br>    await gamePatternDataAccess.savePattern(<br>      gameInView.gameCode,<br>      player._id,<br>      userGameObject<br>    );<br>  })<br>);<br><br>// We keep the main game object clean<br>gameInView.patternsGiven = {}; <br>await gameDataAccess.updateGame(gameInView);</pre><h4>Concurrency Handling</h4><p>We also identified a race condition where multiple users joining simultaneously would overwrite the activePlayers list. We refactored the spread operator logic (...activePlayers) to use direct key assignment, allowing 100+ users to join concurrently without data loss.</p><h3>Conclusion</h3><p>By identifying the <strong>“Fat Item” anti-pattern</strong> and refactoring to a <strong>normalized storage strategy</strong>, we completely eliminated the 400KB bottleneck.</p><p><strong>Final Results:</strong></p><ul><li><strong>Capacity</strong>: Increased from ~20 players to 100+ players (verified via load simulation).</li><li><strong>Performance</strong>: Game start time remained stable even under high load.</li><li><strong>Cost</strong>: More predictable write capacity unit (WCU) consumption.</li></ul><p>This architecture proves that while document stores are powerful, understanding their limits and knowing when to normalize data is key to building scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd70b3fc557" width="1" height="1" alt=""><hr><p><a href="https://medium.com/charisol-pulse/scaling-dynamodb-for-muzingo-real-time-multiplayer-games-8cd70b3fc557">Scaling DynamoDB for Muzingo Real-Time Multiplayer Games</a> was originally published in <a href="https://medium.com/charisol-pulse">Charisol Pulse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design Learning Journey: Building My Own Kafka In NodeJS (Kafka Internals)]]></title>
            <link>https://oluwateezzy03.medium.com/system-design-learning-journey-building-my-own-kafka-in-nodejs-kafka-internals-b16a90296942?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16a90296942</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[data-partitioning]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[event-streaming]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 01:47:19 GMT</pubDate>
            <atom:updated>2026-02-08T01:47:19.489Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The concepts of System Design become much clearer when you see them in action</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ei1M75T-P92U4nbAJuhYbw.png" /></figure><h3>Introduction</h3><p>It started after watching <strong>Hussein Nasser’s</strong> into Kafka internals on YouTube. I find it interesting by how a “simple” log could scale to billions of messages. But curiosity is not enough for me to understand i need to build it. I set out to build <strong>node_kafka</strong>, a zero-dependency broker in Node.js. If you’ve ever wanted to understand the “magic” of message brokers, follow along. We’re going to build this step-by-step, from raw bytes on disk to a discovery-powered cluster.</p><h3>Understanding Kafka Internals</h3><p>Before we write a single line of code, let’s understand the core concepts that make Kafka tick. These are the ideas that clicked for me while watching Hussein Nasser’s breakdowns.</p><h4>The Core Components</h4><p><strong>Broker (The Kafka Server)</strong> A Kafka broker is simply a Kafka server. It’s a process that receives messages from producers, stores them on disk, and serves them to consumers. In a production cluster, you’ll have multiple brokers working together for fault tolerance and scalability.</p><p><strong>Topics (Logical Partitions of Data)</strong> A topic is a logical category or feed name to which messages are published. Think of it like a database table or a folder in a file system. Topics are where you “write content to” they’re the logical organization layer for your data streams.</p><p><strong>Partitions (Physical Parallelism)</strong> Each topic is split into one or more partitions. A partition is an ordered, immutable sequence of messages. Partitions are the secret to Kafka’s parallelism multiple consumers can read from different partitions simultaneously.</p><h4>Discovery: The Bootstrap Server Concept</h4><p>A key insight that blew my mind:</p><blockquote><strong><em>Every broker in a Kafka cluster is also a Bootstrap Server.</em></strong></blockquote><p>When you configure a Kafka client (producer or consumer), you provide a list of “bootstrap servers.” These are just broker addresses. But here’s the magic:</p><ol><li>The client connects to <strong>any one</strong> of the bootstrap servers</li><li>It makes a <strong>Metadata Request</strong></li><li>The broker responds with the <strong>entire cluster topology</strong>: all brokers, all topics, all partitions, and which broker is the <strong>leader</strong> for each partition</li><li>The client then connects <strong>directly to the leader broker</strong> for the specific partition it needs</li></ol><p>This means you don’t need to know the full cluster layout upfront. Connect to one broker, discover everything, then route your requests intelligently.</p><h4>Queue vs Pub/Sub: Kafka Does Both</h4><p>Traditional messaging systems force you to choose:</p><ul><li><strong>Queue: </strong>Message published once, consumed once. Once a consumer reads it, it’s gone.</li><li><strong>Pub/Sub: </strong>Message published once, consumed by many subscribers. Everyone gets a copy.</li></ul><p>Kafka asked: <strong>“How can we do both?” </strong>The answer is <strong>Consumer Groups</strong>.</p><h4>Consumer Groups: The Unifying Abstraction</h4><p>A Consumer Group is a set of consumers that work together to consume a topic.</p><ul><li><strong>To act like a Queue</strong>: Put all your consumers in <strong>one group</strong>. Messages are divided among them each message is processed by exactly one consumer.</li><li><strong>To act like Pub/Sub</strong>: Put each consumer in its <strong>own unique group</strong>. Every consumer gets a copy of every message.</li><li><strong>Bonus</strong>: You get <strong>parallel processing for free</strong>. If a topic has 4 partitions and your consumer group has 4 consumers, each consumer handles one partition simultaneously.</li></ul><h4>Why Kafka is Fast (The Pros)</h4><ol><li><strong>Append-Only Commit Log</strong> — No random writes. Just append to the end of a file. This is as fast as disk I/O gets.</li><li><strong>Sequential I/O</strong> — The operating system is optimized for sequential reads/writes. Kafka leans into this hard.</li><li><strong>Zero-Copy</strong> — Kafka uses OS-level optimizations to send data from disk to network without copying it through user space.</li><li><strong>Distributed by Design</strong> — Partitions spread across brokers. Scale horizontally by adding more brokers.</li><li><strong>Long Polling</strong> — Consumers don’t spam the broker. They wait efficiently for new data.</li><li><strong>Event-Driven</strong> — Works as both Pub/Sub AND Queue via consumer groups.</li></ol><h4>The Tradeoffs (The Cons)</h4><ol><li><strong>ZooKeeper (Legacy)</strong> — Older Kafka versions required ZooKeeper for coordination. Newer versions (KRaft mode) are removing this dependency.</li><li><strong>Producer Partition Selection</strong> — If producers explicitly choose partitions poorly, you can get hot spots and uneven load.</li><li><strong>Operational Complexity</strong> — Installing, configuring, and managing a Kafka cluster is non-trivial.</li></ol><p>Now that we understand the theory, let’s build it ourselves and see these concepts come to life in code.</p><h3>Part 1: The Commit Log — Where Data Lives</h3><p>In Kafka, <strong>the log is the database</strong>. Every message is appended to the end of a file. There are no updates, no deletes just appends. This simplicity is what makes Kafka so fast.</p><h4>Step 1.1: Project Setup</h4><p>Create a new directory and initialize the project:</p><pre>mkdir node_kafka &amp;&amp; cd node_kafka<br>npm init -y</pre><p>We’re going to use <strong>zero external dependencies</strong>. Everything will be built with Node.js core modules: fs, path, and net.</p><h4>Step 1.2: Creating the CommitLog Class</h4><p>Create a file called commitLog.js. This class will handle all disk operations.</p><pre>// commitLog.js<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br><br>// Maximum size for a single segment file (in bytes)<br>const MAX_SEGMENT_SIZE = 1024;<br><br>class CommitLog {<br>    constructor(dirPath) {<br>        this.directory = dirPath;<br><br>        // Create the directory if it doesn&#39;t exist<br>        if (!fs.existsSync(this.directory)) {<br>            fs.mkdirSync(this.directory, { recursive: true });<br>        }<br>    }<br><br>    // Get all segment files, sorted by their base offset<br>    getSegments() {<br>        const files = fs.readdirSync(this.directory);<br>        return files<br>            .filter(f =&gt; f.endsWith(&#39;.log&#39;))<br>            .map(f =&gt; parseInt(f.replace(&#39;.log&#39;, &#39;&#39;), 10))<br>            .sort((a, b) =&gt; a - b);<br>    }<br><br>    // Generate the path for a segment file<br>    // We pad the offset to 10 digits so files sort correctly (e.g., 0000000000.log)<br>    getSegmentPath(offset) {<br>        return path.join(this.directory, offset.toString().padStart(10, &#39;0&#39;) + &#39;.log&#39;);<br>    }<br>}<br><br>module.exports = CommitLog;</pre><p><strong>Why </strong><strong>padStart(10, &#39;0&#39;)?</strong> File systems sort files alphabetically. If we named files 0.log, 10.log, 2.log, they would be sorted as 0, 10, 2. By padding to 0000000000.log, 0000000010.log, 0000000002.log, they sort correctly.</p><h4>Step 1.3: Appending Messages</h4><p>Now let’s add the ability to write messages. This is the core of the log.</p><pre>// Add this method to the CommitLog class<br>async append(message) {<br>    let segments = this.getSegments();<br>    <br>    // Bootstrap: Create the first segment if none exist<br>    if (segments.length === 0) {<br>        fs.writeFileSync(this.getSegmentPath(0), &#39;&#39;);<br>        segments = [0];<br>    }<br><br>    // Get the currently active segment (the last one)<br>    let baseOffset = segments[segments.length - 1];<br>    let activePath = this.getSegmentPath(baseOffset);<br>    <br>    // Get the current size of the active segment<br>    const stats = fs.statSync(activePath);<br>    <br>    // Format the message as JSON + newline<br>    const formattedMessage = JSON.stringify(message) + &#39;\n&#39;;<br>    const msgSize = Buffer.byteLength(formattedMessage, &#39;utf8&#39;);<br><br>    // SEGMENT ROTATION: If this message would exceed the limit, start a new segment<br>    if (stats.size + msgSize &gt; MAX_SEGMENT_SIZE) {<br>        // The new segment&#39;s base offset is the old base + the old segment&#39;s size<br>        baseOffset = baseOffset + stats.size; <br>        activePath = this.getSegmentPath(baseOffset);<br>        fs.writeFileSync(activePath, &#39;&#39;);<br>        console.log(`Rotating to new segment: ${path.basename(activePath)}`);<br>    }<br><br>    // Calculate the relative offset within this segment<br>    const relativeOffset = fs.statSync(activePath).size;<br>    <br>    // Append the message to disk<br>    fs.appendFileSync(activePath, formattedMessage);<br><br>    // Return the global offset (baseOffset + relativeOffset)<br>    return baseOffset + relativeOffset; <br>}</pre><p><strong>Key Concept: What is an “Offset”?</strong> In Kafka, an offset is a unique identifier for a message. In our implementation, the offset is literally <strong>the byte position</strong> in the log where the message starts. For example, if the first message is 50 bytes, the second message starts at offset 50.</p><h4>Step 1.4: Reading Messages</h4><p>Consumers need to read messages starting from a specific offset.</p><pre>// Add this method to the CommitLog class<br>async read(targetOffset) {<br>    const segments = this.getSegments();<br>    if (segments.length === 0) return { messages: [], nextOffset: targetOffset };<br><br>    // Find which segment contains the target offset<br>    let segmentBase = segments[0];<br>    for (const segment of segments) {<br>        if (segment &lt;= targetOffset) {<br>            segmentBase = segment;<br>        }<br>    }<br><br>    const logPath = this.getSegmentPath(segmentBase);<br>    const buffer = fs.readFileSync(logPath);<br>    <br>    // Calculate the position within the segment<br>    const relativeOffset = targetOffset - segmentBase;<br><br>    // If the offset is past this segment, try the next one<br>    if (relativeOffset &gt;= buffer.length) {<br>        const nextIdx = segments.indexOf(segmentBase) + 1;<br>        if (nextIdx &lt; segments.length) {<br>            return this.read(segments[nextIdx]);<br>        }<br>        return { messages: [], nextOffset: targetOffset };<br>    }<br><br>    // Read from the relative position to the end of the file<br>    const data = buffer.toString(&#39;utf8&#39;, relativeOffset);<br>    const lines = data.split(&#39;\n&#39;);<br><br>    const messages = [];<br>    let currentTotalOffset = targetOffset;<br>    <br>    for (const line of lines) {<br>        if (line.trim() === &#39;&#39;) {<br>            currentTotalOffset += 1;<br>            continue;<br>        }<br>        try {<br>            messages.push({<br>                offset: currentTotalOffset,<br>                message: JSON.parse(line)<br>            });<br>        } catch (e) { break; }<br>        <br>        // Move to the next offset (line length + 1 for the newline)<br>        currentTotalOffset += Buffer.byteLength(line, &#39;utf8&#39;) + 1;<br>    }<br><br>    return { messages, nextOffset: currentTotalOffset };<br>}</pre><h3>Part 2: The Broker — The Traffic Controller</h3><p>The Broker is a TCP server that listens for requests from Producers and Consumers. It routes requests to the appropriate CommitLog.</p><h4>Step 2.1: Creating the Broker</h4><p>Create a file called broker.js.</p><pre>// broker.js<br>const CommitLog = require(&#39;./commitLog&#39;);<br>const path = require(&#39;path&#39;);<br>const net = require(&#39;net&#39;);<br><br>class Broker {<br>    constructor(port) {<br>        this.port = port;<br>        this.logs = new Map(); // Stores CommitLog instances for each topic-partition<br>        this.offsets = new Map(); // Stores committed offsets for consumer groups<br>    }<br><br>    // Get (or create) the CommitLog for a specific topic and partition<br>    getLog(topic, partition) {<br>        const key = `${topic}-${partition}`;<br>        if (!this.logs.has(key)) {<br>            const logPath = path.join(__dirname, &#39;data&#39;, topic, partition);<br>            this.logs.set(key, new CommitLog(logPath));<br>        }<br>        return this.logs.get(key);<br>    }<br><br>    start() {<br>        const server = net.createServer((socket) =&gt; {<br>            console.log(&#39;Client connected&#39;);<br><br>            socket.on(&#39;data&#39;, async (data) =&gt; {<br>                // Split by newline - this is our message framing protocol<br>                const chunks = data.toString().split(&#39;\n&#39;);<br>                <br>                for (const chunk of chunks) {<br>                    if (!chunk.trim()) continue;<br><br>                    try {<br>                        const request = JSON.parse(chunk);<br>                        console.log(`Received request: ${request.type}`);<br><br>                        // Handle different request types<br>                        if (request.type === &#39;PRODUCE&#39;) {<br>                            const log = this.getLog(request.topic, request.partition);<br>                            const offset = await log.append(request.data);<br>                            socket.write(JSON.stringify({<br>                                type: &#39;produce_response&#39;,<br>                                offset<br>                            }) + &#39;\n&#39;);<br>                        } <br>                        else if (request.type === &#39;FETCH&#39;) {<br>                            const log = this.getLog(request.topic, request.partition);<br>                            const { messages, nextOffset } = await log.read(request.offset || 0);<br>                            socket.write(JSON.stringify({<br>                                type: &#39;fetch_response&#39;,<br>                                messages,<br>                                nextOffset<br>                            }) + &#39;\n&#39;);<br>                        }<br>                    } catch (error) {<br>                        console.error(&#39;Error:&#39;, error.message);<br>                        socket.write(JSON.stringify({<br>                            type: &#39;error&#39;,<br>                            message: error.message<br>                        }) + &#39;\n&#39;);<br>                    }<br>                }<br>            });<br>        });<br><br>        server.listen(this.port, () =&gt; {<br>            console.log(`Broker listening on port ${this.port}`);<br>        });<br>    }<br>}<br><br>// Start the broker on port 9092 (Kafka&#39;s default port)<br>const broker = new Broker(9092);<br>broker.start();</pre><p><strong>Key Concept: Protocol Framing</strong> TCP is a <strong>stream</strong>, not a message-based protocol. If you send two JSON objects quickly, they might arrive as one chunk or be split across multiple chunks. We solve this by ending every message with \n and splitting by newline on the server.</p><h3>Part 3: The Producer — Sending Messages</h3><p>Create a file called producer.js.</p><pre>// producer.js<br>const net = require(&#39;net&#39;);<br><br>class Producer {<br>    constructor(brokerAddress) {<br>        const [host, port] = brokerAddress.split(&#39;:&#39;);<br>        this.host = host;<br>        this.port = parseInt(port);<br>        this.client = new net.Socket();<br>    }<br><br>    connect() {<br>        return new Promise((resolve, reject) =&gt; {<br>            this.client.connect(this.port, this.host, () =&gt; {<br>                console.log(`Connected to broker at ${this.host}:${this.port}`);<br>                resolve();<br>            });<br>            this.client.on(&#39;error&#39;, reject);<br>        });<br>    }<br><br>    async send(topic, partition, message) {<br>        return new Promise((resolve, reject) =&gt; {<br>            const request = {<br>                type: &#39;PRODUCE&#39;,<br>                topic,<br>                partition,<br>                data: message<br>            };<br>            <br>            // Send the request<br>            this.client.write(JSON.stringify(request) + &#39;\n&#39;);<br><br>            // Wait for the response<br>            this.client.once(&#39;data&#39;, (data) =&gt; {<br>                const response = JSON.parse(data.toString());<br>                if (response.type === &#39;produce_response&#39;) {<br>                    resolve(response.offset);<br>                } else {<br>                    reject(new Error(`Unexpected response: ${response.type}`));<br>                }<br>            });<br>        });<br>    }<br><br>    disconnect() {<br>        this.client.destroy();<br>    }<br>}<br><br>module.exports = Producer;</pre><h4>Step 3.1: Testing the Producer</h4><p>Create example_test/run-producer.js:</p><pre>const Producer = require(&#39;../producer&#39;);<br><br>async function run() {<br>    const producer = new Producer(&#39;localhost:9092&#39;);<br>    await producer.connect();<br><br>    const offset1 = await producer.send(&#39;test-topic&#39;, &#39;0&#39;, { user: &#39;Alice&#39;, action: &#39;click&#39; });<br>    console.log(&#39;Message 1 at offset:&#39;, offset1);<br><br>    const offset2 = await producer.send(&#39;test-topic&#39;, &#39;0&#39;, { user: &#39;Bob&#39;, action: &#39;buy&#39; });<br>    console.log(&#39;Message 2 at offset:&#39;, offset2);<br><br>    producer.disconnect();<br>}<br><br>run().catch(console.error);</pre><p>Run the broker in one terminal: node broker.js Run the producer in another: node example_test/run-producer.js</p><h3>Part 4: The Consumer — Reading Messages</h3><p>Create a file called consumer.js.</p><pre>// consumer.js<br>const net = require(&#39;net&#39;);<br><br>class Consumer {<br>    constructor(brokerAddress, topic, partition, groupId) {<br>        const [host, port] = brokerAddress.split(&#39;:&#39;);<br>        this.host = host;<br>        this.port = parseInt(port);<br>        this.topic = topic;<br>        this.partition = partition;<br>        this.groupId = groupId;<br>        this.currentOffset = 0;<br>        this.client = new net.Socket();<br>    }<br><br>    async connect() {<br>        return new Promise((resolve, reject) =&gt; {<br>            this.client.connect(this.port, this.host, () =&gt; {<br>                console.log(`Connected to broker (Group: ${this.groupId})`);<br>                resolve();<br>            });<br>            this.client.on(&#39;error&#39;, reject);<br>        });<br>    }<br><br>    async fetch() {<br>        return new Promise((resolve, reject) =&gt; {<br>            const request = {<br>                type: &#39;FETCH&#39;,<br>                topic: this.topic,<br>                partition: this.partition,<br>                offset: this.currentOffset<br>            };<br><br>            this.client.write(JSON.stringify(request) + &#39;\n&#39;);<br><br>            this.client.once(&#39;data&#39;, (data) =&gt; {<br>                const response = JSON.parse(data.toString());<br>                if (response.type === &#39;fetch_response&#39;) {<br>                    this.currentOffset = response.nextOffset;<br>                    resolve(response.messages);<br>                } else {<br>                    reject(new Error(response.message));<br>                }<br>            });<br>        });<br>    }<br><br>    async start(handler) {<br>        console.log(&#39;Starting consumer loop...&#39;);<br>        <br>        while (true) {<br>            try {<br>                const messages = await this.fetch();<br>                for (const msg of messages) {<br>                    handler(msg.message, msg.offset);<br>                }<br>            } catch (err) {<br>                console.error(&#39;Fetch error:&#39;, err.message);<br>            }<br>            // Poll every second<br>            await new Promise(resolve =&gt; setTimeout(resolve, 1000));<br>        }<br>    }<br><br>    disconnect() {<br>        this.client.destroy();<br>    }<br>}<br><br>module.exports = Consumer;</pre><h3>Part 5: Sparse Indexing — The Performance Secret</h3><p>Right now, if we want to find offset 5000, we&#39;d have to read from the beginning of the file. That&#39;s slow. This is where <strong>Sparse Indexing</strong> comes in.</p><h4>How It Works</h4><p>Instead of indexing every message, we create an .index file that stores a position every <strong>100 bytes</strong>. To find an offset:</p><ol><li>Binary search the index to find the nearest entry.</li><li>Jump to that byte position in the log.</li><li>Scan sequentially from there.</li></ol><h4>Step 5.1: Adding Indexing to the CommitLog</h4><p>Update commitLog.js to add an index constant and update the append method:</p><pre>// Add at the top of the file<br>const INDEX_INTERVAL_BYTES = 100;<br><br>// Update the append method - add this after fs.appendFileSync():<br>const indexPath = activePath.replace(&#39;.log&#39;, &#39;.index&#39;);<br>const lastIndexEntryPos = stats.size;<br><br>// Only add an index entry if we&#39;ve crossed a 100-byte boundary<br>if (Math.floor(lastIndexEntryPos / INDEX_INTERVAL_BYTES) &lt; <br>    Math.floor((lastIndexEntryPos + msgSize) / INDEX_INTERVAL_BYTES)) {<br>    const indexEntry = `${baseOffset + relativeOffset}, ${relativeOffset}\n`;<br>    fs.appendFileSync(indexPath, indexEntry);<br>    console.log(`[INDEX] Added entry: ${indexEntry.trim()}`);<br>}</pre><h3>Part 6: The Discovery API — Finding the Cluster</h3><p>In a real system, clients don’t hardcode broker addresses. They ask the cluster “Where should I send data for partition X?”</p><h4>Step 6.1: Adding METADATA to the Broker</h4><p>Add this to the request handler in broker.js:</p><pre>else if (request.type === &#39;METADATA&#39;) {<br>    socket.write(JSON.stringify({<br>        type: &#39;metadata_response&#39;,<br>        brokers: [{ id: 0, host: &#39;localhost&#39;, port: this.port }],<br>        topics: [<br>            { <br>                name: request.topic || &#39;all&#39;, <br>                partitions: [<br>                    { id: 0, leader: 0 },<br>                    { id: 1, leader: 0 }<br>                ] <br>            }<br>        ]<br>    }) + &#39;\n&#39;);<br>    console.log(`[METADATA] Served cluster layout`);<br>}</pre><h4>Step 6.2: Adding getMetadata to the Producer</h4><pre>// Add to producer.js<br>async getMetadata(topic) {<br>    return new Promise((resolve, reject) =&gt; {<br>        const request = { type: &#39;METADATA&#39;, topic };<br>        this.client.write(JSON.stringify(request) + &#39;\n&#39;);<br>        <br>        this.client.once(&#39;data&#39;, (data) =&gt; {<br>            const response = JSON.parse(data.toString());<br>            if (response.type === &#39;metadata_response&#39;) {<br>                resolve(response);<br>            } else {<br>                reject(new Error(`Unexpected response: ${response.type}`));<br>            }<br>        });<br>    });<br>}</pre><h3>Part 7: The Inspector Tool — Seeing What’s on Disk</h3><p>Create tools/inspect.js to visualize the log structure:</p><pre>// tools/inspect.js<br>const fs = require(&#39;fs&#39;);<br><br>const logPath = process.argv[2];<br>if (!logPath) {<br>    console.log(&#39;Usage: node inspect.js &lt;path-to-log-file&gt;&#39;);<br>    process.exit(1);<br>}<br><br>const buffer = fs.readFileSync(logPath);<br>let position = 0;<br><br>console.log(`Inspecting: ${logPath}`);<br>console.log(&#39;-----------------------------------&#39;);<br><br>const lines = buffer.toString().split(&#39;\n&#39;);<br><br>for (const line of lines) {<br>    if (!line.trim()) continue;<br>    <br>    const size = Buffer.byteLength(line, &#39;utf8&#39;) + 1;<br>    console.log(`[Pos: ${position.toString().padStart(4)}] Size: ${size} | ${line.substring(0, 50)}...`);<br>    position += size;<br>}</pre><p>Run it: node tools/inspect.js data/test-topic/0/0000000000.log</p><h3>Conclusion:</h3><p>By building <strong>node_kafka</strong>, we’ve demystified the core of what makes Kafka work:</p><ol><li><strong>The Log is the Database</strong> — Just append, never update.</li><li><strong>Segments Keep Things Manageable</strong> — Roll files to keep the OS happy.</li><li><strong>TCP is a Stream</strong> — Frame your messages with delimiters.</li><li><strong>Sparse Indexes = Fast Lookups</strong> — Binary search + small scan.</li><li><strong>Discovery Makes Systems Dynamic</strong> — Clients find their own way.</li></ol><p>Watching <strong>Hussein Nasser’s</strong> videos gave me the map. Building this gave me the territory.</p><p>If you’re curious about systems, don’t just read about them. Build them. The bugs you encounter and the optimizations you implement will teach you more than any documentation ever could.</p><p><strong>Repository</strong>: <a href="https://github.com/Oluwateezzy/node_kafka">https://github.com/Oluwateezzy/node_kafka</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16a90296942" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design Learning Journey: Building a High-Throughput Telemetry Engine]]></title>
            <link>https://oluwateezzy03.medium.com/system-design-learning-journey-building-a-high-throughput-telemetry-engine-d4c0f82e3f25?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4c0f82e3f25</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[performance-engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 23:03:04 GMT</pubDate>
            <atom:updated>2026-01-24T23:03:04.262Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The concepts of System Design become much clearer when you see them in action</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmrfPpEVOLdbHCMNCExT3g.png" /></figure><p>Have you ever wondered how to handle millions of telemetry events without crushing your database? Or how to prevent a single “noisy neighbor” from bringing down your entire multi-tenant API?</p><p>I didn’t know the answers either but I was determined to find out.</p><p>When I received this challenge as a technical assessment, I could have reached for the usual suspects: pre-built monitoring platforms, off-the-shelf solutions, or heavy ORMs that abstract away the complexity. Instead, I saw an opportunity to truly understand the engineering behind high-throughput systems.</p><p>The requirements were deceptively simple but brutally demanding:</p><ul><li><strong>High write throughput: </strong>handle burst traffic without dropping events</li><li><strong>Low-latency reads: </strong>query millions of records in milliseconds</li><li><strong>Burst handling: </strong>survive traffic spikes that would normally crash systems</li><li><strong>Database hotspot prevention: </strong>stop one tenant from monopolizing resources</li></ul><p>This project became <strong>Telemetry Vault </strong>not just a technical assessment submission, but my personal masterclass in performance engineering.</p><h3>Part 1: Understanding the Problem Space</h3><h4>The Assessment That Changed Everything</h4><p>When I first opened the requirements document, I saw this:</p><p><strong><em>Build a telemetry ingestion and query service that can handle high write throughput with low-latency reads, burst handling, and database hotspot prevention.</em></strong></p><p>My initial reaction? “Sure, I’ll just use Kafka for ingestion, Redis for caching, and maybe throw in Elasticsearch for queries.”</p><p>But then I paused. How would i build it Better without too much external service? Or would I just be stitching together services I didn’t fully comprehend?</p><p>I made a choice: <strong>Build it from first principles using PostgreSQL (already part of the test requirment) and Node.js</strong>.</p><h4>What Makes Telemetry Different?</h4><p>I needed to understand what makes telemetry ingestion fundamentally different from normal CRUD operations:</p><ol><li><strong>Write-Heavy Workload</strong>: Telemetry systems might receive 10,000+ events per second but only handle a few dozen queries per minute. Traditional “balanced” database designs don’t work here.</li><li><strong>Bursty Traffic</strong>: Applications don’t generate telemetry at consistent rates. A deployment might trigger 50,000 events in 10 seconds, followed by near-silence.</li><li><strong>Multi-Tenancy Challenges</strong>: One customer doing a load test shouldn’t crash the service for everyone else.</li><li><strong>Time-Series Nature</strong>: Queries are almost always time-bound: “Give me logs from the last hour” not “Give me all logs ever.”</li></ol><h3>Part 2: Database Design</h3><h4>My First Mistake: The Monolithic Table</h4><p>My initial schema looked reasonable:</p><pre>CREATE TABLE telemetry_events (<br>    id VARCHAR(26) PRIMARY KEY,<br>    tenant_id VARCHAR(64) NOT NULL,<br>    event_type VARCHAR(64) NOT NULL,<br>    payload JSONB NOT NULL,<br>    timestamp TIMESTAMPTZ NOT NULL<br>);<br>CREATE INDEX idx_tenant_time ON telemetry_events(tenant_id, timestamp DESC);</pre><p>I loaded 1 million test events and ran a query. It took around 3 seconds. At 10 million events? Over 30 seconds. The database was doing full index scans, and the table was becoming a hotspot.</p><p>Then I discovered PostgreSQL’s native partitioning. The idea is beautifully simple: instead of one massive table, split the data into smaller tables based on time ranges.</p><p>When you query for “events in the last hour,” PostgreSQL only touches the relevant partition(s), ignoring everything else. This is called <em>partition pruning</em>.</p><pre>CREATE TABLE telemetry_events (<br>    id VARCHAR(26) NOT NULL,<br>    tenant_id VARCHAR(64) NOT NULL,<br>    event_type VARCHAR(64) NOT NULL,<br>    payload JSONB NOT NULL,<br>    idempotency_key VARCHAR(128),<br>    ingested_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP NOT NULL,<br>    timestamp TIMESTAMPTZ NOT NULL,<br>    <br>    -- Primary key MUST include the partition key<br>    CONSTRAINT telemetry_events_pkey <br>        PRIMARY KEY (timestamp, tenant_id, id),<br>    <br>    -- Idempotency scoped to partition (more on this later)<br>    CONSTRAINT telemetry_events_unique_idempotency <br>        UNIQUE (tenant_id, idempotency_key, timestamp)<br>) PARTITION BY RANGE (timestamp);<br>-- Index for queries<br>CREATE INDEX telemetry_events_query_idx <br>    ON telemetry_events (tenant_id, timestamp DESC);<br>-- Default partition for data outside defined ranges<br>CREATE TABLE telemetry_events_default <br>    PARTITION OF telemetry_events DEFAULT;</pre><h4>Key Design Decisions</h4><ol><li><strong>Timestamp as the Partition Key<br></strong>Every query in a telemetry system includes a time range. By partitioning on timestamp, I ensure PostgreSQL only scans relevant data.</li><li><strong>Composite Primary Key<br></strong>Notice the primary key includes timestamp. This is critical: PostgreSQL requires primary keys to include all partition key columns.</li><li><strong>The Idempotency Constraint (My Favorite Part)<br></strong>This deserves its own section.</li></ol><h3>Part 3: SQL Idempotency</h3><h4>The Problem with Traditional Idempotency</h4><p>In most APIs, idempotency looks like this:</p><pre>CREATE TABLE events (<br>    idempotency_key VARCHAR(128) UNIQUE,<br>    -- other fields<br>);</pre><p>Simple enough. But at scale, this creates a <strong>global bottleneck</strong>. Every insert checks the entire table for key conflicts.</p><p>In a partitioned system, this gets worse: PostgreSQL has to check <strong>every partition</strong> for duplicates. With 100 time-based partitions, a single insert does 100 lookups. Unacceptable.</p><h4>The Solution: Partition-Scoped Idempotency</h4><p>Think about it: if a client sends the same event with the same timestamp twice, that’s a duplicate. But if they send an event with the same idempotency_key but a different timestamp (e.g., one second later), that&#39;s likely a <strong>different event</strong>.</p><p>This realization led to the triple-key constraint:</p><pre>CONSTRAINT telemetry_events_unique_idempotency <br>    UNIQUE (tenant_id, idempotency_key, timestamp)</pre><p>By including timestamp in the constraint, uniqueness is scoped to the partition. PostgreSQL only checks the relevant time partition for conflicts a single lookup instead of hundreds.</p><h3>Part 4: The Ingestion Pipeline</h3><h4>The Core Problem</h4><p>Every HTTP request that writes directly to PostgreSQL:</p><ol><li>Opens a database connection (expensive)</li><li>Waits for the write to commit (blocks the thread)</li><li>Holds memory until the response completes</li></ol><p>At 100 requests/second, this works. At 10,000 requests/second? Your database connection pool exhausts, requests queue up, and everything crashes.</p><h4>The Solution: Decouple HTTP from Database Writes</h4><p>I needed to break the synchronous link between “request received” and “data persisted.”</p><p><strong>The API handler:</strong></p><ol><li>Validates the API key (more on this later)</li><li>Pushes the event to an in-memory array</li><li>Returns 202 Accepted <strong>immediately</strong></li><li>Moves on to the next request</li></ol><p>Meanwhile, a separate background worker flushes buffered events to PostgreSQL in batches.</p><h4>The Double-Buffer Pattern</h4><p>My first implementation looked like this:</p><pre>class IngestionService {<br>  private buffer: TelemetryEvent[] = [];<br>  <br>  async flush() {<br>    if (this.buffer.length === 0) return;<br>    <br>    // PROBLEM: This blocks new events from being added<br>    await db.insertInto(&#39;telemetry_events&#39;)<br>      .values(this.buffer)<br>      .execute();<br>    <br>    this.buffer = [];<br>  }<br>}</pre><p>The issue? While the database write is happening (potentially 500ms for a large batch), <strong>new incoming events are blocked</strong>. During high traffic, the buffer fills up, and I’m back to the original problem.</p><p>I needed a way to flush the buffer without blocking new writes. Enter the <strong>atomic swap pattern</strong>:</p><pre>export class IngestionService {<br>  private buffer: TelemetryEvent[] = [];<br>  private readonly BATCH_SIZE = 1000;<br>  private isFlushing = false;<br>  constructor() {<br>    // Safety net: flush every 10 minutes regardless of size<br>    setInterval(() =&gt; this.flush(), 1000 * 60 * 10);<br>  }<br>  public ingest(event: TelemetryEvent): void {<br>    // 1. FAST PATH: Push to RAM (microseconds)<br>    this.buffer.push(event);<br>    <br>    // 2. Trigger flush if batch size reached<br>    if (this.buffer.length &gt;= this.BATCH_SIZE &amp;&amp; !this.isFlushing) {<br>      this.flush();<br>    }<br>  }<br>  private async flush() {<br>    if (this.isFlushing || this.buffer.length === 0) return;<br>    this.isFlushing = true;<br>    // 3. ATOMIC SWAP: New events go to fresh buffer<br>    const batch = this.buffer;<br>    this.buffer = [];<br>    try {<br>      // 4. BULK INSERT: Write old buffer to database<br>      await db.insertInto(&#39;telemetry_events&#39;)<br>        .values(batch)<br>        .onConflict(oc =&gt; oc.doNothing()) // Handle idempotency conflicts<br>        .execute();<br>    } catch (error) {<br>      // In production: send to dead-letter queue<br>      console.error(&#39;Flush failed&#39;, error);<br>    } finally {<br>      this.isFlushing = false;<br>      <br>      // 5. If buffer filled during flush, flush again<br>      if (this.buffer.length &gt;= this.BATCH_SIZE) {<br>        setImmediate(() =&gt; this.flush());<br>      }<br>    }<br>  }<br>}</pre><h3>Why This Works</h3><ol><li><strong>Atomic Swap</strong>: const batch = this.buffer; this.buffer = []; happens in a single JavaScript event loop tick. New events immediately start filling a fresh buffer.</li><li><strong>Non-Blocking</strong>: The database write processes the old buffer while new events flow into the new one.</li><li><strong>Automatic Cascading</strong>: If the buffer fills again during a flush, the next flush triggers immediately via setImmediate().</li><li><strong>Burst Absorption</strong>: During a traffic spike, events accumulate in memory (cheap) instead of queueing at the database (expensive).</li></ol><h3>Part 5: Multi-Tenancy and Rate Limiting</h3><h4>The Noisy Neighbor Problem</h4><p>Imagine this scenario:</p><ul><li><strong>Tenant A</strong>: A small startup, sends 10 events/second</li><li><strong>Tenant B</strong>: An enterprise customer doing a load test, sends 9,000 events/second</li></ul><p>Without rate limiting, Tenant B fills the entire batch buffer, and Tenant A’s events can’t get in. Even worse, Tenant B could fill the buffer faster than it flushes, causing memory exhaustion.</p><h4>Building a Token Bucket Rate Limiter</h4><p>I needed rate limiting that was:</p><ul><li><strong>Fast</strong>: No external network calls</li><li><strong>Fair</strong>: Per-tenant limits</li><li><strong>Simple</strong>: No Redis/external state for MVP</li></ul><p>The token bucket algorithm was perfect:</p><pre>interface Bucket {<br>  tokens: number;<br>  lastRefill: number;<br>}<br>class RateLimiter {<br>  private buckets = new Map&lt;string, Bucket&gt;();<br>  private readonly REFILL_RATE = 100; // tokens per second<br>  private readonly MAX_TOKENS = 1000;  // burst capacity<br>  check(tenantId: string): boolean {<br>    const now = Date.now();<br>    let bucket = this.buckets.get(tenantId);<br>    if (!bucket) {<br>      bucket = { tokens: this.MAX_TOKENS, lastRefill: now };<br>      this.buckets.set(tenantId, bucket);<br>    }<br>    // Calculate tokens to add based on time elapsed<br>    const elapsedSeconds = (now - bucket.lastRefill) / 1000;<br>    const tokensToAdd = elapsedSeconds * this.REFILL_RATE;<br>    <br>    bucket.tokens = Math.min(<br>      this.MAX_TOKENS, <br>      bucket.tokens + tokensToAdd<br>    );<br>    bucket.lastRefill = now;<br>    // Try to consume a token<br>    if (bucket.tokens &gt;= 1) {<br>      bucket.tokens -= 1;<br>      return true; // Allow request<br>    }<br>    return false; // Rate limit exceeded<br>  }<br>}</pre><h3>How It Works</h3><p>Each tenant has a “bucket” of tokens. Each request consumes one token. Tokens refill at a constant rate.</p><p><strong>Parameters</strong>:</p><ul><li>REFILL_RATE = 100: In steady state, a tenant can make 100 requests/second</li><li>MAX_TOKENS = 1000: A tenant can burst up to 1,000 requests instantly (using accumulated tokens)</li></ul><p><strong>Example</strong>:</p><ul><li>Tenant sends 1,000 requests instantly → bucket allows it (burst capacity)</li><li>Tenant sends another 1,000 requests 1 second later → rate limiter rejects 900 of them</li><li>Tokens refill at 100/second → tenant back to normal capacity in ~10 seconds</li></ul><h4>The Authentication Cache</h4><p>Rate limiting isn’t useful if every request hammers the database to validate API keys. I needed caching.</p><p>My implementation uses an LRU (Least Recently Used) cache that:</p><ul><li>Stores API key → tenant ID mappings</li><li>Expires entries after 24 hours</li><li>Limits cache size to prevent memory leaks</li></ul><pre>class AuthService {<br>  private keyCache = new LRUCache&lt;string, string&gt;({<br>    max: 10000,<br>    ttl: 1000 * 60 * 60 * 24 // 24 hours<br>  });<br>  async validateKey(apiKey: string): Promise&lt;string | null&gt; {<br>    // Check cache first<br>    const cached = this.keyCache.get(apiKey);<br>    if (cached) return cached;<br>    // Cache miss: query database<br>    const tenant = await db<br>      .selectFrom(&#39;tenants&#39;)<br>      .select(&#39;id&#39;)<br>      .where(&#39;api_key&#39;, &#39;=&#39;, apiKey)<br>      .where(&#39;active&#39;, &#39;=&#39;, true)<br>      .executeTakeFirst();<br>    if (!tenant) return null;<br>    // Store in cache<br>    this.keyCache.set(apiKey, tenant.id);<br>    return tenant.id;<br>  }<br>}</pre><p><strong>Result</strong>: After the first request, API key validation takes <strong>microseconds</strong> instead of milliseconds.</p><h3>Part 6: Querying at Scale</h3><h4>The Problem with Traditional Pagination</h4><p>Most APIs paginate with LIMIT and OFFSET:</p><pre>-- Page 1<br>SELECT * FROM events ORDER BY timestamp DESC LIMIT 100 OFFSET 0;<br>-- Page 100<br>SELECT * FROM events ORDER BY timestamp DESC LIMIT 100 OFFSET 9900;</pre><p>Seems fine, right? <strong>Wrong.</strong></p><p>What PostgreSQL does for page 100:</p><ol><li>Read the first 10,000 rows (9,900 offset + 100 limit)</li><li>Sort them by timestamp</li><li>Skip the first 9,900</li><li>Return the next 100</li></ol><p>For page 1,000? PostgreSQL reads 100,000 rows just to return 100. This is <strong>O(N)</strong> complexity the deeper the page, the slower the query.</p><p>With millions of events, deep pagination becomes unusable.</p><h3>Cursor-Based Pagination: The O(1) Solution</h3><p>The key insight: <strong>We don’t need to count; we need to seek.</strong></p><p>Instead of saying “give me page 100,” we say “give me events older than this specific timestamp and ID.”</p><p><strong>The Cursor</strong>: A cursor is a Base64-encoded reference to the last row of the previous page:</p><pre>interface Cursor {<br>  timestamp: string;<br>  id: string;<br>}<br>function encodeCursor(cursor: Cursor): string {<br>  return Buffer.from(JSON.stringify(cursor)).toString(&#39;base64&#39;);<br>}<br>function decodeCursor(encoded: string): Cursor {<br>  return JSON.parse(Buffer.from(encoded, &#39;base64&#39;).toString());<br>}</pre><p><strong>The Query</strong>:</p><pre>async function queryEvents(<br>  tenantId: string, <br>  cursor?: string, <br>  limit: number = 100<br>) {<br>  let query = db<br>    .selectFrom(&#39;telemetry_events&#39;)<br>    .selectAll()<br>    .where(&#39;tenant_id&#39;, &#39;=&#39;, tenantId)<br>    .orderBy(&#39;timestamp&#39;, &#39;desc&#39;)<br>    .orderBy(&#39;id&#39;, &#39;desc&#39;)<br>    .limit(limit);<br>  // If cursor provided, seek to that position<br>  if (cursor) {<br>    const { timestamp, id } = decodeCursor(cursor);<br>    query = query.where(({ eb, or }) =&gt;<br>      or([<br>        eb(&#39;timestamp&#39;, &#39;&lt;&#39;, timestamp),<br>        eb.and([<br>          eb(&#39;timestamp&#39;, &#39;=&#39;, timestamp),<br>          eb(&#39;id&#39;, &#39;&lt;&#39;, id)<br>        ])<br>      ])<br>    );<br>  }<br>  return await query.execute();<br>}</pre><h3>Why This is O(1)</h3><p>PostgreSQL uses the index (tenant_id, timestamp DESC) to:</p><ol><li>Jump directly to the cursor position (index seek)</li><li>Read the next 100 rows sequentially</li><li>Return results</li></ol><p>Whether you’re on page 1 or page 1,000,000, the query time is <strong>constant</strong> (~2–5ms in my tests).</p><h3>The SQL Behind It</h3><p>For those curious, the generated SQL:</p><pre>SELECT * FROM telemetry_events<br>WHERE tenant_id = $1<br>  AND (<br>    timestamp &lt; $2 <br>    OR (timestamp = $2 AND id &lt; $3)<br>  )<br>ORDER BY timestamp DESC, id DESC<br>LIMIT 100;</pre><p>The (timestamp, id) composite comparison allows seeking to exact positions in the sort order.</p><h3>Conclusion</h3><p>One week ago, I didn’t know how to build a high-throughput telemetry system. I’d heard terms like “partitioning,” “idempotency,” and “burst handling,” but I couldn’t explain how they actually worked.</p><p>Today, I’ve built a production-grade system that:</p><ul><li>Ingests 10,000+ events/second without breaking a sweat</li><li>Queries millions of records in milliseconds</li><li>Handles traffic bursts gracefully</li><li>Prevents noisy neighbors from crushing the system</li></ul><p>But more importantly, <strong>I understand why it works</strong>.</p><p>Link: <a href="https://github.com/Oluwateezzy/telemetryVault">https://github.com/Oluwateezzy/telemetryVault</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4c0f82e3f25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Muzingo Music Synchronization: From Global Radio Streams to Per-Game Isolated Sessions]]></title>
            <link>https://medium.com/charisol-pulse/muzingo-music-synchronization-from-global-radio-streams-to-per-game-isolated-sessions-c87a49fea2f5?source=rss-99f5ff9a805b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c87a49fea2f5</guid>
            <category><![CDATA[deterministic-rotation]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[radiostreamingserver]]></category>
            <category><![CDATA[music-bingo]]></category>
            <dc:creator><![CDATA[Oluwatobiloba Olamide]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 15:06:04 GMT</pubDate>
            <atom:updated>2026-01-21T15:06:04.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sr0vxUsLdtnTj-lDgkpxbA.png" /></figure><h3>Introduction</h3><p>In the world of multiplayer music-bingo, synchronization is everything. If one player hears a song five seconds before another, the competitive integrity of the game vanishes. At Muzingo, we’ve spent significant engineering effort refining how we deliver audio snippets to thousands of players simultaneously.</p><h3>Why Radio-Songs Streaming?</h3><p>Our core gameplay depends on everyone identifying the same song at the same time. We don’t just “play a file”; we provide a continuous, time-synced audio experience.</p><ul><li><strong>Engagement</strong>: Short snippets (10s, 25s, or 40s) keep the game fast-paced.</li><li><strong>Fairness</strong>: Every player must be on the same beat to ensure winning “Muzingos” are valid.</li><li><strong>Scalability</strong>: Fetching a specific “current” state is more efficient than managing thousands of active socket streams for simple audio.</li></ul><h3>How We Approach the Problem</h3><p>Our system relies on two main components:</p><ol><li><strong>Radio Stations</strong>: The master configuration (playlist, mode, current track pointer).</li><li><strong>Radio Cache</strong>: A pre-calculated schedule showing exactly which song is playing at what millisecond.</li><li><strong>Deterministic Logic</strong>: Using mathematical offsets from the game’s start time to calculate the current song without needing a real-time “DJ” server for every room.</li></ol><h3>Previous Approach: The Global Broadcast</h3><p>In our initial implementation, the system operated like an FM radio station.</p><h4>How it worked:</h4><ul><li>A single RadioWorker would poll active playlists and update a global RadioStationCache.</li><li>Every game using a “90s Pop” playlist heard the exact same song at the exact same time.</li><li>The frontend fetched the <strong>radioUrl</strong> once and joined the &quot;global stream.&quot;</li></ul><h4>Pros:</h4><ul><li><strong>Low Compute</strong>: Only one calculation per playlist, regardless of the number of active games.</li><li><strong>Simplicity</strong>: Easy to conceptualize as a single broadcast.</li></ul><h4>Cons:</h4><ul><li><strong>Zero Privacy</strong>: Every game shared the same history. If a player was in two different games on the same playlist, they’d see identical results.</li><li><strong>Race Conditions</strong>: If a new song started just as a player clicked “Join,” the global state could shift mid-transition.</li><li><strong>Limited Control</strong>: You couldn’t have unique song rotations or “Easy Mode” vs “Hard Mode” variations within the same playlist for different game rooms.</li></ul><h3>Current Approach: Isolated Per-Game Sessions</h3><p>We recently-migrated to an Isolated Session model. This treats every game room as its own private radio station.</p><h4>How it works:</h4><ul><li><strong>Deterministic Rotation</strong>: When a game starts, we generate a unique <strong>songRotation</strong> array for that specific <strong>gameId</strong>.</li><li><strong>Time-Based Offsets</strong>: Instead of a global pointer, the “current song” is calculated mathematically:</li></ul><pre>// Backend: Deterministic Current Song Calculation<br>const now = new Date();<br>const gameStartTime = new Date(game.createdAt);<br>const elapsedSeconds = Math.floor((now - gameStartTime) / 1000);<br><br>const currentIndex = Math.floor(elapsedSeconds / snippetDuration) % songRotation.length;<br>const seekOffset = elapsedSeconds % snippetDuration;<br><br>// Constructing the URL with a time fragment<br>const radioUrl = `${currentSong.url}#t=${seekOffset}`;</pre><ul><li><strong>Per-Game Caching</strong>: Hints and “Already Played” validations are stored with a gameId index in DynamoDB.</li><li><strong>Snippet Enforcement</strong>: The frontend receives the URL, parses the fragment, and sets a local timer to force a refresh.</li></ul><pre>// Frontend: Parsing the Seek Offset<br>const streamTime = Number(newRadioUrl?.split(&#39;t=&#39;)[1]);<br>if (!isNaN(streamTime) &amp;&amp; audioRef.current) {<br>  audioRef.current.currentTime = streamTime;<br>}<br><br>// Frontend: Enforcing the Snippet Limit<br>useEffect(() =&gt; {<br>  const timer = setInterval(() =&gt; {<br>    const currentTime = audioRef.current?.currentTime || 0;<br>    if (currentTime &gt;= snippetDuration) {<br>      getRadioStationId(); // Trigger next track fetch<br>    }<br>  }, 1000);<br>  return () =&gt; clearInterval(timer);<br>}, [snippetDuration]);</pre><h4>Pros:</h4><ul><li><strong>Complete Isolation</strong>: Game A and Game B can use the same playlist but will hear different songs and have different winners.</li><li><strong>No Desync</strong>: Since everything is calculated from the <strong>GameStartTime</strong>, a player joining 10 minutes late automatically lands at the exact correct second of the current song.</li><li><strong>Better Hint Logic</strong>: Hints are now unique to the songs <em>actually</em> played in that specific game room.</li></ul><h4>Cons:</h4><ul><li><strong>High Data Volume</strong>: We now store cache entries per game rather than per playlist.</li><li><strong>Complex UI Logic</strong>: The frontend must be smarter, parsing time offsets and handling individual track transitions autonomously.</li></ul><h3>Conclusion</h3><p>Moving from a global broadcast to isolated sessions was a necessary step for Muzingo’s growth. By embracing deterministic, time-based offsets and per-game caching, we’ve improved the fairness of our leaderboard and given ourselves the flexibility to create more complex, isolated game modes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c87a49fea2f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/charisol-pulse/muzingo-music-synchronization-from-global-radio-streams-to-per-game-isolated-sessions-c87a49fea2f5">Muzingo Music Synchronization: From Global Radio Streams to Per-Game Isolated Sessions</a> was originally published in <a href="https://medium.com/charisol-pulse">Charisol Pulse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>