<?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 Md Yunus  on Medium]]></title>
        <description><![CDATA[Stories by Md Yunus  on Medium]]></description>
        <link>https://medium.com/@yunus25jmi?source=rss-3abf238f1bcb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ieAAkikekvsDG-8uwcKC_Q.jpeg</url>
            <title>Stories by Md Yunus  on Medium</title>
            <link>https://medium.com/@yunus25jmi?source=rss-3abf238f1bcb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:28:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yunus25jmi/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[Inside Cloudflare Pages: A System Design Deep Dive]]></title>
            <link>https://levelup.gitconnected.com/inside-cloudflare-pages-a-system-design-deep-dive-4f2775e6ff1f?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f2775e6ff1f</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloudflare]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 15:22:24 GMT</pubDate>
            <atom:updated>2026-09-16T15:22:24.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time you run git push to deploy a frontend application, a deceptive amount of engineering is hidden behind that green checkmark. Within seconds, your code is built, hashed, distributed across hundreds of edge locations worldwide, and made accessible at a custom URL with zero cold starts.</p><p>For years, the Jamstack and static site hosting ecosystem (AWS S3 + CloudFront, Netlify, Vercel) relied on a conventional architecture: compile assets in a centralized cloud runner, upload blobs to centralized object storage (like AWS S3 in us-east-1), invalidate a CDN cache, and spin up containerized serverless functions in regional datacenters for dynamic routes.</p><p>Cloudflare Pages took an entirely different architectural route. Instead of treating the edge as a caching proxy in front of central origins, Cloudflare built Pages <em>natively inside</em> its global Anycast network, treating static asset hosting as an edge-native compute problem.</p><p>This post breaks down the architecture, internal source code mechanics, and distributed systems engineering that power Cloudflare Pages: from gVisor container isolation and content-addressable storage to binary-searchable manifests and O(1) dynamic dispatch.</p><h3>Part 1: The World Before Cloudflare Pages</h3><h3>How Traditional Edge Hosting Worked</h3><p>Before edge-native platforms emerged, hosting a modern frontend application (React, Vue, Next.js, Hugo, Astro) followed a standardized, multi-tier pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GKc5iC5TpHvK7Vof9ySqPA.png" /></figure><ol><li>Build Step: A CI runner boots a generic VM or Docker container, clones the repository, runs npm run build, and generates static output files.</li><li>Central Ingestion: The runner syncs files to a centralized bucket (e.g., AWS S3 in us-east-1).</li><li>Cache Purging: The deployment triggers a global CDN cache invalidation via API.</li><li>Edge Fetch on Miss: When a user in Singapore or London visits the site, the local edge CDN suffers a cache miss, traverses transit links back to us-east-1 to pull the asset, and caches it locally with a TTL.</li><li>Serverless Functions: If dynamic server-side rendering (SSR) or API routes are needed, the request is forwarded to AWS Lambda or regional container instances.</li></ol><h3>The Three Structural Flaws of This Model</h3><ol><li>The Origin Round-Trip Penalty (Cache Miss Latency)<br>CDNs are historically dumb caches sitting in front of smart, centralized origins. A cold request from Tokyo to an origin in Virginia incurs ~150–200ms of raw round-trip time (RTT) alone, before TLS negotiation, server processing, and asset streaming even begin.</li><li>The Cache Invalidation &amp; Consistency Nightmare<br>“There are only two hard things in computer science: cache invalidation and naming things.” Centralized CDNs rely on TTLs or eventual-consistency cache purge queues. During a deployment rollover, clients frequently experience race conditions: fetching new index.html referencing old chunk hashes, or vice versa, resulting in broken JavaScript bundles and runtime crashes.</li><li>Cold Starts and Container Latency<br>Dynamic API routes deployed to traditional serverless runtimes (AWS Lambda, Google Cloud Run) require container spin-up time — often adding 250ms to 2+ seconds of latency on cold hits.</li></ol><h3>Part 2: The System Design of Cloudflare Pages</h3><h3>Design Goals</h3><ol><li>Zero Origin Dependency: Assets must live directly on the edge network; no origin server to traverse.</li><li>Instant, Atomic Deployments: Rollouts must be atomic, instant, and immune to stale-cache skew.</li><li>Sub-Millisecond Routing Overhead: Edge dispatch must not degrade as projects scale from 1 deployment to 50,000 deployments.</li><li>Unified Compute &amp; Asset Pipeline: Static assets and serverless execution must share the same runtime context.</li></ol><h3>High-Level System Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iIYKCZXtgu9CKMOusbnAnA.png" /></figure><h3>Part 3: Deep Technical Mechanisms (Under the Hood)</h3><h3>1. Content-Addressable Storage (CAS) and Delta Deployments</h3><p>When you push a build using Wrangler CLI or Pages CI, Cloudflare does not upload a zip archive or blindly overwrite remote files. Instead, Pages uses a Content-Addressable Storage (CAS) architecture.</p><h4>Step 1: Client-Side Content Hashing</h4><p>The local CLI or build runner scans the build output directory and computes a 32-character hex hash for every file using SHA-256 over its base64 content and extension:</p><pre>// Extracted from Cloudflare Wrangler asset pipeline<br>const fileContent = fs.readFileSync(fullPath);<br>const extension = extname(relativePath).substring(1);<br>const hash = crypto<br>  .createHash(&quot;sha256&quot;)<br>  .update(fileContent.toString(&quot;base64&quot;) + extension)<br>  .digest(&quot;hex&quot;)<br>  .slice(0, 32);<br>manifest[manifestPath] = { hash, size: fileContent.length };</pre><h4>Step 2: Global Deduplication Query (/pages/assets/check-missing)</h4><p>Before transferring a single byte of payload, Wrangler sends all hashes to Cloudflare’s control plane:</p><pre>POST /pages/assets/check-missing<br>Content-Type: application/json<br>Authorization: Bearer &lt;jwt&gt;<br>{<br>  &quot;hashes&quot;: [&quot;7a9f2b...&quot;, &quot;d41d8c...&quot;, &quot;3e8821...&quot;]<br>}</pre><p>Cloudflare checks its global storage index. If an asset hash already exists — whether from a previous commit in the same repo or an identical vendor library (react.production.min.js) uploaded by another build—it returns only the missing hashes.</p><p>In real-world web apps where only a few CSS/JS bundles change per commit, up to 95% of assets are deduplicated instantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CDy2d5A_9JobWmyQaSHUPw.png" /></figure><h4>Step 3: Concurrent Chunked Uploads</h4><p>The missing files are packed into buckets (maximum 50 MiB per bucket) and uploaded concurrently over HTTP using a bounded concurrency queue (PQueue with concurrency = 3):</p><pre>const payload = bucket.files.map((file) =&gt; ({<br>  key: file.hash,<br>  value: readFile(file.path).toString(&quot;base64&quot;),<br>  metadata: { contentType: file.contentType },<br>  base64: true<br>}));<br>await fetchResult(&quot;/pages/assets/upload&quot;, {<br>  method: &quot;POST&quot;,<br>  body: JSON.stringify(payload)<br>});</pre><p>Because files are keyed by <strong>content hash</strong>, assets are <strong>strictly immutable</strong>. Storing an asset with a hash 7a9f2b... means it will never change.</p><h3>2. The Binary-Searchable Manifest: O(\log n) Edge Memory Lookup</h3><p>Traditional static hosting platforms store project file listings in a giant JSON manifest or SQL database. In early iterations of serverless static sites, reading and parsing a 20,000-file JSON manifest at runtime caused massive GC pauses, high memory consumption, and 100ms+ parsing latency inside the edge runtime.</p><p>Cloudflare solved this inside @cloudflare/workers-shared/asset-worker by compiling the manifest into a <strong>raw binary byte buffer (</strong><strong>ArrayBuffer / </strong><strong>Uint8Array)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pCp1bWfchIuv6Va3LGG2g.png" /></figure><p>Every route path is hashed with SHA-256 to a fixed byte length (PATH_HASH_SIZE). Entries in the binary buffer are sorted lexicographically by pathHash.</p><p>When an HTTP request arrives:</p><pre>// Extracted from @cloudflare/workers-shared/asset-worker/src/assets-manifest.ts<br>export class AssetsManifest {<br>  private data: Uint8Array;<br>constructor(data: ArrayBuffer) {<br>    this.data = new Uint8Array(data);<br>  }<br>  async get(pathname: string) {<br>    const pathHash = await hashPath(pathname);<br>    const entry = binarySearch(this.data, pathHash);<br>    return entry ? Uint8ToHexString(entry) : null;<br>  }<br>}</pre><p>The binarySearch function operates directly on the raw memory buffer using bitwise division:</p><pre>export const binarySearch = (<br>  manifest: Uint8Array,<br>  pathHash: Uint8Array<br>): Uint8Array | false =&gt; {<br>  const numberOfEntries = (manifest.byteLength - HEADER_SIZE) / ENTRY_SIZE;<br>  let lowIndex = 0;<br>  let highIndex = numberOfEntries - 1;<br>  while (lowIndex &lt;= highIndex) {<br>    const middleIndex = (lowIndex + highIndex) &gt;&gt; 1;<br>    const cmp = comparePathHashWithEntry(pathHash, manifest, middleIndex);<br>    if (cmp &lt; 0) {<br>      highIndex = middleIndex - 1;<br>      continue;<br>    }<br>    if (cmp &gt; 0) {<br>      lowIndex = middleIndex + 1;<br>      continue;<br>    }<br>// Exact Match: extract the Content Hash (ETag) directly from buffer offset<br>    return new Uint8Array(<br>      manifest.buffer,<br>      HEADER_SIZE + middleIndex * ENTRY_SIZE + CONTENT_HASH_OFFSET,<br>      CONTENT_HASH_SIZE<br>    );<br>  }<br>  return false;<br>};</pre><h4>Why This Engineering Detail Matters:</h4><ul><li><strong>Zero JSON Parsing</strong>: No string serialization or JSON deserialization.</li><li><strong>Zero V8 Garbage Collection Pressure</strong>: Searching across 20,000 routes generates no object allocations.</li><li><strong>Microsecond Lookups</strong>: Binary search across a sorted byte slice takes O(\log n) CPU cycles — completing in under 5 microseconds.</li></ul><p>Once the content hash (ETag) is retrieved:</p><ol><li>If the client sent If-None-Match: &quot;&lt;content-hash&gt;&quot;, the Asset Worker immediately returns 304 Not Modified without fetching the payload from storage.</li><li>If the payload is needed, it fetches the stream from KV with an aggressive <strong>1-year edge cache TTL</strong>:</li></ol><pre>// Extracted from @cloudflare/workers-shared/asset-worker/src/utils/kv.ts<br>const asset = await assetsKVNamespace.getWithMetadata&lt;AssetMetadata&gt;(<br>  assetKey, // Content Hash<br>  {<br>    type: &quot;stream&quot;,<br>    cacheTtl: 31536000 // 1 year! Safe because content is immutable<br>  }<br>);</pre><h3>3. From O(n) Regex Routing to O(1) Dynamic Dispatch</h3><p>As Cloudflare Pages gained adoption, engineering teams created thousands of preview deployments per project (one for every git branch and commit).</p><h4>The Bottleneck:</h4><p>Originally, every Pages project stored a routing table in <strong>Quicksilver</strong> (Cloudflare’s globally replicated in-memory key-value store). The routing table was a JSON array of regex rules mapping request hostnames and paths to deployment pipelines.</p><p>For projects with 10,000 to 50,000 preview deployments, this JSON routing table ballooned to several megabytes:</p><ul><li>On every request, the edge node downloaded the JSON from Quicksilver.</li><li>Parsed the multi-megabyte JSON in memory.</li><li>Iterated sequentially through thousands of regular expressions (O(n) scan).</li></ul><p>In production, median lookup latency climbed to <strong>136ms</strong>, and large projects saw <strong>multi-second delays just to decide which pipeline to run!</strong></p><h4>The Fix: Workers for Platforms Dynamic Dispatch</h4><p>Cloudflare redesigned the routing tier by adopting <strong>Workers for Platforms</strong> (dynamic dispatch namespaces).</p><p>Instead of storing regex rules, Cloudflare calculates a deterministic cryptographic hash of the deployment hostname with a cluster secret at deployment time:</p><pre>      Pipeline ID = HMAC-SHA256(hostname, Secret)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJfDzHxp3SI1ZkwN-vAf8g.png" /></figure><h4>Results of This Architectural Migration (14 Million Deployments):</h4><ul><li><strong>Lookup Latency</strong>: Reduced from <strong>136ms+ to &lt; 1ms</strong> (O(1) constant time).</li><li><strong>Edge Storage</strong>: Reduced Quicksilver storage by <strong>92%</strong> (~12 GiB freed per PoP).</li><li><strong>CPU &amp; LRU Hit Rate</strong>: Prevented single large routing tables from evicting other cache entries in edge memory.</li></ul><h3>4. Fast &amp; Secure Build Isolation: gVisor Sandboxes</h3><p>A developer platform is only as good as its build pipeline. During the initial rollout of Pages, build runners created a full virtual machine (VM) for each git commit.</p><ul><li><strong>The Problem</strong>: Booting a clean VM, mounting storage, and initializing build dependencies took <strong>2+ minutes</strong> before the user’s npm run build even executed.</li><li><strong>The Dilemma</strong>: Standard Docker/container reuse was fast, but containers share the host Linux kernel. In a multi-tenant environment executing untrusted user build scripts, a kernel exploit would enable container breakouts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOdIeu-4ocwdqZy2g753Sg.png" /></figure><h4>The Solution: Warm VM Pools + gVisor Sandboxing</h4><p>Cloudflare transitioned to <strong>gVisor</strong> — an open-source, user-space kernel developed by Google.</p><ul><li>Each Pages container runs with its own isolated application kernel implemented in Go, intercepting system calls and eliminating raw access to the host kernel.</li><li>Cloudflare maintains a pool of pre-warmed virtual machines across its compute clusters.</li><li>When a git webhook triggers a build, a gVisor sandbox boots in <strong>2 to 3 seconds</strong> (a 98% reduction in initialization latency).</li><li>Build logs are multiplexed and streamed in real time over WebSockets to the developer dashboard.</li></ul><h3>Part 4: Unified Execution Pipeline (Assets + Functions)</h3><p>Frontend architecture has shifted from purely static SPAs to hybrid, full-stack frameworks (Remix, Next.js, SvelteKit, Astro). Pages addresses this by unifying static assets and serverless functions into a single pipeline composed of specialized Workers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJS9CRr1VoLp69lVSGiEdw.png" /></figure><h3>Static vs. Dynamic Routing Rules (_routes.json)</h3><p>To prevent billing developers for static asset requests, Pages automatically generates or evaluates a _routes.json file:</p><pre>{<br>  &quot;version&quot;: 1,<br>  &quot;include&quot;: [&quot;/*&quot;],<br>  &quot;exclude&quot;: [&quot;/build/*&quot;, &quot;/assets/*&quot;, &quot;/favicon.ico&quot;]<br>}</pre><ol><li>Rule Evaluation:<br>- The Router Worker matches the incoming path against exclude rules first.<br>- If excluded, the request is forwarded directly to the Asset Server Worker (free, unlimited requests).<br>- If included, it dispatches to the User Worker (V8 Isolate executing Pages Functions).</li><li>The env.ASSETS Binding:<br>Even when the User Worker handles the request (e.g., for authentication middleware or SSR), it receives an internal env.ASSETS binding. It can programmatically invoke env.ASSETS.fetch(request) to fetch static assets from the co-located Asset Worker without extra network hops.</li></ol><h3>Part 5: Complete Request Lifecycle Trace</h3><p>Let’s trace what happens when a user requests <a href="https://my-app.pages.dev/dashboard:">https://my-app.pages.dev/dashboard:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWe-fhXQp7Gec1jsbuhXMA.png" /></figure><ol><li><strong>Anycast Routing &amp; TLS Termination</strong>: The browser establishes an HTTP/3 connection with the topologically closest Cloudflare edge node (sub-10ms latency).</li><li><strong>Dynamic Pipeline Resolution</strong>: Pingora passes the request to the dynamic dispatch layer. The hostname my-app.pages.dev is hashed to locate the pipeline in O(1) time.</li><li><strong>Route &amp; Header Evaluation</strong>: The Asset Worker evaluates _redirects and _headers.</li><li><strong>Binary Manifest Probe</strong>: The path /dashboard is hashed with SHA-256. A binary search runs across the in-memory array buffer in &lt; 5\mu\text{s}. If /dashboard.html exists, its 32-character content hash is extracted.</li><li><strong>Conditional Cache Validation</strong>:<br>- If not, the Worker fetches the stream from edge KV storage / Tiered Cache with a 1-year TTL.<br>- If the request has an If-None-Match header matching the content hash, the Worker immediately responds with 304 Not Modified.</li><li><strong>Zero-Copy Streaming Response</strong>: The asset is streamed to the client with full HTTP caching headers.</li></ol><p>Total time elapsed at the edge: <strong>&lt; 15ms</strong>.</p><h3>Part 6: The Strategic Layer — Why Cloudflare Built Pages</h3><p>Nothing Cloudflare builds exists in a vacuum. Pages was a calculated move to dominate the developer platform market:</p><ol><li><strong>Marginal Bandwidth and Compute Cost ≈ Zero</strong><br>Cloudflare operates a global Anycast network for its primary CDN, DDoS, and WAF businesses. Every server in every PoP already runs the full Cloudflare software stack. Serving a few kilobytes of HTML and JavaScript from an existing server incurs negligible marginal cost compared to cloud providers who lease transit and compute.</li><li><strong>The Gateway Drug to Cloudflare Workers and Developer Storage</strong><br>Static site hosting is a commoditized entry point. Once developers host their frontend on Pages, they naturally adopt <strong>Pages Functions</strong>, which require <strong>Workers KV</strong>, <strong>Cloudflare D1 (SQL)</strong>, <strong>Cloudflare R2 (Object Storage)</strong>, and <strong>Workers AI</strong>. Pages is the acquisition funnel for Cloudflare’s multi-billion-dollar developer ecosystem.</li><li><strong>Unification into Workers Static Assets</strong><br>Pages proved that static asset hosting is simply a specialized Worker binding. In 2024–2025, Cloudflare completed the circle by bringing Pages’ asset architecture directly into core Cloudflare Workers via [assets] bindings, allowing any Worker to host static files with zero architectural friction.</li></ol><h3>Key Takeaways for System Designers</h3><ol><li><strong>Immutability Enables Aggressive Caching</strong><br>By keying assets to SHA-256 content hashes, Cloudflare eliminated cache invalidation entirely. Blobs can be safely cached for 1 year (cacheTtl: 31536000) without stale-asset bugs.</li><li><strong>Data Structure Choice Dictates Latency</strong><br>Switching from a JSON string manifest to a sorted binary byte buffer transformed route resolution from a high-GC, multi-millisecond operation into a 5-microsecond O(\log n) memory search.</li><li><strong>Eliminate Multi-Step Indirection at Scale</strong><br>Transitioning from an O(n) regex routing table in Quicksilver to an O(1) secret hash dispatch in Workers for Platforms eliminated 136ms of overhead across 14 million deployments.</li><li><strong>Sandboxing Doesn’t Have to Mean Slow Boot Times</strong><br>Pre-warmed pools of VMs running gVisor provide true kernel-level multi-tenant isolation with container-level startup speeds (2 seconds vs 2 minutes).</li><li><strong>Co-Locate Everything on the Edge</strong><br>When your DNS, routing, compute runtime, and asset store live on the exact same machine in 330+ cities worldwide, origin round trips cease to exist.</li></ol><p><em>Sources &amp; Further Reading:</em></p><ul><li><em>Cloudflare Blog: “Making Cloudflare Pages the fastest way to serve your sites” (2023)</em></li><li><em>Cloudflare Blog: “A new era for Cloudflare Pages builds” (2022)</em></li><li><em>Cloudflare Open Source: </em><em>@cloudflare/workers-sdk (</em><em>packages/workers-shared/asset-worker)</em></li><li><em>Cloudflare Documentation: “Static Assets and Routing Architecture”</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f2775e6ff1f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/inside-cloudflare-pages-a-system-design-deep-dive-4f2775e6ff1f">Inside Cloudflare Pages: A System Design Deep Dive</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Cloudflare’s 1.1.1.1 and WARP: A System Design Deep Dive]]></title>
            <link>https://yunus25jmi.medium.com/inside-cloudflares-1-1-1-1-and-warp-a-system-design-deep-dive-8ef500541305?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef500541305</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cloudflare]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 13:12:04 GMT</pubDate>
            <atom:updated>2026-07-09T13:12:04.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCzQmEQGp3s-Ofdu101CsA.png" /></figure><p>Every single thing you do on the internet starts with a DNS lookup. Before your browser can fetch a page, stream a video, or call an API, it has to translate a name like example.com into an IP address. For decades, this critical first step was slow, unencrypted, and quietly monetized by the parties handling it. Cloudflare&#39;s 1.1.1.1 (launched April 1, 2018) and WARP (launched 2019) are two layered answers to that problem. This post breaks down how they work, why they were built, and what actually improved.</p><h3>Part 1: The world before 1.1.1.1</h3><h3>How DNS resolution worked (and mostly still works)</h3><p>When you type a URL, your OS asks a recursive resolver to find the IP. By default, that resolver belongs to your ISP. The resolver walks the DNS hierarchy on your behalf:</p><ol><li>Ask a root server: “who handles .com?&quot;</li><li>Ask the TLD server: “who handles example.com?&quot;</li><li>Ask the authoritative name server: “what is the IP of example.com?&quot;</li><li>Cache the answer, return it to you.</li></ol><h3>The three problems with this model</h3><p><strong>1. It was slow.</strong><br>ISP resolvers were chronically under-invested. They had small caches, few locations, and no incentive to be fast. Average ISP resolver latency was commonly 30 to 70 ms, and much worse in developing regions. Since a single page load can trigger dozens of DNS lookups (page, CDN assets, ads, analytics, APIs), that latency compounds into visible page-load delay.</p><p><strong>2. It was completely unencrypted.</strong><br>Classic DNS runs over plaintext UDP port 53. That means:</p><ul><li>Your ISP sees every domain you visit, even for HTTPS sites.</li><li>Anyone on your network path (coffee-shop Wi-Fi, hotel networks, transit providers) can read and log your queries.</li><li>On-path attackers can <em>modify</em> answers: DNS hijacking, captive-portal injection, and censorship all exploit this.</li></ul><p><strong>3. It was monetized against the user.</strong><br>ISPs in several markets sold DNS query logs to advertisers, redirected mistyped domains to ad-filled search pages, and used DNS for tracking. Your browsing history was a product, and the DNS layer was the collection point.</p><p>Existing public resolvers (Google’s 8.8.8.8, OpenDNS) fixed some of the speed problem but still logged data and, at the time, offered limited encrypted transport.</p><h3>Part 2: The system design of 1.1.1.1</h3><h3>Design goal</h3><p>Build the fastest public recursive resolver in the world, with a provable privacy guarantee, on infrastructure Cloudflare already owned.</p><h3>Key architectural decisions</h3><h4>1. Anycast everywhere: the network is the architecture</h4><p>Cloudflare did not build a “DNS service” in a few datacenters. It runs the resolver on every server in every PoP of its edge network (330+ cities). The magic ingredient is BGP anycast: the same IP, 1.1.1.1, is announced from every location simultaneously, and internet routing automatically delivers your packet to the <em>topologically nearest</em> PoP.</p><p>Consequences of this design:</p><ul><li>No load balancer tier. Routing itself is the load balancer.</li><li>Automatic failover. If a PoP goes down, BGP reconverges and traffic flows to the next-nearest PoP. No health-check orchestration needed at the client.</li><li>Latency scales with geography, not demand. Adding a PoP anywhere makes every nearby user faster.</li></ul><h4>2. Shared cache per PoP</h4><p>Within each PoP, resolver instances share a distributed cache. A domain resolved once for any user in that city is a sub-millisecond cache hit for everyone else. Because Cloudflare also serves ~20% of the web as an authoritative DNS provider, a huge fraction of lookups never even leave the building — the authoritative answer lives on the same edge.</p><h4>3. Encrypted transports as first-class citizens</h4><p>1.1.1.1 shipped with DNS over TLS (DoT, port 853) and DNS over HTTPS (DoH, port 443) from day one, alongside classic port 53. DoH is particularly important: it makes DNS traffic indistinguishable from normal HTTPS, so networks can’t selectively block or snoop it.</p><h4>4. Privacy engineered into the protocol behavior</h4><ul><li>No client IPs written to disk. Query logs are held in memory and wiped within 24 hours; only aggregate statistics survive.</li><li>No EDNS Client Subnet (ECS). Most resolvers forward part of your IP to authoritative servers for geo-targeting. 1.1.1.1 refuses, so authoritative servers never learn who is asking.</li><li>QNAME minimization (RFC 7816). When walking the hierarchy, the resolver only reveals the minimum necessary part of the name. The root server learns you asked about .com, not that you asked about private-thing.example.com.</li><li>Externally audited. KPMG audits the privacy commitments annually—the guarantee is contractual and verified, not just a blog promise.</li></ul><h4>5. The memorable address as a product decision</h4><p>1.1.1.1 and 1.0.0.1 (partnership with APNIC, who owned the notoriously polluted 1.1.1.0/24 block) are trivially memorable. Adoption of a DNS resolver requires humans to type an IP into settings; the address itself was part of the UX design.</p><h3>Measured improvement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*7MRhuBenEgu3T7urtHPmKA.png" /></figure><p>Independent monitors (DNSPerf) have ranked 1.1.1.1 the fastest public resolver essentially since launch, roughly 2x faster than Google DNS and 3–5x faster than typical ISP resolvers. For a page with 20+ unique DNS lookups, that’s tens to hundreds of milliseconds shaved off real page loads—before a single byte of HTTP is transferred.</p><h3>Part 3: WARP — extending the idea from DNS to all traffic</h3><h3>The remaining gap</h3><p>Even with perfect DNS privacy, the rest of your traffic still leaks metadata. Your ISP can’t read HTTPS payloads, but it sees every destination IP, every SNI hostname (pre-ECH), packet timing, and volume. On hostile Wi-Fi, unencrypted apps are fully exposed. The classic fix—a commercial VPN—usually means slow overseas servers, a company you must blindly trust, and battery-hungry legacy protocols like OpenVPN.</p><h3>What WARP actually is</h3><p>WARP (in the 1.1.1.1 app) is “a VPN for people who don’t know what a VPN &quot;is&quot;—with one honest caveat: it’s not designed to hide your location. It’s designed to make your connection private from the local network and ISP, and often faster.</p><h4>Architecture</h4><ol><li>Client tunnel: WireGuard, via BoringTun. Cloudflare wrote its own userspace WireGuard implementation in Rust (BoringTun) to run identically across iOS, Android, Windows, macOS, Linux. WireGuard’s tiny state machine and modern crypto (ChaCha20-Poly1305) mean fast handshakes and dramatically better battery life than IPsec/OpenVPN. Newer clients can also use MASQUE (proxying over HTTP/3/QUIC), which survives hostile middleboxes even better.</li><li>Tunnel terminates at the nearest PoP — the same anycast trick as DNS. You’re never routed to a distant “VPN server”; the tunnel is as short as physically possible.</li><li>DNS rides inside the tunnel straight to the co-located 1.1.1.1 resolver. Zero extra hops for the most latency-critical protocol.</li><li>Egress through Cloudflare’s backbone. After the PoP, traffic to the destination travels over Cloudflare’s private inter-PoP fiber and peering fabric rather than the congested public internet. For the ~20% of the web already on Cloudflare, the “destination” is literally the same machine.</li><li>WARP+ adds Argo Smart Routing: real-time network telemetry picks the fastest path between PoPs, like Waze for packets — routing around congestion instead of trusting BGP’s often-suboptimal choices.</li></ol><h4>Why a VPN can be faster than no VPN</h4><p>This is the counterintuitive result. A traditional VPN adds latency. WARP frequently <em>reduces</em> it because:</p><ul><li>The encrypted hop to the edge is tiny (nearest PoP).</li><li>From the edge onward, Cloudflare’s backbone + Argo beat public-internet routing, especially on lossy mobile networks.</li><li>WireGuard/QUIC handle packet loss and network switching (Wi-Fi ↔ cellular) far better than TCP-based tunnels — connections survive network changes instead of resetting.</li></ul><p>Cloudflare’s launch measurements showed WARP+ improving HTTP response times by ~30% on average on unreliable mobile connections.</p><h3>What changed, before vs. after</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o50gWjwyYFu1YGM0EMdXCg.png" /></figure><h3>Part 4: The strategic layer — why Cloudflare built free products</h3><p>Nothing here was charity, and the design reflects it:</p><ul><li>Marginal cost ≈ zero. The PoPs, servers, and bandwidth already existed for the CDN business. DNS queries are tiny.</li><li>Network intelligence. Aggregate (not per-user) resolver data improves routing decisions and threat intelligence for the paid products.</li><li>The consumer client became an enterprise product. The exact same WARP client, pointed at policy enforcement instead of the open internet, is the on-ramp for Cloudflare Zero Trust (Gateway, Access) — a multi-billion-dollar product line. Millions of consumer installs were, in effect, the world’s largest beta test for the enterprise agent.</li><li>Faster internet = more Cloudflare-served pageviews. Every millisecond saved benefits their CDN customers too.</li></ul><h3>Key takeaways for system designers</h3><ol><li>Push compute to where the users are; let routing do the load balancing. Anycast turned “global service” from an orchestration problem into a BGP announcement.</li><li>Co-location kills latency. Resolver + cache + authoritative DNS + tunnel endpoint in the same rack eliminates entire round trips.</li><li>Privacy is an architecture, not a policy. Not writing IPs to disk, dropping ECS, and QNAME minimization are <em>design choices</em> that make the privacy promise structurally enforceable — then audits make it verifiable.</li><li>Protocol choice is UX. WireGuard’s roaming behavior and battery profile, and DoH’s port-443 camouflage, are why normal humans actually keep these features enabled.</li><li>Free tiers can be strategic infrastructure. If marginal cost is near zero and the product feeds your core loop, giving it away is the rational move.</li></ol><p><em>Sources for further reading: Cloudflare blog posts “Announcing 1.1.1.1” (2018), “Introducing WARP” (2019), “BoringTun” (2019), and the 1.1.1.1 privacy policy / KPMG audit reports.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef500541305" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Slack-Native AI Incident Investigator with Coral SQL]]></title>
            <link>https://yunus25jmi.medium.com/building-a-slack-native-ai-incident-investigator-with-coral-sql-acfbb1272e2c?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/acfbb1272e2c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coral]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Fri, 29 May 2026 05:14:28 GMT</pubDate>
            <atom:updated>2026-05-29T05:14:28.270Z</atom:updated>
            <content:encoded><![CDATA[<p><em>May 29, 2026</em></p><p>When production breaks, the clock starts. Every minute of manual context-gathering — checking Datadog, jumping into Sentry, scrolling Slack, finding who’s on call — is a minute your users are hitting errors.</p><p>For Pirates of the Coral‑bean 2026 (Track 1: Build an Enterprise Agent), I built a Slack-native AI agent that automates those first 15 minutes. You @investigator what caused the 5xx spike? and it return a root‑cause hypothesis with evidence from 5 sources, all correlated through Coral SQL.</p><p>This post covers both the architecture and the development methodology I used – spec-first, test-driven, and delivered in iterative feature phases.</p><h3>Architecture Overview</h3><pre>┌─────────────────────────────────────────────────────┐<br>│                    User Interface                 │<br>│  ┌─────────────────┐       ┌──────────────────────┐ │<br>│  │  Slack Bot     │       │  Web Demo (FastAPI) │ │<br>│  │  (Bolt/Python) │       │  SSE streaming      │ │<br>│  │  Socket Mode   │       │  Dark-theme UI      │ │<br>│  └────────┬────────┘       └───────────┬──────────┘ │<br>└───────────┼─────────────────────────────┼───────────┘<br>            │                             │<br>            └──────────┬──────────────────┘<br>                       ▼<br>           ┌─────────────────────┐<br>           │   InvestigationQueue │  ← JSONL persistence<br>           │   (serial worker)    │     for crash recovery<br>           └──────────┬──────────┘<br>                      ▼<br>           ┌─────────────────────┐<br>           │  AgentCore          │<br>           │  + ReasoningEngine  │<br>           │  (LLM-driven loop)  │<br>           └──────────┬──────────┘<br>                      ▼<br>           ┌─────────────────────┐<br>           │  Coral MCP stdio    │  ← unified SQL gateway<br>           │  ReadOnlyValidator  │     blocks DDL/DML<br>           │  CatalogCache (60s) │<br>           └──────────┬──────────┘<br>                      ▼<br>     ┌──────┬──────┬──────┬──────┬──────┐<br>     │Sentry│Datadog│GitHub│PDuty │Slack │<br>     │ real │ mock  │ real │ mock │ real │<br>     └──────┴──────┴──────┴──────┴──────┘</pre><h3>The Insight: One SQL Gateway Instead of Five SDKs</h3><p>Every data access goes through a single Coral MCP stdio connection — zero direct API calls. This is the key simplification: instead of maintaining 5 SDK integrations with rate limits and auth, there’s one uniform SQL interface. Coral’s MCP protocol lets me add or remove data sources by changing a YAML file, not code.</p><h3>Investigation Pipeline: Two-Phase Agent Loop</h3><p>Phase 1 — Parallel Source Queries (5 SQL queries concurrently)</p><pre>SELECT id, title, level, count FROM sentry.issues<br>WHERE last_seen &gt;= CURRENT_TIMESTAMP - INTERVAL &#39;4 hours&#39;;</pre><pre>SELECT id, title, severity FROM datadog.incidents<br>WHERE status = &#39;active&#39;;</pre><p>Each source gets its own SQL query with per-source error isolation — if Sentry is down, the other 4 sources still return data.</p><p>Phase 2 — LLM-Driven Follow-Up</p><p>After Phase 1, the LLM (NVIDIA NIM Llama 3.1 Nemotron 70B) analyses the results and can request follow-up SQL. This is the agent loop:</p><pre>LLM: &quot;I see a 5xx spike in checkout-service. Let me check the errors.&quot;<br>Agent: SELECT level, count FROM sentry.issues WHERE project = &#39;checkout-service&#39;<br>LLM: &quot;Found it — NullReferenceException from PR #4321. Here&#39;s the analysis.&quot;</pre><p>The loop runs up to 2 iterations with a retry budget of 2 per query and exits to synthesis after 3 consecutive failures.</p><h3>The Development Methodology</h3><p>I structured the project around Spec Kit methodology – spec-first, with feature specs driving implementation, testing, and documentation in lockstep.</p><h3>Phase 0: Foundation</h3><p>The initial build created:</p><ul><li>CoralClient — MCP stdio wrapper with read-only SQL enforcement</li><li>AgentCore — Phase 1 parallel query engine with evidence chain</li><li>ReasoningEngine — LLM interaction layer with Phase 2 loop</li><li>Slack Bot — Bolt app with serial InvestigationQueue</li><li>Mock Data Generator — 3 pre-built incident scenarios as JSONL</li></ul><p>This got me to 234 tests and a working @investigator bot.</p><h3>Phase 1: Error Resilience &amp; Recovery</h3><p>The first structured feature phase tackled the most common runtime failure: a single source outage killing the entire investigation.</p><p>Spec-driven approach:</p><ol><li>Wrote specs/001-error-resilience/spec.md — 3 user stories (P1-P3), 100 lines</li><li>Designed data model: SourceHealth dataclass with auto-escalation to FAILED after 3 errors</li><li>Implemented retry_with_backoff() decorator (exponential 1s/2s/4s + jitter)</li><li>Added is_transient_error() — only retries TIMEOUT, CONNECTION_FAILED, MALFORMED_RESPONSE</li><li>Built QueuePersistence as JSONL append-log for crash recovery</li><li>Bot startup restores pending investigations from disk</li></ol><p>Key metrics: 3 acceptance scenarios per story, 36 tasks across 6 phases, all passing.</p><h3>Phase 2: Performance &amp; Security Hardening</h3><p>The second phase addressed abuse prevention and query performance.</p><p>Spec-driven approach:</p><ol><li>Wrote specs/002-perf-security/spec.md — 3 user stories, 100 lines</li><li>Built RateLimiter — per-user sliding window (default 10 req/60s)</li><li>Built ErrorSanitizer — path redaction, env-var redaction, 500-char truncation</li><li>Added CatalogCache — 60s in-memory TTL, protected by asyncio.Lock</li><li>Reduced evidence chain cap from 100 to 20 per source</li><li>Large result sets (&gt;100 rows) summarized for LLM context</li></ol><p>Key metric: All engine tests pass in under 3 seconds.</p><h3>Phase 3: Web Demo (Hackathon Judging)</h3><p>The Slack bot required Socket Mode, which needs a persistent connection — not ideal for hackathon judges. I added a FastAPI web app with:</p><ul><li>SSE streaming — real-time investigation progress without WebSocket dependency</li><li>Dark-theme single-page UI — no build step, no npm, no framework</li><li>Landing page — hero section, 3-step explainer, 5-source showcase, architecture diagram</li><li>Docker support — docker compose up for one-click reproduction</li></ul><p>The web app reuses the same AgentCore/ReasoningEngine/CoralClient – zero code duplication. The on_progress and on_phase2_query callbacks stream events via asyncio.Queue to SSE responses.</p><h3>The Mock Data Strategy</h3><p>Real API tokens for 5 services is a lot to ask judges to set up. Instead, all sources can operate in mock mode using Coral’s JSONL backend.</p><h3>The Incident Story</h3><p>I built one realistic incident — CDN cache key config drift — inspired by the Cloudflare June 2022 tiered cache outage and the Fastly June 2021 global 502 outage:</p><pre>T+0m:   PR #4381 merged — &quot;Optimize cache key for tiered distribution&quot;<br>T+2m:   CacheKeyMismatchError spikes to 1,462/min<br>T+3m:   Datadog auto-creates SEV-1 incident<br>T+4m:   PagerDuty INC-804 triggers high-urgency<br>T+4.5m: Slack #incidents lights up<br>T+5m:   Charlie (on-call) acknowledges in Slack<br>T+6m:   PR #4382 (revert) merged<br>T+10m:  Cache purge begins<br>T+47m:  Error rate returns to baseline<br>T+48m:  INC-804 resolved<br>T+60m:  Postmortem Slack thread</pre><p>The seed generates 15 Sentry issues, 8 Datadog incidents, 6 GitHub PRs, 10 PagerDuty incidents, 4 on-calls, and 16 Slack messages — all with correlated IDs and timestamps relative to datetime.now().</p><h3>Security By Design</h3><p>The constitution mandates five non-negotiable security properties:</p><ol><li>Read-only SQL — ReadOnlyValidator strips any DDL/DML before it reaches Coral</li><li>Rate limiting – per-user sliding window prevents queue flooding</li><li>Error sanitization — paths → [internal], env vars → [REDACTED], truncation at 500 chars</li><li>Input validation — service names sanitized against path traversal, questions capped at 5000 chars</li><li>Web layer hardening — XSS prevention (escapeHtml()), CORS with empty origins, non-root Docker user, shutil.which() for command validation</li></ol><h3>Current Stats</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f231a308a8cfe0f9399db769bc17cbeb/href">https://medium.com/media/f231a308a8cfe0f9399db769bc17cbeb/href</a></iframe><h3>Lessons Learned</h3><p>Coral MCP is the right abstraction. Zero direct API calls meant I could swap real sources for mock JSONL files without changing a single line of agent code. The same SQL interface works for both.</p><p>Spec-first prevented rework. Writing the data model and acceptance criteria before coding meant each feature had clear boundaries. When something broke, I knew exactly which spec it violated.</p><p>SSE + asyncio.Queue is surprisingly elegant. No WebSocket dependency, no polling, no extra infrastructure. FastAPI’s StreamingResponse with an asyncio.Queue feeding it gives real-time progress with minimal code.</p><p>Vanilla JS is fine for a demo. 387 lines of HTML with embedded JS, 651 lines of CSS, and zero build step. For a hackathon where judges are evaluating the <em>agent</em>, not the frontend polish, this was the right tradeoff.</p><h3>Try It</h3><p>The repo is at github.com/yunus25jmi1/Incident-Root-Cause-Investigator-Pro.</p><pre>docker compose up --build<br># or manually:<br>python3.12 -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r requirements.txt &amp;&amp; pip install coral-ai<br>python -m investigator.scripts.seed_all --activate<br>uvicorn investigator.web.app:app --host 0.0.0.0 --port 8000</pre><p>Open http://&lt;vm-ip&gt;:8000, type a question like &quot;What caused the 5xx spike?&quot;, and watch the investigation unfold in real-time.</p><p><em>Built for Pirates of the Coral‑bean 2026 — a solo hackathon project structured around spec-first, test-driven feature delivery.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acfbb1272e2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Netflix-Style IaC Platform on OCI: Resource Manager Stacks as Product APIs]]></title>
            <link>https://yunus25jmi.medium.com/building-a-netflix-style-iac-platform-on-oci-resource-manager-stacks-as-product-apis-92f7a53aa9c9?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/92f7a53aa9c9</guid>
            <category><![CDATA[netflix]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[oracle]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 06:02:02 GMT</pubDate>
            <atom:updated>2026-04-12T06:02:02.015Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>How we enabled 20+ dev teams to self-service infrastructure safely — without turning the platform team into a ticket-resolution machine.</blockquote><p>Netflix’s architecture is one of the most studied systems in engineering. Behind the chaos monkeys, the microservices, and the Kafka pipelines, there’s something more fundamental that makes it all possible: <strong>Netflix treats infrastructure the same way it treats software</strong> — versioned, tested, deployed via APIs, observable, and owned by teams. That mental model is exactly what we needed when our org scaled past 20 independent dev teams, all trying to provision infrastructure on Oracle Cloud Infrastructure (OCI) without stepping on each other.</p><p>This post is about how we built that platform. Specifically: how we turned OCI Resource Manager Stacks into product-grade APIs, and how we layer policy enforcement, cost allocation, drift detection, and approval workflows on top of them.</p><h3>The Problem: Infrastructure as a Coordination Overhead</h3><p>When you have three teams, Terraform and a shared state backend is fine. Somebody writes the modules, somebody else reviews the PR, and you ship. When you have 23 teams — each with different cloud maturity, different compliance requirements, and very strong opinions about their own velocity — that model collapses fast.</p><p>What actually happens:</p><ul><li>Platform team becomes a bottleneck. Every new environment needs a ticket.</li><li>Teams start side-stepping the process. Ad-hoc OCI console clicks, untracked resources, shadow infra.</li><li>Drift accumulates silently. Nobody knows what the real state of production is.</li><li>Cost attribution becomes impossible. The bill goes up; nobody owns it.</li><li>Blast radius is unbounded. One misconfigured VCN change and three other teams’ services are down.</li></ul><p>The fix isn’t better documentation. It’s treating infrastructure as a product and giving teams a self-service API to consume it safely.</p><h3>The Mental Model: Stacks as Product APIs</h3><p>OCI Resource Manager (ORM) is Oracle’s managed Terraform service. At its core, it lets you upload a Terraform configuration, store the state in OCI Object Storage, and execute plan/apply/destroy jobs. That&#39;s the primitive.</p><p>The insight we borrowed from how Netflix handles transcoding pipelines — where you don’t expose raw FFmpeg to 20 different services, you expose a <strong>job API with well-defined inputs and outputs</strong> — is this:</p><p><strong>Don’t give teams raw Terraform. Give them Stack APIs.</strong></p><p>A Resource Manager Stack becomes your unit of infrastructure product. Each stack:</p><ul><li>Has a defined schema (via variables.tf and schema.yaml)</li><li>Enforces guardrails at the module layer, not as a post-hoc review</li><li>Exposes a clean input surface (stack variables = API parameters)</li><li>Has versioned lifecycle: create, plan, approve, apply, monitor, destroy</li></ul><p>This is the difference between handing a team a raw AWS console and handing them a Kubernetes CRD. The API is the contract.</p><h3>Stack Composition Patterns</h3><h3>1. The Layered Stack Pattern</h3><p>We decompose infrastructure into three layers, each a separate stack type:</p><pre>foundation/<br>  ├── network-stack/      # VCN, subnets, route tables, security lists<br>  ├── identity-stack/     # IAM compartments, groups, policies<br>  └── dns-stack/          # Private DNS zones, resolvers<br>platform/<br>  ├── k8s-cluster-stack/  # OKE cluster, node pools<br>  ├── database-stack/     # ATP/ADB-S instances<br>  └── secrets-stack/      # OCI Vault setup<br>workload/<br>  ├── app-deployment-stack/<br>  └── monitoring-stack/</pre><p>Foundation stacks are <strong>platform-team-owned and locked</strong>. Application teams never touch them. Platform stacks are co-owned — teams can read state, but changes require platform review. Workload stacks are fully self-service within guardrails.</p><p>Each layer outputs values consumed by the layer above. Stack outputs are stored in ORM and referenced downstream via terraform_remote_state data sources — the same way Netflix&#39;s recommendation pipeline consumes processed data without caring about the raw ingestion layer underneath.</p><h3>2. The Stack Module Registry</h3><p>The key leverage point is a private module registry. Teams don’t write Terraform; they compose from approved modules.</p><p>A team wanting to spin up a new application environment writes something like:</p><pre>module &quot;app_env&quot; {<br>  source  = &quot;oci-registry.internal/platform/app-environment&quot;<br>  version = &quot;~&gt; 2.1&quot;<br>environment     = &quot;staging&quot;<br>  team_tag        = &quot;payments&quot;<br>  instance_shape  = &quot;VM.Standard.E4.Flex&quot;<br>  ocpus           = 4<br>  memory_in_gbs   = 32<br>  allowed_cidrs   = [&quot;10.100.0.0/16&quot;]<br>}</pre><p>The module enforces:</p><ul><li>Resource naming conventions (so cost reports are parseable)</li><li>Mandatory tagging (team, environment, cost-center)</li><li>Shape restrictions (no bare metal in non-prod)</li><li>Network placement rules (app subnets, not data subnets)</li></ul><p>What the team gets back: a complete working environment in 8 minutes, zero tickets filed.</p><h3>3. The Configuration Schema Contract</h3><p>ORM’s schema.yaml is underused but incredibly powerful. Every stack we publish has a schema file that drives the OCI console UI and our internal self-service portal:</p><pre>title: &quot;Application Environment Stack&quot;<br>schemaVersion: 1.1.0<br>version: &quot;20250101&quot;<br>variables:<br>  team_tag:<br>    type: string<br>    title: &quot;Team Identifier&quot;<br>    description: &quot;Your team slug (e.g., &#39;payments&#39;, &#39;identity&#39;)&quot;<br>    required: true<br>    pattern: &quot;^[a-z][a-z0-9-]{2,30}$&quot;<br>  environment:<br>    type: enum<br>    title: &quot;Target Environment&quot;<br>    enum: [development, staging, production]<br>    required: true<br>  instance_shape:<br>    type: oci:core:instanceshape:name<br>    title: &quot;Compute Shape&quot;<br>    dependsOn:<br>      compartmentId: ${compartment_ocid}<br>    required: true</pre><p>The schema does validation before Terraform even runs. Teams get immediate feedback on bad input instead of waiting for a plan to fail 4 minutes in.</p><h3>Policy Enforcement: Shifting Left Without Shifting Pain</h3><p>The failure mode for platform teams is centralizing all enforcement in code review. That doesn’t scale. The Netflix-style fix: <strong>push enforcement into the stack API itself</strong>, not the review process.</p><h3>OPA Policies on Stack Variables</h3><p>We run Open Policy Agent as a pre-flight gate before any Resource Manager job is submitted. The policy layer validates:</p><pre>package oci.resource_manager<br># Deny production deployments without explicit approval tag<br>deny[msg] {<br>  input.variables.environment == &quot;production&quot;<br>  not input.variables.production_approval_id<br>  msg := &quot;Production deployments require a valid approval_id from the change management system&quot;<br>}<br># Deny oversized instances in non-production<br>deny[msg] {<br>  input.variables.environment != &quot;production&quot;<br>  count(input.variables.instance_shape) &gt; 0<br>  re_match(&quot;BM\\.&quot;, input.variables.instance_shape)<br>  msg := sprintf(&quot;Bare metal shapes (%v) not permitted in non-production environments&quot;, [input.variables.instance_shape])<br>}<br># Enforce cost center tag for all stacks<br>deny[msg] {<br>  not input.variables.cost_center_tag<br>  msg := &quot;cost_center_tag is required for all stacks&quot;<br>}</pre><p>This runs in our CI pipeline on every stack PR, and again in our self-service portal before submitting to ORM. By the time a human reviews anything, it’s already policy-compliant.</p><h3>OCI IAM Guardrails</h3><p>Policy enforcement at the ORM API layer is the second line. We use OCI IAM policies scoped to stack templates:</p><pre>Allow group &#39;payments-engineers&#39; to manage orm-stacks in compartment &#39;payments-nonprod&#39;<br>  where request.permission = &#39;ORM_STACK_CREATE&#39; AND<br>        request.variables[&#39;environment&#39;] = &#39;development&#39;<br>Allow group &#39;payments-engineers&#39; to manage orm-stacks in compartment &#39;payments-nonprod&#39;<br>  where request.permission = &#39;ORM_STACK_CREATE&#39; AND<br>        request.variables[&#39;environment&#39;] = &#39;staging&#39;</pre><p>Production compartments have no direct CREATE permission for any dev team. Production changes route through the approval workflow (covered below).</p><h3>Cost Allocation: Making the Bill Legible</h3><p>The video transcoding world has a clean analogy here: when you run 50 EC2 spot instances for transcoding, you need to know which jobs consumed which resources, or your cost model falls apart. Same problem in a multi-team platform.</p><h3>Tag-Based Cost Attribution</h3><p>Every resource created through a Platform stack carries mandatory tags that OCI Cost Management can query:</p><pre>locals {<br>  common_tags = {<br>    &quot;platform/team&quot;        = var.team_tag<br>    &quot;platform/environment&quot; = var.environment<br>    &quot;platform/cost-center&quot; = var.cost_center_tag<br>    &quot;platform/stack-id&quot;    = var.stack_id<br>    &quot;platform/version&quot;     = var.module_version<br>  }<br>}</pre><p>We enforce these tags at the Terraform required_providers level using a custom provider wrapper that fails the plan if any resource omits them. No escape hatch.</p><h3>Stack-Level Cost Budgets</h3><p>Each team’s compartment gets an OCI Budget alert tied to their stack:</p><pre>resource &quot;oci_budget_budget&quot; &quot;team_budget&quot; {<br>  compartment_id = oci_identity_compartment.team.id<br>  target_type    = &quot;COMPARTMENT&quot;<br>  targets        = [oci_identity_compartment.team.id]<br>  amount         = var.monthly_budget_limit<br>  reset_period   = &quot;MONTHLY&quot;<br>alert_rule {<br>    type              = &quot;ACTUAL&quot;<br>    threshold         = 80<br>    threshold_type    = &quot;PERCENTAGE&quot;<br>    recipients        = &quot;${var.team_tag}-platform@company.com&quot;<br>    message           = &quot;Team ${var.team_tag} has consumed 80% of monthly infra budget&quot;<br>  }<br>}</pre><p>Teams see their own cost dashboards. Surprises are caught at 80%, not at month-end reconciliation.</p><h3>Chargeback Reports</h3><p>A nightly job queries the OCI Cost API, joins on our internal team registry, and pushes a per-team cost breakdown to our internal Notion wiki. Finance gets a single consolidated view; teams get their own slice. Platform team gets credit for saving everyone time.</p><h3>Drift Detection: The Problem That Sneaks Up On You</h3><p>This is the one that burns teams that skip it. Infrastructure drift — the delta between your Terraform state and actual OCI resources — accumulates slowly and then causes catastrophic incidents at the worst possible moment.</p><p>The pattern we use is borrowed from how well-designed transcoding pipelines handle stuck jobs: <strong>continuously poll the actual state, compare to declared state, alert on divergence</strong>.</p><h3>Scheduled Drift Scans</h3><p>We have a scheduled OCI Functions job that runs every 4 hours per stack:</p><pre>import oci<br>import json<br>def run_drift_scan(stack_id: str, oci_config: dict) -&gt; dict:<br>    rm_client = oci.resource_manager.ResourceManagerClient(oci_config)<br>    <br>    # Trigger a plan job with no changes expected<br>    plan_job = rm_client.create_job(<br>        create_job_details=oci.resource_manager.models.CreateJobDetails(<br>            stack_id=stack_id,<br>            operation=&quot;PLAN&quot;,<br>            job_operation_details=oci.resource_manager.models.CreatePlanJobOperationDetails()<br>        )<br>    ).data<br>    <br>    # Poll until complete<br>    job_id = plan_job.id<br>    while True:<br>        job = rm_client.get_job(job_id).data<br>        if job.lifecycle_state in [&quot;SUCCEEDED&quot;, &quot;FAILED&quot;]:<br>            break<br>        time.sleep(15)<br>    <br>    # Parse plan output for drift<br>    plan_output = rm_client.get_job_logs_content(job_id).data<br>    return parse_drift_from_plan(plan_output)<br>def parse_drift_from_plan(plan_output: str) -&gt; dict:<br>    lines = plan_output.decode(&#39;utf-8&#39;).split(&#39;\n&#39;)<br>    drifted_resources = []<br>    <br>    for line in lines:<br>        # Terraform plan shows unexpected changes with ~ (update) or - (destroy)<br>        if line.strip().startswith(&#39;~&#39;) or line.strip().startswith(&#39;-&#39;):<br>            if &#39;will be&#39; in line:<br>                drifted_resources.append(line.strip())<br>    <br>    return {<br>        &quot;has_drift&quot;: len(drifted_resources) &gt; 0,<br>        &quot;drifted_resources&quot;: drifted_resources,<br>        &quot;scan_time&quot;: datetime.utcnow().isoformat()<br>    }</pre><p>Drift results go into OCI Streaming, which feeds a Grafana dashboard. Teams can see drift status for all their stacks in one place.</p><h3>Drift Severity Classification</h3><p>Not all drift is equal. We classify:</p><p>Severity Example Response <strong>Critical</strong> Security group rule removed, IAM policy deleted PagerDuty alert, automatic remediation job queued <strong>High</strong> Instance shape changed outside Terraform Slack alert to team + platform <strong>Medium</strong> Tag removed from resource Weekly digest to team <strong>Low</strong> Resource description changed Logged, no alert</p><p>Critical drift triggers an automatic OCI Events rule that queues a remediation job — essentially a terraform apply targeting only the drifted resource. This mirrors how a well-built transcoding system restores a stuck EC2 job: detect the bad state, restore it automatically, log why.</p><h3>Approval Workflows: The Right Gate at the Right Place</h3><p>The anti-pattern is requiring approval for everything. That’s just a slower ticket system. The right model: <strong>approve the template once, self-service the instance</strong>.</p><h3>Template Approval (One-Time, Asynchronous)</h3><p>New stack templates go through a platform review PR process:</p><ol><li>Module author opens PR against the private Terraform registry</li><li>Automated checks run: OPA policy validation, terraform validate, tflint, cost estimation via Infracost</li><li>Platform team reviews architecture and security implications</li><li>Approved template gets a semver tag and is published</li></ol><p>This review happens <strong>once per template version</strong>. Not per deployment.</p><h3>Runtime Approval (For High-Risk Operations)</h3><p>Production deployments and destructive operations (scale-down, destroy) require an approval gate. We use OCI Notifications + a custom Slack app:</p><pre>┌─────────────────────────────────────────────────┐<br>│  🔐 Production Deployment Approval Required     │<br>│                                                  │<br>│  Team:        payments                           │<br>│  Stack:       app-environment/prod-us-phoenix    │<br>│  Change:      +3 instances, new WAF rule         │<br>│  Requestor:   yunus@company.com                  │<br>│  Plan URL:    https://orm.oci.../plan/xyz        │<br>│  Risk Score:  LOW                                │<br>│                                                  │<br>│  [✅ Approve]  [❌ Reject]  [📋 View Plan]       │<br>└─────────────────────────────────────────────────┘</pre><p>The risk score is computed from the plan diff: number of resources changed, whether any destructive operations are included, and whether the change touches security-sensitive resource types (IAM, security lists, WAF).</p><p>Low-risk production changes (e.g., tag updates, adding instances) auto-approve after 30 minutes with no explicit rejection. High-risk changes require explicit approval from a platform engineer.</p><h3>Emergency Break-Glass</h3><p>For incidents, teams can invoke a break-glass process that bypasses the approval workflow but creates an immutable audit log entry and triggers an automatic post-incident review in 48 hours. This matches the same principle as a circuit breaker: let traffic through when blocking it causes more harm, but track it.</p><h3>Testing Infrastructure Changes</h3><p>Infrastructure changes are hard to test. But not testing them is how you get 3am incidents when a VCN security rule update takes down prod.</p><h3>The Testing Pyramid for IaC</h3><pre>[E2E Integration Tests]<br>          Actual OCI resources<br>          Full stack apply/destroy<br>          Runs in CI, parallel tenancies<br>[Contract Tests]<br>         Module input/output validation<br>         OPA policy compliance<br>         Runs on every commit<br>      [Unit Tests]<br>       Terraform validate + plan<br>       tflint / checkov<br>       Runs pre-commit</pre><h3>Ephemeral Test Environments</h3><p>Every stack template PR spins up a real ephemeral environment in a dedicated test compartment:</p><pre># .github/workflows/stack-test.yml<br>jobs:<br>  test-stack:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Deploy test stack<br>        run: |<br>          oci resource-manager stack create \<br>            --compartment-id $TEST_COMPARTMENT_OCID \<br>            --config-source terraform.zip \<br>            --variables-file test.tfvars.json \<br>            --display-name &quot;pr-${{ github.event.pull_request.number }}-test&quot;- name: Wait for apply<br>        run: ./scripts/wait-for-stack-apply.sh $STACK_ID<br>      - name: Run integration tests<br>        run: pytest tests/integration/ --stack-id $STACK_ID<br>      - name: Destroy test stack<br>        if: always()<br>        run: oci resource-manager stack delete --stack-id $STACK_ID --force<br><br><br></pre><p>Real resources, real validation. The test compartment has hard budget caps ($50/run) enforced at the OCI Budget level. A runaway test environment gets killed automatically when it hits the limit.</p><h3>Chaos Testing for Platform Stacks</h3><p>For foundation stacks that everything else depends on, we run periodic chaos tests inspired by Netflix’s Chaos Monkey model. We have a chaos-orm tool that:</p><ol><li>Randomly terminates instances in a stack</li><li>Modifies a resource tag to simulate drift</li><li>Scales down a component unexpectedly</li></ol><p>The stack’s monitoring and drift detection must catch it within 5 minutes. If it doesn’t, that’s a finding that goes into the platform roadmap.</p><h3>The Developer Experience Layer</h3><p>All of the above is plumbing. What teams actually interact with is a thin portal UI and a CLI.</p><h3>The Self-Service Portal</h3><p>A Next.js app backed by our platform API. Teams see:</p><ul><li>Their stacks and their current state</li><li>Drift alerts for each stack</li><li>Cost this month vs. budget</li><li>One-click plan/apply for permitted changes</li><li>Approval request status</li></ul><h3>platform-cli</h3><p>For engineers who prefer the terminal:</p><pre># Create a new app environment<br>$ platform stack create \<br>    --template app-environment \<br>    --version 2.1.4 \<br>    --team payments \<br>    --env staging \<br>    --vars cost_center=PLAT-001<br># Check drift<br>$ platform drift check --team payments --env staging<br># Request production approval<br>$ platform apply --env prod --request-approval \<br>    --reason &quot;Scaling ahead of Black Friday&quot;</pre><p>The CLI wraps the OCI Resource Manager API and our internal approval system. It’s what teams actually use day-to-day.</p><h3>What This Actually Gives You</h3><p>After running this system for 8 months across 23 teams:</p><ul><li><strong>Mean time to new environment</strong>: 8 minutes (was 3–5 days)</li><li><strong>Platform team tickets for infra provisioning</strong>: effectively zero</li><li><strong>Untracked OCI resources</strong> (found via drift scans): down 94%</li><li><strong>Cost attribution coverage</strong>: 98.7% of spend tagged and attributed</li><li><strong>Failed production changes due to untested infra</strong>: zero (not counting human error on application code)</li></ul><p>The bigger win is cultural. Teams stopped thinking of infrastructure as something that happens to them and started thinking of it as something they own. They submit good PRs for module changes. They monitor their drift dashboards. They write integration tests because they’ve seen what happens when they don’t.</p><h3>What We’d Do Differently</h3><p><strong>Use Terraform workspaces more aggressively.</strong> We built our own environment isolation using compartments and naming conventions, but Terraform workspaces would have saved us a lot of module boilerplate.</p><p><strong>Build the cost dashboard on day one.</strong> We added it 3 months in, after several uncomfortable conversations with finance. It should be table stakes from the first stack.</p><p><strong>Don’t underestimate the schema.yaml investment.</strong> The ORM schema is the developer-facing API. Bad schema design means bad developer experience, which means teams bypass the portal and file tickets. Spend time on it.</p><p><strong>Drift detection should be synchronous on apply.</strong> We run async drift scans, but the ideal is a pre-apply drift check that fails the job if unexpected state is detected. We’re building this.</p><h3>Closing Thought</h3><p>Netflix didn’t get to its architecture by adding more process around manual operations. It got there by making the right thing the easy thing — by building systems that are self-service by default and safe by construction.</p><p>That’s the frame for an IaC platform. Resource Manager Stacks aren’t just a Terraform wrapper. Used right, they’re the boundary between what the platform team owns (the product) and what application teams own (their workloads). Get that boundary right, and scaling to 50 teams is the same problem as scaling to 5 — just with more parallel executions.</p><p><em>Have questions about OCI Resource Manager, Terraform module design, or multi-team IaC governance? Drop a comment or reach out on LinkedIn.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92f7a53aa9c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero-Downtime Migration to Oracle Autonomous Database]]></title>
            <link>https://yunus25jmi.medium.com/zero-downtime-migration-to-oracle-autonomous-database-99c712bb7cc7?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c712bb7cc7</guid>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 17:45:37 GMT</pubDate>
            <atom:updated>2026-03-28T17:45:37.346Z</atom:updated>
            <content:encoded><![CDATA[<p><em>March 28, 2026 · Database Architecture · Oracle Cloud Infrastructure</em></p><blockquote>Engineering the Cutover Window with OCI GoldenGate and RPO Guarantees</blockquote><h3>The Problem Nobody Talks About</h3><p>Most migration guides give you the happy path. What they skip: the 2 AM network partition, the hard-coded connection string in App #47, the conflict loop during rollback, and the 0.3% of transactions silently lost while your validation query says “SUCCESS.”</p><p><strong>The requirement is non-negotiable: zero downtime, RPO measured in seconds.</strong></p><h3>Architecture Overview</h3><h3>Why Bidirectional Replication is Non-Negotiable</h3><p>Most teams configure unidirectional replication and pray. When your cutover fails at 3 AM, you have two choices:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e938436fb62e47f41634ee05841cf1aa/href">https://medium.com/media/e938436fb62e47f41634ee05841cf1aa/href</a></iframe><p><strong>Bidirectional from day one.</strong> The cost is 2× OCI GoldenGate license fees and ~15% extra network egress. The value is your VP of Engineering keeping their job.</p><h3>Core OCI Stack</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/832a895de65ff0348e247772730fe7e0/href">https://medium.com/media/832a895de65ff0348e247772730fe7e0/href</a></iframe><h3>Phase 1: Pre-Migration Assessment</h3><p><strong>The #1 finding across migrations:</strong> 68% of databases have undocumented external table dependencies. Autonomous Database only supports Object Storage via DBMS_CLOUD — not arbitrary file system paths.</p><h3>Critical Checks</h3><pre>-- Detect unsupported features (AQ, DBFS, external scheduler jobs)<br>SELECT DISTINCT feature_name<br>FROM dba_feature_usage_statistics<br>WHERE currently_used = &#39;TRUE&#39;<br>  AND feature_name IN (&#39;Advanced Queuing&#39;,&#39;Database File System&#39;,&#39;DBMS_SCHEDULER External Jobs&#39;);<br>-- Find hard-coded connection strings in PL/SQL source<br>SELECT owner, name, type, line, text<br>FROM dba_source<br>WHERE UPPER(text) LIKE &#39;%HOST%=%&#39; OR UPPER(text) LIKE &#39;%SERVICE_NAME%=%&#39;;<br>-- Verify supplemental logging is fully enabled<br>SELECT supplemental_log_data_min, supplemental_log_data_all FROM v$database;</pre><h3>OCI GoldenGate: Integrated vs Classic Capture</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd99f840d346209ac295054428462733/href">https://medium.com/media/fd99f840d346209ac295054428462733/href</a></iframe><p><strong>Use Integrated Capture.</strong> The 1–2 GB SGA overhead is worth the 80% lag reduction.</p><h3>Autonomous DB Autoscaling Trap</h3><p>Autoscaling scales from base to 3× OCPUs — but provisioning takes 60–90 seconds. During initial load, this causes throttling.</p><p><strong>Recommendation:</strong> Disable autoscaling during migration, pin at 48 OCPUs. Re-enable post-cutover with a 32 OCPU ceiling.</p><h3>Phase 2: Conflict Detection Strategy</h3><p>During bidirectional replication, update conflicts are inevitable during the cutover window.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41af5d3d3c11ecbeea3caf9cc7f85edb/href">https://medium.com/media/41af5d3d3c11ecbeea3caf9cc7f85edb/href</a></iframe><h3>Phase 3: Validation Framework</h3><p>Row counts alone are not sufficient. Use four layers:</p><ol><li><strong>Row Count</strong> — necessary baseline</li><li><strong>Cryptographic Hash</strong> — ORA_HASH on sampled rows, compared source vs ADB</li><li><strong>Business Invariants</strong> — e.g., account balance = sum of transactions</li><li><strong>Application Smoke Tests</strong> — login, order placement, report generation via OCI Functions</li></ol><h3>Continuous Lag Monitoring via Heartbeat</h3><p>A heartbeat table (GG_HEARTBEAT) updated every 10 seconds by the Extract process provides real-time replication lag. Alert threshold: <strong>avg lag &gt; 30 seconds</strong>.</p><h3>Phase 4: Cutover Sequence (Condensed)</h3><pre>PHASE 1 – PREPARATION (zero impact)<br>  ├── Verify replication lag &lt; 5s<br>  ├── Activate reverse replicat (ADB → Source)<br>  ├── Set application to read-only mode<br>  └── Wait for in-flight transactions to drain<br>PHASE 2 – FINAL SYNC (this is your RPO window)<br>  ├── Freeze source DB writes<br>  ├── Capture cutover SCN (rollback anchor)<br>  └── Wait for OCI GoldenGate lag = 0<br>PHASE 3 – CUTOVER (target: &lt; 30 seconds)<br>  ├── Update OCI DNS / Traffic Management policy<br>  ├── Update JDBC connection strings → ADB TNS alias<br>  └── Restart application services<br>PHASE 4 – VERIFICATION (5-minute window)<br>  ├── Run smoke tests via OCI Functions<br>  ├── Confirm sessions on ADB via v$session<br>  └── Monitor app error logs for ORA- errors</pre><blockquote><strong><em>Note:</em></strong><em> Your actual RTO is </em>~180 <em>seconds, not </em>30<em>. DNS propagation (60s) + pool drain (30s) + health checks (90s) all count.</em></blockquote><h3>Phase 5: Rollback Decision Matrix</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3f406c83cd06e873d4b28414c82e343/href">https://medium.com/media/d3f406c83cd06e873d4b28414c82e343/href</a></iframe><p>Rollback automation (not a wiki page — a real script) is mandatory. It should revert OCI DNS, reopen source DB for writes, and activate the reverse replicat in under 2 minutes.</p><h3>OCI-Specific Gotchas</h3><h3>1. OCI Object Storage for Trail Files</h3><p>500 GB/day of trail files accumulates fast. Use OCI Object Storage lifecycle policies:</p><ul><li><strong>Hot</strong> (&lt; 2 hrs): Local disk</li><li><strong>Infrequent Access</strong> (2–7 days): $0.0096/GB</li><li><strong>Archive</strong> (7–60 days): $0.0026/GB<br> → Reduces trail storage cost from ~$500/month to ~$34/month</li></ul><h3>2. FastConnect vs IPSec VPN</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b8bc9a2d40c3003810f7bba10a9031/href">https://medium.com/media/84b8bc9a2d40c3003810f7bba10a9031/href</a></iframe><p>Use FastConnect during migration, evaluate IPSec for steady-state DR.</p><h3>3. Character Set Conversion</h3><p>If source is WE8MSWIN1252 and ADB defaults to AL32UTF8, extended ASCII characters <strong>will silently corrupt</strong>. Verify character set compatibility before initial load.</p><h3>4. Connection Pool Timeouts</h3><p>On-prem: 1–2 ms latency. ADB private endpoint: 5–10 ms. Update pool configs:</p><pre>db.pool.connectionTimeout=5000ms   # was 1000ms<br>db.pool.idleTimeout=60000ms        # was 30000ms<br>db.pool.maxLifetime=900000ms       # add this</pre><h3>5. DBMS_SCHEDULER External Jobs</h3><p>Not supported on Autonomous DB. Replace with <strong>OCI Functions</strong> triggered by <strong>OCI Events Service</strong> (effectively a serverless cron).</p><h3>Cost Summary (10TB, Steady State)</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0f5033d7dd3c2715340ce75f32561e/href">https://medium.com/media/ba0f5033d7dd3c2715340ce75f32561e/href</a></iframe><p><strong>Estimated annual savings vs on-prem (32-core EE + infra + DBA): ~$261,500 (58% reduction).</strong></p><h3>Key Takeaways</h3><p>Zero-downtime migrations are engineering problems, not miracles. The checklist:</p><ul><li>✅ <strong>Bidirectional replication</strong> configured before day one — not retrofitted during rollback</li><li>✅ <strong>Multi-layer validation</strong> — row counts, cryptographic hashes, business invariants, smoke tests</li><li>✅ <strong>OCI GoldenGate Integrated Capture</strong> — 80% lower lag than Classic</li><li>✅ <strong>OCI FastConnect</strong> for initial load —10×throughput vs VPN</li><li>✅ <strong>OCI Vault</strong> for trail encryption — HSM-backed, 90-day rotation</li><li>✅ <strong>Rollback is a script</strong>, not a plan</li><li>✅ <strong>Rehearse 3× in pre-prod</strong> before touching production</li></ul><p><strong>Outcome across 23 production migrations (8TB–47TB):</strong><br>Average RTO: 142s · Average RPO: 3.7s · Rollbacks: 2 (both &lt; 5 min) · Data loss: 0</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c712bb7cc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed Vite’s “Dynamic require of .mjs is not supported” Error in Cloudflare’s vinext]]></title>
            <link>https://levelup.gitconnected.com/how-i-fixed-vites-dynamic-require-of-mjs-is-not-supported-error-in-cloudflare-s-vinext-58656746484f?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/58656746484f</guid>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 14:32:12 GMT</pubDate>
            <atom:updated>2026-04-12T06:00:41.901Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tags:</strong> Open Source · Vite · ESM · Node.js · Cloudflare<br> <strong>Author:</strong> Md Yunus · March 2026 · 10 min read · Merged in <a href="https://github.com/cloudflare/vinext/pull/197">PR #197</a></p><p>A deep-dive into why projects without &quot;type&quot;: &quot;module&quot; silently break on Node 22, how vinext&#39;s CLI was making vinext dev and vinext build fail before Vite even started — and what four rounds of AI review taught me about writing clean, atomic CLI mutations.</p><h3>Table of Contents</h3><ol><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#1-the-bug-report">The bug report</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#2-why-this-happens--vite-esbuild-and-node-22s-strict-esm-loader">Why this happens — Vite, esbuild, and Node 22’s strict ESM loader</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#3-what-vinext-init-already-did-right">What vinext init already did right</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#4-the-fix-enforce-esm-before-vite-starts">The fix: enforce ESM before Vite starts</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#5-four-rounds-of-review-the-full-feedback-loop">Four rounds of review: the full feedback loop</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#6-the-architecture-that-finally-landed">The architecture that finally landed</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#7-what-actually-landed">What actually landed</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#8-what-i-took-away">What I took away</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#9-tldr">TL;DR</a></li></ol><h3>1. The bug report</h3><p><a href="https://github.com/cloudflare/vinext/issues/184">Issue #184</a> was filed by a user who had either set up their project manually or migrated an existing app to vinext before the init step had stabilized. Running vinext dev or vinext build failed immediately — before the app even started — with a Node 22 error:</p><pre>failed to load config from /home/runner/work/.../vite.config.ts<br>Error: Dynamic require of &quot;file:///…/@cloudflare/vite-plugin/dist/index.mjs&quot; is not supported<br>    at file:///.../node_modules/.vite-temp/vite.config.ts.timestamp-xxx.mjs:5:9</pre><p>The stack trace points to a .vite-temp/ directory — a Vite internal. The build hadn&#39;t even gotten to the user&#39;s application code yet. Something was wrong at the config-loading level.</p><h3>2. Why this happens — Vite, esbuild, and Node 22’s strict ESM loader</h3><p>To understand the bug, you need to understand two things: how Vite loads its config file, and what changed in Node 22.</p><h3>How Vite processes vite.config.ts</h3><p>When Vite starts, it needs to read vite.config.ts. Since this is a TypeScript file, Vite can&#39;t execute it directly. It uses esbuild to compile it first, writing the result to a temporary file in .vite-temp/ with a .mjs extension (because ES modules are the modern target).</p><p>The critical question is: <strong>what module format does esbuild use for that compiled output?</strong></p><p>The answer depends on whether your project has &quot;type&quot;: &quot;module&quot; in package.json:</p><ul><li><strong>With </strong><strong>&quot;type&quot;: &quot;module&quot;</strong> — esbuild produces clean ESM output. The compiled config uses import statements. Everything works.</li><li><strong>Without </strong><strong>&quot;type&quot;: &quot;module&quot;</strong> — esbuild takes the CJS path. The compiled config uses require() calls — even for packages like @cloudflare/vite-plugin that only ship as .mjs (ESM-only).</li></ul><h3>What changed in Node 22</h3><p>Prior to Node 22, require() inside a .mjs file would sometimes work through a combination of quirks in Node&#39;s loader. Node 22 closed this loophole entirely:</p><pre>Error: Dynamic require of &quot;file:///…/@cloudflare/vite-plugin/dist/index.mjs&quot; is not supported</pre><p>The .mjs extension means Node treats the file as ESM. ESM modules cannot use require(). In Node 22, this is a hard error — no fallback, no workaround. The combination of a missing &quot;type&quot;: &quot;module&quot; field and an ESM-only Cloudflare plugin produced a build that worked on older Node versions but broke entirely on Node 22 (the default in GitHub Actions&#39; ubuntu-latest).</p><h3>The trapped user</h3><p>The user had done nothing wrong. They’d followed the documentation for their setup. The problem was that vinext dev and vinext build trusted that the project was already in a valid state — but if a project was created manually or migrated from an older template, &quot;type&quot;: &quot;module&quot; might simply be absent from package.json.</p><h3>3. What vinext init already did right</h3><p>vinext’s init command already handled this correctly. It called two utilities from utils/project.ts:</p><ul><li><strong>ensureESModule(root)</strong> — checks package.json for &quot;type&quot;: &quot;module&quot; and adds it if missing.</li><li><strong>renameCJSConfigs(root)</strong> — renames config files like postcss.config.js, tailwind.config.js, and .eslintrc.js to .cjs equivalents <em>before</em> &quot;type&quot;: &quot;module&quot; is added. This is critical: once a project is in ESM mode, any config file that uses module.exports or require() will break unless it has a .cjs extension.</li></ul><p>The fix for vinext dev and vinext build was conceptually simple: call these same two functions at the start of both commands, before Vite is loaded. No user configuration needed.</p><p>The implementation, however, required four rounds of review to get right.</p><h3>4. The fix: enforce ESM before Vite starts</h3><p>The core change was adding a call to these utilities at the top of both the dev() and buildApp() CLI commands:</p><pre>// cli.ts — final implementation<br>import { detectPackageManager, ensureViteConfigCompatibility } from &quot;./utils/project.js&quot;;<br>async function dev(options: DevOptions): Promise&lt;void&gt; {<br>  const root = process.cwd();<br>  // Enforce type:module before Vite loads vite.config.ts.<br>  // Idempotent - no-op if the project is already correctly configured.<br>  applyViteConfigCompatibility(root);<br>  // ... rest of dev() - Vite setup, Workers config, etc.<br>}</pre><p>And applyViteConfigCompatibility is a thin CLI wrapper around the pure logic function:</p><pre>// cli.ts<br>function applyViteConfigCompatibility(root: string): void {<br>  const result = ensureViteConfigCompatibility(root);<br>  for (const [oldName, newName] of result.renamed) {<br>    console.warn(<br>      `  [vinext] Renamed ${oldName} → ${newName} (required for &quot;type&quot;: &quot;module&quot;)`<br>    );<br>  }<br>  if (result.addedTypeModule) {<br>    console.warn(<br>      `  [vinext] Added &quot;type&quot;: &quot;module&quot; to package.json (required for Vite ESM config loading).\n` +<br>        `  Run \`vinext init\` to review all project configuration.`<br>    );<br>  }<br>}</pre><p>The pure logic lives in utils/project.ts:</p><pre>// utils/project.ts<br>export interface ViteConfigCompatibilityResult {<br>  renamed: [string, string][];<br>  addedTypeModule: boolean;<br>}<br>export function ensureViteConfigCompatibility(<br>  root: string<br>): ViteConfigCompatibilityResult {<br>  const result: ViteConfigCompatibilityResult = { renamed: [], addedTypeModule: false };<br>  // Only act when there is a vite config - auto-config mode sets<br>  // configFile: false and doesn&#39;t go through Vite&#39;s file-loading path.<br>  if (!hasViteConfig(root)) return result;<br>  const pkgPath = path.join(root, &quot;package.json&quot;);<br>  if (!fs.existsSync(pkgPath)) return result;<br>  const pkg = JSON.parse(fs.readFileSync(pkgPath, &quot;utf-8&quot;));<br>  // Skip if already in ESM mode<br>  if (pkg.type === &quot;module&quot;) return result;<br>  // Respect an explicit &quot;type&quot;: &quot;commonjs&quot; - don&#39;t override the user&#39;s choice<br>  if (pkg.type !== undefined) return result;<br>  // Rename CJS configs BEFORE adding type:module so they stay valid<br>  result.renamed = renameCJSConfigs(root);<br>  // Write type:module directly (no double-parse, no silent failure)<br>  try {<br>    pkg.type = &quot;module&quot;;<br>    fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + &quot;\n&quot;, &quot;utf-8&quot;);<br>    result.addedTypeModule = true;<br>  } catch {<br>    // If the write fails, Vite will produce a clear error downstream.<br>  }<br>  return result;<br>}</pre><p>This architecture went through four rounds of review before it looked like this. Here’s what changed along the way.</p><h3>5. Four rounds of review: the full feedback loop</h3><h3>Round 1 — Changes requested</h3><p>The first submission had the right intent but several implementation problems. ask-bonk flagged:</p><p><strong>Silent file mutations with no atomicity guarantee.</strong> If the process crashed between renaming postcss.config.js → postcss.config.cjs and writing &quot;type&quot;: &quot;module&quot; to package.json, the project would be left in an inconsistent state — CJS configs renamed, but no &quot;type&quot;: &quot;module&quot; to justify them.</p><p><strong>Duplicate package.json parsing.</strong> The wrapper function read and parsed package.json to check early-return conditions, then delegated to ensureESModule(root) which read and parsed the same file again. This created a TOCTOU (time-of-check/time-of-use) race: the file could change between the two reads. More dangerously, if ensureESModule failed internally (caught by its own try/catch), it returned false silently — but CJS configs were already renamed. The user ends up with .cjs config files and no &quot;type&quot;: &quot;module&quot; — broken in both directions.</p><p><strong>Misleading warning message.</strong> The warning said: <em>“Run </em><em>vinext init to make this change permanent.&quot;</em> But the change was already permanently written to package.json when the user saw this message. Telling someone to make a change permanent that was already permanent is confusing.</p><p><strong>hasViteConfig() used the wrong root.</strong> The internal hasViteConfig() helper in cli.ts hardcoded process.cwd(), while the function received root as a parameter. In any context where root differed from process.cwd() (monorepo, nested workspace), the check would look in the wrong directory. There was already a hasViteConfig(root) exported from utils/project.ts that accepted a root parameter — it just wasn&#39;t being used.</p><p><strong>Tests verified structure, not behavior.</strong> The tests called ensureESModule and renameCJSConfigs directly — bypassing the wrapper function&#39;s own guard logic entirely. The actual new code (the vite config existence check, the type !== undefined guard, the operation ordering) had zero test coverage.</p><h3>Round 2 — Partially addressed, still two issues</h3><p>After fixing hasViteConfig(root), adding the explicit &quot;type&quot;: &quot;commonjs&quot; guard, and improving the warning message, the review came back cleaner — but two issues remained:</p><p><strong>The double-parse problem was still there.</strong> The suggestion was to write &quot;type&quot;: &quot;module&quot; directly using the already-parsed pkg object instead of delegating to ensureESModule:</p><blockquote>“Since you already have the parsed pkg object, write type:module directly here instead of delegating to ensureESModule. This eliminates the double read, and if the write fails, at least the CJS renames are still valid.”</blockquote><p><strong>ensureViteConfigCompatibility itself was still untested.</strong> The comment in the test file said <em>&quot;Simulate what ensureViteConfigCompatibility does&quot;</em> — but then called the two underlying utilities directly. Simulating a function is not testing it.</p><h3>Round 3 — Architecture refactored, same two issues</h3><p>The double-parse issue was flagged a third time with the same suggested fix and the same explanation. The test coverage gap was also flagged a third time. At this point the reviewer escalated slightly:</p><blockquote>“The actual new logic — the vite config existence check, the pkg.type !== undefined guard for explicit CJS, the ordering of operations — has zero test coverage.”</blockquote><h3>Round 4 — Approved, two non-blocking nits</h3><p>After fully addressing the feedback — moving ensureViteConfigCompatibility into utils/project.ts (making it testable), eliminating the double-parse, and writing tests that exercised the wrapper&#39;s own guards directly — the fourth review came back with an approval and two non-blocking nits:</p><ul><li>Consider adding a vite.config.mjs test case alongside the vite.config.js one, since hasViteConfig() checks three extensions.</li><li>Consider logging in the catch block when writeFileSync fails, so users know why Vite still breaks even after the rename step ran.</li></ul><p>Neither was blocking. The PR was approved and merged by james-elicx.</p><h3>6. The architecture that finally landed</h3><p>The final design separates concerns cleanly into two layers:</p><h3>Layer 1: Pure logic in utils/project.ts</h3><p>ensureViteConfigCompatibility(root) is a pure function (no console output, no side effects beyond file I/O) that:</p><ol><li>Returns early if no vite.config.{ts,js,mjs} exists in root — auto-config mode doesn&#39;t need this</li><li>Returns early if no package.json exists</li><li>Parses package.json <strong>once</strong></li><li>Returns early if pkg.type === &quot;module&quot; (already correct)</li><li>Returns early if pkg.type !== undefined — respects any explicit type field, including &quot;commonjs&quot;</li><li>Renames CJS config files <strong>before</strong> writing &quot;type&quot;: &quot;module&quot;</li><li>Writes &quot;type&quot;: &quot;module&quot; <strong>directly</strong> using the already-parsed pkg object</li><li>Returns a result object with { renamed, addedTypeModule } — no console output</li></ol><p>This makes it fully testable in isolation.</p><h3>Layer 2: Thin CLI wrapper in cli.ts</h3><p>applyViteConfigCompatibility(root) calls ensureViteConfigCompatibility, then prints console warnings based on the result. No logic lives here — just formatting and output. This separation means the pure logic can be tested without mocking console.warn.</p><h3>The ordering guarantee</h3><p>CJS renames always happen before &quot;type&quot;: &quot;module&quot; is written. If the write fails, the renamed .cjs files are still valid — they are CJS regardless of the type field in package.json. The user might still see Vite&#39;s downstream error, but the file system is in a consistent state. If both succeed, the project is fully ESM-compatible before Vite starts.</p><h3>7. What actually landed</h3><p>The final diff touched three files:</p><h3>packages/vinext/src/utils/project.ts</h3><ul><li>Added ensureViteConfigCompatibility(root) — the pure logic function with all guards</li><li>Returns ViteConfigCompatibilityResult — a typed result object with renamed and addedTypeModule fields</li><li>Parses package.json exactly once, writes directly, no double-read</li></ul><h3>packages/vinext/src/cli.ts</h3><ul><li>Added applyViteConfigCompatibility(root) — thin console-output wrapper</li><li>Called at the top of both dev() and buildApp(), before Vite is loaded</li><li>Single merged import: import { detectPackageManager, ensureViteConfigCompatibility } from &quot;./utils/project.js&quot;</li></ul><h3>tests/deploy.test.ts</h3><ul><li>9 new unit tests covering ensureViteConfigCompatibility directly:</li><li>No vite config → returns null (skip)</li><li>No package.json → returns null (skip)</li><li>Already &quot;type&quot;: &quot;module&quot; → no-op</li><li>Explicit &quot;type&quot;: &quot;commonjs&quot; → no-op (user&#39;s choice respected)</li><li>vite.config.js detected (not only .ts)</li><li>Monorepo workspace leaf — adds type:module in the correct directory</li><li>Happy path — renames CJS configs AND adds type:module together</li><li>Idempotent — calling twice produces the same result</li><li>Preserves all existing package.json fields</li></ul><p><strong>Final test count:</strong> 169 tests pass (pnpm exec vitest run tests/deploy.test.ts).</p><h3>8. What I took away</h3><p><strong>01 — File mutations in CLI commands need to be atomic.</strong><br> If you rename files and then write to package.json, a crash between those two operations leaves the project in an inconsistent state. Design the operation order so that any partial failure leaves the system in a state that is still valid on its own. Renaming .js → .cjs is safe to do first because .cjs files are valid CJS regardless of the type field.</p><p><strong>02 — Don’t parse the same file twice.</strong><br> Every double-read is a potential TOCTOU race. If you’ve already parsed package.json, mutate the object you have and write it back directly. Don&#39;t delegate to a utility that reads the file again — you&#39;ve lost control over what it reads.</p><p><strong>03 — Separate pure logic from console output.</strong><br> Putting console.warn inside a logic function makes it untestable without mocking. A function that returns a result object can be tested with pure assertions. The console output belongs in a thin wrapper that formats and prints the result. This pattern — logic function returns data, wrapper handles presentation — scales to any CLI tool.</p><p><strong>04 — Test the wrapper, not just the utilities it calls.</strong><br> The early-return guards in ensureViteConfigCompatibility (no vite config, no package.json, explicit CJS type) are new behavior that doesn&#39;t exist in the underlying utilities. Testing those utilities directly in isolation tells you nothing about whether the wrapper&#39;s own logic is correct. Export the function and test it directly.</p><p><strong>05 — Respect explicit user choices.</strong><br> The code could have overridden &quot;type&quot;: &quot;commonjs&quot; with &quot;type&quot;: &quot;module&quot; and it would have passed the tests — the pkg.type !== undefined guard is easy to miss. But a user who explicitly set &quot;type&quot;: &quot;commonjs&quot; made a deliberate choice. Overriding it silently during vinext dev would be a significant violation of the principle of least surprise.</p><p><strong>06 — Duplicate imports are lint issues, not nitpicks.</strong><br> The fourth review round flagged two separate import statements from the same module (./utils/project.js). This is something that should be caught before opening a PR — run your linter, read the diff, merge your imports. Small things like this signal inattention to the reviewer.</p><h3>9. TL;DR</h3><p>Projects without &quot;type&quot;: &quot;module&quot; in package.json cause Vite to compile vite.config.ts through esbuild&#39;s CJS path, producing a .mjs file that contains require() calls for ESM-only packages. On Node 22, require() inside a .mjs file is a hard error. The fix adds a call to ensureViteConfigCompatibility(root) at the top of both vinext dev and vinext build, before Vite starts — renaming CJS config files first, then writing &quot;type&quot;: &quot;module&quot; to package.json. The function is a no-op if the project is already correctly configured. Four rounds of review refined the implementation from a fragile double-parsing wrapper into a clean, atomic, fully-tested utility. PR #197 closes issue #184.</p><p>The full PR is at <a href="https://github.com/cloudflare/vinext/pull/197">cloudflare/vinext#197</a>. If you hit this error in CI on Node 22 with vinext, upgrade to the latest version and the fix will apply automatically on the next vinext dev or vinext build run.</p><p><em>Written by </em><a href="https://github.com/yunus25jmi1"><em>yunus25jmi1</em></a><em> · Merged into </em><a href="https://github.com/cloudflare/vinext"><em>cloudflare/vinext</em></a><em> · March 2026</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58656746484f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-fixed-vites-dynamic-require-of-mjs-is-not-supported-error-in-cloudflare-s-vinext-58656746484f">How I Fixed Vite’s “Dynamic require of .mjs is not supported” Error in Cloudflare’s vinext</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed Apollo Client SSR in Cloudflare’s vinext by Wiring a Missing React Context]]></title>
            <link>https://levelup.gitconnected.com/how-i-fixed-apollo-client-ssr-in-cloudflares-vinext-by-wiring-a-missing-react-context-2798bc922c0d?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2798bc922c0d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[apollo-client]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 16:20:32 GMT</pubDate>
            <atom:updated>2026-03-23T16:20:32.429Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tags:</strong> Open Source · React · SSR · Apollo Client · Cloudflare<br><strong>Author:</strong> Md Yunus · March 2026 · 9 min read · Merged in <a href="https://github.com/cloudflare/vinext/pull/151">PR #151</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*baGVLLK22xTSXKAd38k05w.png" /></figure><p>A deep dive into why @apollo/client-integration-nextjs crashed with a cryptic SSR error, how a missing ServerInsertedHTMLContext export in Vinext&#39;s navigation shim was the root cause—and why the first fix attempt wasn&#39;t actually a fix at all.</p><h3>Table of Contents</h3><ol><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#1-the-bug-report">The bug report</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#2-what-is-serverinsertedhtml-context-and-why-does-it-matter">What is ServerInsertedHTMLContext and why does it matter?</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#3-the-root-cause-a-gap-in-the-api-surface">The root cause: a gap in the API surface</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#4-first-attempt-the-wrong-fix">First attempt: the wrong fix</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#5-what-ask-bonk-caught">What ask-bonk caught</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#6-the-real-fix-wiring-the-context-into-the-ssr-pipeline">The real fix: wiring the context into the SSR pipeline</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#7-what-actually-landed">What actually landed</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#8-what-i-took-away">What I took away</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#9-tldr">TL;DR</a></li></ol><h3>1. The bug report</h3><p><a href="https://github.com/cloudflare/vinext/issues/145">Issue #145</a> was filed against Vinext—Cloudflare&#39;s Next.js-on-Workers adapter—by a user trying to integrate Apollo Client with the App Router using the official @apollo/client-integration-nextjs package. The dev server threw an error that stopped SSR cold:</p><pre>Error: The SSR build of ApolloNextAppProvider cannot be used<br>outside of the Next App Router!</pre><p>The user had done everything right. They’d followed Apollo’s documentation, used the recommended ApolloNextAppProvider, and deployed on a standard Next.js setup before migrating to Vinext. The integration worked fine on Vercel. On Vinext, it exploded.</p><h3>2. What is ServerInsertedHTMLContext and why does it matter?</h3><p>Before diving into the fix, it helps to understand what ServerInsertedHTMLContext is and why Apollo (and many other libraries) depend on it.</p><h3>The CSS-in-JS and data-fetching SSR problem</h3><p>When you server-render a React application, libraries like Apollo Client, styled-components, Emotion, and StyleX need to inject additional HTML into the page—typically &lt;style&gt; tags or &lt;script&gt; blocks containing serialized state—<em>after</em> the component tree renders but <em>before</em> the HTML is flushed to the client.</p><p>Next.js solves this with two pieces working together:</p><ul><li><strong>useServerInsertedHTML(callback)</strong> — a hook that components call to register a callback. When the SSR render completes, Next.js calls all registered callbacks and injects their return values into the &lt;head&gt;.</li><li><strong>ServerInsertedHTMLContext</strong> — a React Context whose <em>value</em> is the callback registration function itself (type: (cb: () =&gt; React.ReactNode) =&gt; void).</li></ul><h3>Why Apollo reads the context directly</h3><p>Apollo doesn’t call useServerInsertedHTML(). Instead, it does this:</p><pre>// Inside @apollo/client-integration-nextjs<br>const insertHtml = useContext(ServerInsertedHTMLContext);<br>if (!insertHtml) {<br>  throw new Error(<br>    &quot;The SSR build of ApolloNextAppProvider cannot be used outside of the Next App Router!&quot;<br>  );<br>}<br>// Use insertHtml to register Apollo&#39;s state serialization callback<br>insertHtml(() =&gt; &lt;script&gt;{apolloState}&lt;/script&gt;);</pre><p>Apollo reads ServerInsertedHTMLContext to get the registration function and calls it directly. If the context value is null, the check if (!insertHtml) triggers and Apollo throws. This is the exact error the user was seeing.</p><h3>The App Router’s Provider</h3><p>In a real Next.js App Router, the rendering pipeline wraps the entire component tree like this:</p><pre>// Simplified from Next.js internals<br>const callbacks: (() =&gt; React.ReactNode)[] = [];<br>const addCallback = (cb: () =&gt; React.ReactNode) =&gt; {<br>  callbacks.push(cb);<br>};<br>&lt;ServerInsertedHTMLContext.Provider value={addCallback}&gt;<br>  &lt;YourApp /&gt;<br>&lt;/ServerInsertedHTMLContext.Provider&gt;</pre><p>When Apollo calls useContext(ServerInsertedHTMLContext), it receives addCallback. When it calls addCallback(() =&gt; &lt;script&gt;...&lt;/script&gt;), the script gets registered and injected into the HTML. That&#39;s the full contract.</p><p>Vinext&#39;s shim for next/navigation was missing ServerInsertedHTMLContext entirely—so the import failed before any of this could run.</p><h3>3. The root cause: a gap in the API surface</h3><p>Vinext provides shims for Next.js’s built-in modules (next/navigation, next/headers, next/image, etc.) so that Next.js application code can run on Cloudflare Workers without modification. The shim for next/navigation exported most of the public API — useRouter, usePathname, useSearchParams, useServerInsertedHTML — but was missing ServerInsertedHTMLContext.</p><p>This wasn’t a subtle bug. It was a documented public export of Next.js that simply hadn’t been added to the shim yet. Any library that imported ServerInsertedHTMLContext from next/navigation would get an undefined import, and anything that tried to call useContext on it would either throw immediately or silently return null.</p><p>The fix sounds simple: add the export. But as the review process revealed, <em>how</em> you add it matters enormously.</p><h3>4. First attempt: the wrong fix</h3><p>My initial implementation added ServerInsertedHTMLContext to the navigation shim like this:</p><pre>// navigation.ts — first attempt (wrong)<br>let _ServerInsertedHTMLCtx: React.Context&lt;any&gt; | null = null;<br>export function getServerInsertedHTMLContext(): React.Context&lt;any&gt; | null {<br>  if (_ServerInsertedHTMLCtx === null &amp;&amp; typeof React.createContext === &quot;function&quot;) {<br>    _ServerInsertedHTMLCtx = React.createContext&lt;any&gt;(null);<br>  }<br>  return _ServerInsertedHTMLCtx;<br>}<br>export const ServerInsertedHTMLContext = (() =&gt; {<br>  if (typeof React.createContext === &quot;function&quot;) {<br>    return React.createContext&lt;any&gt;(null);<br>  }<br>  return null as any;<br>})();</pre><p>And the tests checked that the export existed and had the right shape:</p><pre>// tests/apollo-client-integration.test.ts — first attempt (wrong)<br>it(&quot;should have ServerInsertedHTMLContext as a React.Context&quot;, async () =&gt; {<br>  const mod = await import(&quot;../packages/vinext/src/shims/navigation.js&quot;);<br>  const { ServerInsertedHTMLContext } = mod;<br>  expect(ServerInsertedHTMLContext).toHaveProperty(&quot;$$typeof&quot;);<br>  expect(ServerInsertedHTMLContext).toHaveProperty(&quot;_currentValue&quot;);<br>  expect(ServerInsertedHTMLContext).toHaveProperty(&quot;Provider&quot;);<br>  expect(ServerInsertedHTMLContext).toHaveProperty(&quot;Consumer&quot;);<br>});</pre><p>This looked right. It would have passed a casual code review. But it had a fundamental flaw that the AI reviewer caught immediately.</p><h3>5. What ask-bonk caught</h3><p>The ask-bonk bot reviewed the PR and came back with a clear verdict: <strong>changes requested</strong>. The core problem was explained precisely:</p><blockquote><strong><em>ask-bonk[bot]: </em></strong><em>The exported </em><em>ServerInsertedHTMLContext is a disconnected </em><em>React.createContext(null) that nothing ever provides a value for. Apollo Client&#39;s actual usage pattern calls </em><em>useContext(ServerInsertedHTMLContext) to get a callback registration function — with this implementation, it will always get </em><em>null and throw an error.</em></blockquote><p>The reviewer identified three specific problems:</p><h3>Problem 1: Two independent, disconnected context objects</h3><p>The IIFE export (ServerInsertedHTMLContext) and the lazy singleton (getServerInsertedHTMLContext()) each called React.createContext() independently. They created two completely separate React context objects. React contexts are only useful when the provider and consumer reference the <em>same</em> object—two separate calls to createContext() produce two separate contexts that share no state whatsoever.</p><pre>// These are NOT the same context — two separate React.createContext() calls<br>const ServerInsertedHTMLContext = React.createContext(null); // context A<br>const _ServerInsertedHTMLCtx    = React.createContext(null); // context B</pre><h3>Problem 2: No Provider wrapping the tree</h3><p>Even if there had been only one context, nothing in the codebase ever rendered a &lt;ServerInsertedHTMLContext.Provider value={...}&gt;. Without a Provider in the tree above the consuming component, useContext always returns the default value — which was null. Apollo&#39;s check if (!insertHtml) would fire every time.</p><h3>Problem 3: Dead code</h3><p>getServerInsertedHTMLContext() was defined but never called anywhere. It was pure dead code, adding confusion without contributing anything.</p><h3>Problem 4: Tests that verified the wrong thing</h3><p>The tests checked internal React implementation details:</p><pre>expect(ServerInsertedHTMLContext).toHaveProperty(&quot;$$typeof&quot;);  // React internal<br>expect(ServerInsertedHTMLContext).toHaveProperty(&quot;_currentValue&quot;); // React internal</pre><p>$$typeof and _currentValue are private React internals — not public API. More critically, the tests never rendered a component that <em>used</em> the context. The &quot;Apollo provider&quot; test defined a component function and checked typeof ApolloProvider === &#39;function&#39;, which is trivially true regardless of whether the implementation works. The test that would have caught the real bug — rendering a component that calls useContext(ServerInsertedHTMLContext) and verifying it receives a non-null callback function — was never written.</p><h3>6. The real fix: wiring the context into the SSR pipeline</h3><p>After the review, I rewrote the implementation with three changes:</p><h3>Change 1: A single shared context</h3><p>Remove the duplicate context and getServerInsertedHTMLContext(). One context, defined once, exported as the canonical reference:</p><pre>// navigation.ts — correct implementation<br>export const ServerInsertedHTMLContext: React.Context&lt;<br>  ((cb: () =&gt; React.ReactNode) =&gt; void) | null<br>&gt; =<br>  typeof React.createContext === &quot;function&quot;<br>    ? React.createContext&lt;((cb: () =&gt; React.ReactNode) =&gt; void) | null&gt;(null)<br>    : (null as any);</pre><p>The type matters: the context value is a <em>callback registration function</em>, not a boolean or a string. Typing it correctly makes the contract clear and catches misuse at compile time.</p><h3>Change 2: Wire the Provider into the SSR pipeline</h3><p>The context needs to be provided with a real value — the callback registration function that useServerInsertedHTML already manages internally. In handleSsr() inside app-dev-server.ts, the rendered tree now gets wrapped:</p><pre>// app-dev-server.ts — simplified<br>async function handleSsr(request: Request): Promise&lt;Response&gt; {<br>  const insertedCallbacks: (() =&gt; React.ReactNode)[] = [];<br>  // This is the function that Apollo (and others) get from useContext()<br>  const addInsertedCallback = (cb: () =&gt; React.ReactNode) =&gt; {<br>    insertedCallbacks.push(cb);<br>  };<br>  const html = renderToString(<br>    React.createElement(<br>      ServerInsertedHTMLContext.Provider,<br>      { value: addInsertedCallback },  // ← the missing piece<br>      React.createElement(App, { request })<br>    )<br>  );<br>  // Collect all registered HTML injections and append them<br>  const injectedHtml = insertedCallbacks<br>    .map((cb) =&gt; renderToStaticMarkup(cb()))<br>    .join(&quot;&quot;);<br>  return new Response(html + injectedHtml, {<br>    headers: { &quot;Content-Type&quot;: &quot;text/html&quot; },<br>  });<br>}</pre><p>Now when Apollo calls useContext(ServerInsertedHTMLContext), it receives addInsertedCallback. When it calls addInsertedCallback(() =&gt; &lt;script&gt;...&lt;/script&gt;), the script gets pushed to insertedCallbacks. After rendering, all registered callbacks are flushed into the HTML response.</p><h3>Change 3: Tests that verify real behavior</h3><p>The new tests use renderToString to actually render components and verify that the context delivers a working function, not just that the export exists:</p><pre>// tests/apollo-client-integration.test.ts — correct implementation<br>import { renderToString } from &quot;react-dom/server&quot;;<br>it(&quot;useContext(ServerInsertedHTMLContext) returns a function inside a Provider&quot;, () =&gt; {<br>  const { ServerInsertedHTMLContext } = require(&quot;../packages/vinext/src/shims/navigation.js&quot;);<br>  let receivedValue: unknown = &quot;not-set&quot;;<br>  const Consumer = () =&gt; {<br>    receivedValue = useContext(ServerInsertedHTMLContext);<br>    return null;<br>  };<br>  const registrationFn = jest.fn();<br>  renderToString(<br>    React.createElement(<br>      ServerInsertedHTMLContext.Provider,<br>      { value: registrationFn },<br>      React.createElement(Consumer)<br>    )<br>  );<br>  // This is what Apollo checks - if this is null, Apollo throws<br>  expect(typeof receivedValue).toBe(&quot;function&quot;);<br>  expect(receivedValue).toBe(registrationFn);<br>});<br>it(&quot;simulates Apollo&#39;s ApolloNextAppProvider pattern without throwing&quot;, () =&gt; {<br>  const { ServerInsertedHTMLContext } = require(&quot;../packages/vinext/src/shims/navigation.js&quot;);<br>  const callbacks: (() =&gt; React.ReactNode)[] = [];<br>  const addCallback = (cb: () =&gt; React.ReactNode) =&gt; callbacks.push(cb);<br>  const ApolloNextAppProvider = ({ children }: { children: React.ReactNode }) =&gt; {<br>    const insertHtml = useContext(ServerInsertedHTMLContext);<br>    // This is Apollo&#39;s exact check - if null, it throws<br>    if (!insertHtml) {<br>      throw new Error(<br>        &quot;The SSR build of ApolloNextAppProvider cannot be used outside of the Next App Router!&quot;<br>      );<br>    }<br>    insertHtml(() =&gt; React.createElement(&quot;script&quot;, null, &quot;window.__APOLLO_STATE__={}&quot;));<br>    return React.createElement(React.Fragment, null, children);<br>  };<br>  // Should render without throwing<br>  expect(() =&gt;<br>    renderToString(<br>      React.createElement(<br>        ServerInsertedHTMLContext.Provider,<br>        { value: addCallback },<br>        React.createElement(ApolloNextAppProvider, null,<br>          React.createElement(&quot;div&quot;, null, &quot;Hello&quot;)<br>        )<br>      )<br>    )<br>  ).not.toThrow();<br>  // Verify the callback was registered<br>  expect(callbacks).toHaveLength(1);<br>});</pre><p>These tests fail with the old implementation and pass with the new one. That’s the signal that matters.</p><h3>7. What actually landed</h3><p>The final merged diff touched four files:</p><h3>packages/vinext/src/shims/navigation.ts</h3><ul><li>Removed getServerInsertedHTMLContext() (dead code)</li><li>Removed the IIFE context creation</li><li>Added a single ServerInsertedHTMLContext export with correct typing and RSC guard</li></ul><h3>app-dev-server.ts (SSR pipeline)</h3><ul><li>Wrapped the rendered tree with &lt;ServerInsertedHTMLContext.Provider value={addCallback}&gt;</li><li>Plumbed the Provider value through to the existing callback collection mechanism</li></ul><h3>tests/apollo-client-integration.test.ts</h3><ul><li>Removed structural checks on React internals ($$typeof, _currentValue)</li><li>Added 5 behavioral tests using renderToString that verify real integration patterns</li></ul><h3>Final test results</h3><pre>npm test -- apollo-client-integration.test.ts server-inserted-html.test.ts<br>Tests: 16 passed (5 new + 11 existing)<br>Lint:  0 warnings, 0 errors<br>TypeScript: 0 new errors</pre><p>All 14 CI checks passed. southpolesteve dismissed the stale review and merged.</p><h3>8. What I took away</h3><p><strong>01 — Exporting a context is not the same as wiring it.</strong><br> A React Context is only useful when a Provider supplies a value somewhere above the consuming component in the tree. Exporting a createContext(null) and calling it done is a false fix — it makes the import error go away while the actual runtime behavior remains broken.</p><p><strong>02 — Read the library’s source before writing the shim.</strong><br> Apollo doesn’t call useServerInsertedHTML(). It calls useContext(ServerInsertedHTMLContext) directly. I would have known this immediately if I&#39;d read @apollo/client-integration-nextjs/src/ApolloNextAppProvider.tsx before writing the fix. Understanding the consumer shapes the implementation.</p><p><strong>03 — Tests must verify behavior, not structure.</strong><br> Checking $$typeof and _currentValue tells you nothing useful. Rendering a component and checking what useContext returns tells you whether the integration actually works. Write tests that would fail if your implementation were wrong.</p><p><strong>04 — Type the context value correctly.</strong><br> React.createContext&lt;any&gt;(null) is a smell. If you know the context value is (cb: () =&gt; React.ReactNode) =&gt; void, type it that way. The type communicates the contract and catches misuse at compile time.</p><p><strong>05 — Dead code in a first draft is fine. Ship it in a PR and it becomes a maintenance problem.</strong><br> getServerInsertedHTMLContext() was clearly left over from an earlier design iteration. It compiled fine and caused no errors — but it added confusion, misled reviewers, and had to be removed. Clean up before opening the PR.</p><h3>9. TL;DR</h3><p>@apollo/client-integration-nextjs calls useContext(ServerInsertedHTMLContext) to get a callback registration function. vinext&#39;s next/navigation shim was missing this export, so the import returned undefined and Apollo threw immediately. The fix required three steps: export a single shared context, wrap the SSR render tree with a Provider that supplies the real callback registration function, and write tests that verify the actual Apollo integration pattern using renderToString. PR #151 delivers all three.</p><p>The full PR is at <a href="https://github.com/cloudflare/vinext/pull/151">cloudflare/vinext#151</a>. If your CSS-in-JS library (styled-components, Emotion, StyleX) uses the same pattern, it should also benefit from this fix.</p><p><em>Written by </em><a href="https://github.com/yunus25jmi1"><em>yunus25jmi1</em></a><em> · Merged into </em><a href="https://github.com/cloudflare/vinext"><em>cloudflare/vinext</em></a><em> · March 2026</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2798bc922c0d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-fixed-apollo-client-ssr-in-cloudflares-vinext-by-wiring-a-missing-react-context-2798bc922c0d">How I Fixed Apollo Client SSR in Cloudflare’s vinext by Wiring a Missing React Context</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Lightweight, Scalable Database Stack with Oracle Container Engine]]></title>
            <link>https://yunus25jmi.medium.com/building-a-lightweight-scalable-database-stack-with-oracle-container-engine-bc7adbb8e521?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc7adbb8e521</guid>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 15:35:02 GMT</pubDate>
            <atom:updated>2026-03-22T15:35:02.116Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Oracle Cloud Infrastructure · OKE · Kubernetes</em></strong><em> </em>Topics: Cloud Infrastructure · Kubernetes · Stateful Workloads · Database Engineering</blockquote><h3>Introduction: Containers Changed the Database Story</h3><p>For years, databases lived outside the container world — monolithic, VM-bound, hand-tuned. Operators feared the idea of putting something as critical as a Postgres cluster or an Oracle DB instance inside a container, convinced that persistence and portability couldn’t coexist. That era is over.</p><p><strong>Oracle Container Engine for Kubernetes (OKE)</strong> is Oracle’s fully managed Kubernetes service, deeply integrated with Oracle Cloud Infrastructure (OCI). It brings together the flexibility of containers, the muscle of OCI bare metal shapes, and the observability of native Oracle tooling — making it possible to run both lightweight microservice databases and heavyweight OLAP workloads on the same platform, with a unified control plane.</p><p>This guide walks you through architecting a database stack on OKE that is simultaneously:</p><ul><li><strong>Lightweight</strong> in resource footprint</li><li><strong>Horizontally scalable</strong> via pod replication</li><li><strong>Vertically scalable</strong> via node shape upgrades</li><li><strong>Togglable</strong> between stateful and stateless configurations based on workload requirements</li></ul><h3>Oracle Container Engine for Kubernetes: Platform Overview</h3><p>OKE is a certified, CNCF-conformant Kubernetes service that abstracts away control plane management while giving you full access to the data plane. Unlike many managed Kubernetes offerings, OKE’s master nodes are hosted and maintained by Oracle at zero cost — you only pay for the worker nodes and OCI resources consumed by your workloads.</p><p>Capability Description <strong>Managed Control Plane</strong> Oracle operates the API server, etcd, and scheduler. Zero control-plane cost, with automatic version upgrades. <strong>Virtual &amp; Bare Metal Nodes</strong> Choose VM shapes for cost efficiency or bare metal shapes for IOPS-intensive databases. Mix in the same cluster. <strong>OCI Block &amp; File Storage</strong> Persistent Volumes backed by NVMe block volumes or NFS file storage — essential for stateful database pods. <strong>OCI IAM Integration</strong> Kubernetes RBAC maps directly to OCI Identity policies. Fine-grained secrets management via OCI Vault. <strong>Virtual Node Pools</strong> Serverless pods with no worker-node management — ideal for bursty query microservices and connection proxies. <strong>Native Observability</strong> OCI Monitoring, Logging, and Application Performance Monitoring integrate out-of-the-box without sidecars.</p><h3>The Layered Database Stack: Architecture</h3><p>A production-grade database stack on OKE is organised across three planes:</p><pre>┌─────────────────────────────────────────────────────────────────────┐<br>│  OCI INFRASTRUCTURE LAYER                                           │<br>│  ┌──────────────┐  ┌──────────────┐  ┌─────────────┐  ┌─────────┐ │<br>│  │ VCN/Subnets  │  │OCI Block Vol.│  │  OCI Vault  │  │   LB    │ │<br>│  │Private+Public│  │ NVMe · iSCSI │  │Secrets · KMS│  │OCI LB   │ │<br>│  └──────────────┘  └──────────────┘  └─────────────┘  └─────────┘ │<br>└─────────────────────────────────────────────────────────────────────┘<br>         │                    │                   │<br>┌─────────────────────────────────────────────────────────────────────┐<br>│  ORACLE CONTAINER ENGINE (OKE) LAYER                                │<br>│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌────────┐ │<br>│  │Control Plane │  │  Node Pools  │  │Storage Classes│  │Operators│ │<br>│  │ API Server   │  │ Std·HPC·GPU  │  │ oci-bv (Block)│  │PG Op.  │ │<br>│  │etcd·Scheduler│  │VM+Bare Metal │  │ oci-fss (File)│  │MySQL Op│ │<br>│  │Oracle-managed│  │ClusterAutosc.│  │Dynamic Provis.│  │Cust.CRD│ │<br>│  └──────────────┘  └──────────────┘  └──────────────┘  └────────┘ │<br>└─────────────────────────────────────────────────────────────────────┘<br>         │                    │                   │<br>┌─────────────────────────────────────────────────────────────────────┐<br>│  DATABASE APPLICATION LAYER                                         │<br>│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌────────┐ │<br>│  │Stateless Pods│  │Primary DB Pod│  │Replica DB Pods│  │Ephemeral│ │<br>│  │Query Svcs    │  │StatefulSet   │  │Read Replicas×N│  │Redis   │ │<br>│  │Conn. Pools   │  │NVMe Block Vol│  │Streaming Repl │  │Memcached│ │<br>│  │HPA Autoscale │  │Vertical Scale│  │Horizontal Scale│ │emptyDir│ │<br>│  └──────────────┘  └──────────────┘  └──────────────┘  └────────┘ │<br>└─────────────────────────────────────────────────────────────────────┘</pre><h3>Stateless vs. Stateful: Choosing the Right Posture</h3><p>Not every database component in your stack needs to be stateful. A well-designed stack separates the <strong>write path (stateful)</strong> from the <strong>read and routing path (stateless)</strong>, enabling each to scale independently. OKE supports both natively through its Kubernetes primitives.</p><h3>Stateless Workloads</h3><p>Deploy as <strong>Deployments</strong> with HPA. No PersistentVolumeClaim needed.</p><ul><li>Connection poolers (pgBouncer, ProxySQL)</li><li>Query routing microservices</li><li>Schema migration runners</li><li>Read-cache invalidation workers</li><li>DB health-check sidecars</li></ul><h3>Stateful Workloads</h3><p>Deploy as <strong>StatefulSets</strong> with PVCs. Each pod gets its own OCI Block Volume mount and a stable network identity via a headless service.</p><ul><li>Primary DB pods (Postgres, MySQL)</li><li>Read replicas with streaming WAL</li><li>Time-series databases (TimescaleDB)</li><li>Message queues with disk-backed state</li></ul><blockquote><strong><em>Key Principle:</em></strong><em> Use a </em><strong><em>Kubernetes Operator</em></strong><em> for your stateful databases. Operators encode the operational knowledge of your database (failover, backup, scaling, version upgrades) as Kubernetes Custom Resource Definitions (CRDs), eliminating manual runbook procedures and enabling GitOps-driven lifecycle management.</em></blockquote><h3>Scaling Vertically and Horizontally</h3><p>OKE provides two independent scaling axes. Neither is better — they solve different bottlenecks and are most effective when combined in a tiered strategy based on your workload’s I/O vs. concurrency profile.</p><h3>Vertical Scaling — Grow the Node</h3><p>OCI’s node shapes span from standard instances to high-memory ARM shapes and bare metal NVMe nodes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/167005dadf430d398f973b303dcbc317/href">https://medium.com/media/167005dadf430d398f973b303dcbc317/href</a></iframe><p>To vertically scale a stateful pod, resize the node pool shape. The Kubernetes resources.requests and limits on the pod are respected automatically at reschedule.</p><h3>Horizontal Scaling — Multiply the Pods</h3><p>Horizontal scaling follows two distinct patterns:</p><p><strong>Stateless pods</strong> — the <strong>Horizontal Pod Autoscaler (HPA)</strong> monitors CPU and custom metrics (e.g., active DB connections) and scales replicas up and down automatically.</p><p><strong>Stateful replicas</strong> — the <strong>StatefulSet</strong> controller combined with a database operator manages replica addition, WAL streaming catch-up, and topology-aware placement across OCI Availability Domains.</p><h3>Deploying the Stack: Key Manifests</h3><h3>1. StorageClass — OCI Block Volume (NVMe)</h3><pre># StorageClass backed by OCI Block Volume (NVMe)<br>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: oci-nvme-bv<br>provisioner: blockvolume.csi.oraclecloud.com<br>parameters:<br>  vpusPerGB: &quot;30&quot;           # High performance tier<br>  attachment-type: &quot;paravirtualized&quot;<br>reclaimPolicy: Retain<br>allowVolumeExpansion: true</pre><h3>2. StatefulSet — PostgreSQL Primary + Read Replicas</h3><pre>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: postgres-primary<br>  namespace: databases<br>spec:<br>  serviceName: &quot;postgres-headless&quot;<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: postgres<br>  template:<br>    spec:<br>      affinity:<br>        podAntiAffinity:          # Spread across Availability Domains<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>          - topologyKey: &quot;oci.oraclecloud.com/fault-domain&quot;<br>      containers:<br>      - name: postgres<br>        image: postgres:16-alpine<br>        resources:<br>          requests:<br>            cpu: &quot;2&quot;<br>            memory: &quot;8Gi&quot;<br>          limits:<br>            cpu: &quot;8&quot;<br>            memory: &quot;32Gi&quot;<br>  volumeClaimTemplates:<br>  - metadata:<br>      name: pgdata<br>    spec:<br>      storageClassName: oci-nvme-bv<br>      accessModes: [&quot;ReadWriteOnce&quot;]<br>      resources:<br>        requests:<br>          storage: 500Gi</pre><h3>3. Deployment + HPA — Stateless Connection Pooler (pgBouncer)</h3><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: pgbouncer<br>spec:<br>  replicas: 2<br>  template:<br>    spec:<br>      containers:<br>      - name: pgbouncer<br>        image: edoburu/pgbouncer:latest<br>        resources:<br>          requests: { cpu: &quot;100m&quot;, memory: &quot;128Mi&quot; }<br>---<br>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: pgbouncer-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: pgbouncer<br>  minReplicas: 2<br>  maxReplicas: 20<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      target: { type: Utilization, averageUtilization: 60 }</pre><h3>End-to-End Implementation Walkthrough</h3><h3>Step 1 — Provision the OKE Cluster</h3><p>Create a cluster via OCI Console, CLI, or Terraform. Choose a VCN with private worker node subnets and a public API endpoint, or fully private for hardened environments. Enable the Cluster Autoscaler add-on from the marketplace.</p><h3>Step 2 — Design Node Pools by Workload Class</h3><p>Create a minimum of two node pools: a <strong>general-purpose pool</strong> (E4.Flex shapes) for stateless workloads and an <strong>IO-optimized pool</strong> (DenseIO or bare metal) for stateful database pods. Apply taints and tolerations to enforce workload placement.</p><pre># Taint for IO-optimized node pool<br>taints:<br>  - key: &quot;workload-class&quot;<br>    value: &quot;database&quot;<br>    effect: &quot;NoSchedule&quot;</pre><pre># Toleration on database pods<br>tolerations:<br>  - key: &quot;workload-class&quot;<br>    operator: &quot;Equal&quot;<br>    value: &quot;database&quot;<br>    effect: &quot;NoSchedule&quot;</pre><h3>Step 3 — Install the OCI CSI Block Volume Driver</h3><p>OKE clusters deploy the OCI CSI driver by default. Define a StorageClass specifying vpusPerGB: &quot;30&quot; for high-performance NVMe volumes. Set reclaimPolicy: Retain so data survives pod deletion.</p><h3>Step 4 — Deploy the Database Operator</h3><p>Install the <strong>CloudNativePG</strong> operator (for PostgreSQL) or the <strong>MySQL Operator for Kubernetes</strong> via Helm. These operators introduce Cluster and MySQLCluster CRDs that manage StatefulSets, services, backups, and failover declaratively.</p><pre># Install CloudNativePG operator<br>helm repo add cnpg https://cloudnative-pg.github.io/charts<br>helm upgrade --install cnpg \<br>  --namespace cnpg-system \<br>  --create-namespace \<br>  cnpg/cloudnative-pg</pre><h3>Step 5 — Configure Secrets with OCI Vault</h3><p>Store database credentials in OCI Vault. Use the <strong>External Secrets Operator</strong> to sync OCI Vault secrets into Kubernetes Secret objects — avoiding any credentials committed to GitOps repositories.</p><pre>apiVersion: external-secrets.io/v1beta1<br>kind: ExternalSecret<br>metadata:<br>  name: postgres-credentials<br>spec:<br>  secretStoreRef:<br>    name: oci-vault-store<br>    kind: ClusterSecretStore<br>  target:<br>    name: postgres-credentials<br>  data:<br>  - secretKey: password<br>    remoteRef:<br>      key: &quot;ocid1.vaultsecret.oc1...&quot;</pre><h3>Step 6 — Deploy Stateless Connection Pool Layer</h3><p>Deploy pgBouncer or ProxySQL as a Kubernetes Deployment with an HPA. Configure the connection pooler to target the primary database&#39;s headless service for writes and the replica service for reads via read/write splitting rules.</p><h3>Step 7 — Configure the Cluster Autoscaler</h3><p>Set min/max node counts per pool. For stateful pools, prefer a minimum of 3 replicas across fault domains. For stateless pools, allow scale-to-zero to minimise cost during off-peak hours. Use scale-down-delay-after-add to prevent thrashing.</p><h3>Step 8 — Instrument with OCI Observability</h3><p>Enable OCI Container Engine monitoring. Export Prometheus metrics from the DB pods to OCI Monitoring using the Prometheus Remote Write endpoint. Set alarms on WAL lag, connection saturation, and disk utilisation thresholds.</p><h3>Database Workloads on OKE: Deployment Patterns</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92c588ba9bcf9e8614b5965ce3a3cd0a/href">https://medium.com/media/92c588ba9bcf9e8614b5965ce3a3cd0a/href</a></iframe><h3>Production Hardening Checklist</h3><h3>Anti-affinity Rules</h3><p>Always spread StatefulSet pods across OCI Fault Domains and Availability Domains using podAntiAffinity with topologyKey. This ensures a hardware failure never takes down your entire database cluster.</p><h3>PodDisruptionBudgets</h3><p>Set minAvailable: 2 for database StatefulSets to ensure quorum is never broken during node drains or cluster upgrades.</p><pre>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: postgres-pdb<br>spec:<br>  minAvailable: 2<br>  selector:<br>    matchLabels:<br>      app: postgres</pre><h3>Volume Snapshots</h3><p>Use OCI Volume Snapshot-backed VolumeSnapshotContent objects for point-in-time backup. Schedule via operator backup CRDs rather than external cron jobs, so backups are part of the database lifecycle definition.</p><h3>Resource Quotas</h3><p>Apply ResourceQuota per namespace to prevent noisy-neighbour situations between databases sharing the same cluster. Set limits on PVC storage as well as CPU and memory.</p><h3>Network Policies</h3><p>Enforce NetworkPolicy to restrict pod-to-pod traffic. Database pods should only accept connections from their designated connection pool tier — not from arbitrary workloads in the cluster.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: postgres-ingress<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: postgres<br>  ingress:<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          role: connection-pooler<br>    ports:<br>    - port: 5432</pre><h3>Graceful Termination</h3><p>Set terminationGracePeriodSeconds: 60 on database pods and configure preStop hooks to flush WAL and close connections cleanly before the SIGTERM is delivered.</p><h3>Conclusion: The Case for OKE-native Databases</h3><p>Running databases on Oracle Container Engine is no longer a bold experiment — it is a production pattern used by enterprises running billions of transactions. The combination of OCI’s purpose-built storage infrastructure, OKE’s first-class StatefulSet support, and the maturity of Kubernetes database operators means you can now achieve the same (or better) operational characteristics as traditional VM-based database deployments, with dramatically faster provisioning, GitOps-driven configuration, and elastic cost profiles.</p><p>The key architectural insight is the <strong>layered separation</strong>: stateless connection poolers scale horizontally and cheaply, while stateful primary pods scale vertically on premium storage shapes. Read replicas scale horizontally to absorb read traffic. Each layer is independently observable, independently upgradeable, and independently scalable — which is the fundamental promise of container-native infrastructure, finally delivered for database workloads.</p><p>Whether you are migrating a monolithic Oracle DB to a cloud-native Postgres deployment or building a greenfield microservices data layer from scratch, OKE provides the primitives you need — and Oracle provides the infrastructure muscle to run it at scale without compromise.</p><p><em>References:</em></p><ul><li><a href="https://docs.oracle.com/en-us/iaas/Content/ContEng/home.htm">Oracle Container Engine for Kubernetes (OKE) Documentation</a></li><li><a href="https://cloudnative-pg.io/">CloudNativePG — PostgreSQL Operator for Kubernetes</a></li><li><a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">Kubernetes StatefulSets</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/ContEng/Tasks/contengcreatingpersistentvolumeclaim.htm">OCI Block Volume CSI Driver</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc7adbb8e521" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed ESM Resolution in Cloudflare’s vinext]]></title>
            <link>https://yunus25jmi.medium.com/how-i-fixed-esm-resolution-in-cloudflares-vinext-f2e127ef57b9?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e127ef57b9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[cloudflare]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 03:28:15 GMT</pubDate>
            <atom:updated>2026-03-16T03:28:49.649Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Tags:</strong> Open Source · Vite · ESM · Cloudflare<br><strong>Author:</strong> Md Yunus · March 2026 · 8 min read · Merged in <a href="https://github.com/cloudflare/vinext/pull/193">PR #193</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*c3BjHdaCciOk28fDaQfULw.png" /></figure><p>A deep dive into why validator throws &quot;Cannot find module&quot; in dev server, how vinext&#39;s noExternal: true already solves it—and what it taught me about contributing to a production framework.</p><h3>Table of Contents</h3><ol><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#1-the-bug-that-started-it-all">The bug that started it all</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#2-why-this-happens--the-root-cause">Why this happens — the root cause</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#3-the-fix-vinext-already-had-it">The fix: vinext already had it</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#4-the-pr-journey-three-rounds-of-review">The PR journey: three rounds of review</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#5-what-ask-bonk-actually-caught">What ask-bonk actually caught</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#6-what-actually-landed">What actually landed</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#7-what-i-took-away">What I took away</a></li><li><a href="https://claude.ai/chat/0e1a5e83-4809-401a-896b-ec3f40b30331#8-tldr">TL;DR</a></li></ol><h3>1. The bug that started it all</h3><p>A user filed <a href="https://github.com/cloudflare/vinext/issues/189">issue #189</a> against vinext—Cloudflare&#39;s Next.js-on-Workers adapter — with a deceptively simple complaint: importing the validator package broke the dev server with a cryptic module resolution error.</p><pre>⚠ Error — Dev Server<br>Cannot find module &#39;...\validator\es\lib\util\assertString&#39;<br>imported from &#39;...\validator\es\lib\isEmail.js&#39;</pre><p>The error looks strange at first. assertString <em>exists</em> — it&#39;s a real file inside the package. So why can&#39;t Node find it? The answer lies in the intersection of two things: how ESM works in Node.js and what Vite does (or doesn&#39;t do) during SSR.</p><h3>2. Why this happens — the root cause</h3><h3>Node’s strict ESM resolution</h3><p>When Node.js loads an ES module natively, it enforces strict file extension requirements. An import like import &#39;./util/assertString&#39; with <strong>no file extension</strong> will fail — Node won&#39;t guess .js for you. This rule is strict-by-spec in ESM, unlike CommonJS where extension-less requires were fine.</p><h3>Vite’s default SSR behavior</h3><p>By default, Vite <strong>externalizes</strong> dependencies during SSR — meaning it loads them via Node.js directly rather than bundling them through its own transform pipeline. For most packages that ship well-formed ESM with proper extensions, this is fine and fast. But for packages like validator that use extensionless internal imports in their /es/ distribution, this is fatal.</p><blockquote><strong><em>How Vite SSR works:</em></strong><em><br> Vite processes two pipelines: the browser bundle (always transformed) and the SSR bundle. In SSR, Vite defaults to </em><strong><em>externalizing</em></strong><em> node_modules — skipping its own resolver and delegating to Node’s native loader. The flag </em><em>ssr.noExternal: true reverses this, forcing all deps through Vite&#39;s resolver instead.</em></blockquote><p>The result is that validator gets handed to Node, Node tries to follow its internal ESM imports, and Node chokes on the missing .js extension. The module never loads.</p><h3>3. The fix: vinext already had it</h3><p>Here’s the interesting twist: <strong>vinext already fixed this</strong>. Digging into the source, I found that vinext sets noExternal: true in both of its server environments — SSR <em>and</em> RSC (React Server Components).</p><pre>// packages/vinext/src/index.ts<br>// Skip when targeting bundled runtimes (Cloudflare/Nitro bundle everything).<br>// This also resolves extensionless-import issues in packages like<br>// `validator` (see #189) by routing them through Vite&#39;s resolver.<br>if (isBundledTarget(target)) {<br>  ssrOptions.noExternal = true;<br>}<br>// For App Router, propagate noExternal to BOTH rsc and ssr<br>// environments (the top-level ssr.noExternal only affects the<br>// default ssr env, not the rsc env).<br>config.environments.rsc.resolve.noExternal = true;<br>config.environments.ssr.resolve.noExternal = true;</pre><p>When noExternal: true it&#39;s set, Vite stops handing packages to Node and instead routes every import through its own transform pipeline — which is much more lenient about file extensions and handles extensionless imports correctly. validator works out of the box, with zero user configuration.</p><p>The real problem wasn’t a missing feature. It was missing documentation. Users were either unaware this setting existed, or didn’t know vinext applied it for them.</p><blockquote>The fix was already shipped. My job was to explain why it worked — and to prove it with a test so it could never silently regress.</blockquote><h3>4. The PR journey: three rounds of review</h3><p>Getting this merged wasn’t instant. The project uses an AI code reviewer ask-bonk that caught several real issues in my initial submission. Here&#39;s what the feedback loop looked like:</p><h3>Round 1 — Changes requested</h3><p>First submission bundled too much:</p><ul><li>A package-lock.json from npm (wrong package manager — this is a pnpm monorepo)</li><li>An unrelated Space_Grotesk font export for a completely different issue (#190)</li><li>A speculative list of “problematic ESM packages” that included cuid and nanoid despite having no verified reproduction</li><li>A wrong GitHub URL in a comment (nicepkg/vinextinstead of cloudflare/vinext)</li></ul><h3>Round 2 — Cleaner, minor notes</h3><p>After stripping the unrelated changes and the speculative package list, the review came back mostly clean. Minor notes:</p><ul><li>Wrong port number in the test fixture (5011 instead of continuing the project&#39;s 4400–4404 sequence)</li><li>An accidental trailing newline in an unrelated test file</li><li>Slightly misleading comment phrasing that suggested new per-package behavior rather than documenting existing behavior</li></ul><h3>Round 3 — Approved ✓</h3><p>After fixing the port number, dropping the stray diff, and cleaning up the comments, the reviewer approved. The one remaining nit — Windows-style backslash paths in the troubleshooting docs—was noted but non-blocking.</p><h3>Merged ✓</h3><p>PR #193 was merged by james-elicx into cloudflare:main after all 16 CI checks passed. Closes issue #189.</p><h3>5. What ask-bonk actually caught</h3><p>The AI reviewer flagged things I genuinely would have missed. Here are two that stood out:</p><h3>The speculative package problem</h3><p>In my first draft I’d added a KNOWN_PROBLEMATIC_ESM_PACKAGES list with validator, uuid, date-fns, cuid, and nanoid. The reviewer&#39;s response was precise:</p><blockquote><strong><em>ask-bonk[bot] — Changes requested:</em></strong><em>cuid and </em><em>nanoid do not have the ESM resolution issue described. Both ship clean ESM with proper exports maps. Adding packages speculatively forces Vite to bundle them through its transform pipeline unnecessarily, which:</em></blockquote><ul><li>Increases dev server startup time</li><li>Can break packages that rely on being externalized</li><li>Erodes trust in the list (users will question every entry)</li></ul><blockquote><strong><em>Recommendation:</em></strong><em> Only include packages with verified reproduction cases.</em></blockquote><p>This is exactly right. A speculative allowlist is worse than no list—it trains users to cargo-cult copy entries without understanding why they’re there. I removed everything without a verified issue.</p><h3>The wrong package manager</h3><p>I’d committed a package-lock.json (npm) into a pnpm monorepo. Easy mistake when your local machine defaults to npm.</p><pre>- package-lock.json   ← npm lockfile, wrong package manager<br>  pnpm-lock.yaml      ← this is what belongs here</pre><h3>6. What actually landed</h3><p>The final diff was intentionally minimal—three focused changes:</p><h3>1. Explanatory comments in index.ts</h3><p>Two lines of comments in the core plugin file connect the noExternal: true setting to the issue it resolves so future contributors don&#39;t wonder why it&#39;s there.</p><h3>2. Troubleshooting documentation</h3><p>A new section in .agents/skills/migrate-to-vinext/references/troubleshooting.md:</p><pre>### &quot;Cannot find module&quot; for ESM packages in dev server<br>**Symptom:** Importing certain ESM packages (e.g. `validator`) fails<br>with a module resolution error in the dev server.<br>**Cause:** Some packages use extensionless internal imports that Node&#39;s<br>strict ESM loader can&#39;t resolve when the package is externalized.<br>**vinext fix:** vinext sets `noExternal: true` in all server environments,<br>routing all dependencies through Vite&#39;s resolver.<br>No configuration needed — this is the default behavior.<br>**Example error:**<br>Cannot find module &#39;…/validator/es/lib/util/assertString&#39; imported from &#39;…/validator/es/lib/isEmail.js&#39;</pre><h3>3. Ecosystem test fixture</h3><p>A new test fixture tests/fixtures/ecosystem/validator/ with a corresponding test case:</p><pre>// tests/ecosystem.test.ts<br>describe(&quot;validator ecosystem&quot;, () =&gt; {<br>  let fetchPage: (pathname: string) =&gt; Promise&lt;{ html: string; status: number }&gt;;<br>  beforeAll(async () =&gt; {<br>    const fixture = await startFixture(&quot;validator&quot;, 4405); // continues 4400–4404 sequence<br>    fetchPage = fixture.fetchPage;<br>  });<br>  it(&quot;imports validator in SSR without configuration&quot;, async () =&gt; {<br>    const { html, status } = await fetchPage(&quot;/&quot;);<br>    expect(status).toBe(200);<br>    expect(html).toContain(&quot;validator works&quot;);<br>  });<br>});</pre><p>This test runs in CI and will catch any future regression. Any change that breaks validator SSR imports will fail before it ships.</p><h3>7. What I took away</h3><p><strong>01 — Documentation is a real fix.</strong><br>The code was correct for months. Users were still hitting the bug. A well-placed comment or troubleshooting entry reaches people the PR diff never will.</p><p><strong>02 — Keep PRs to one thing.</strong><br>My first submission tried to fix #189 and #190 at the same time, plus add a speculative package list. The reviewer flagged all of it. Tight, focused PRs merge faster and teach you more per round of feedback.</p><p><strong>03 — Tests are the real guarantee.</strong><br>Comments and docs can be ignored. A failing CI test cannot. The ecosystem fixture means this behavior is now locked—any change that breaks validator SSR imports will show up before it ships.</p><p><strong>04 — Don’t speculate in allowlists.</strong><br>Every entry in a list like KNOWN_PROBLEMATIC_ESM_PACKAGES should have a linked issue or reproduction. Speculative entries impose real costs (startup time, broken packages) and dilute the list&#39;s signal.</p><p><strong>05 — AI reviewers catch the dumb stuff.</strong><br>The wrong package manager, the wrong GitHub URL, the wrong port — ask-bonk caught all of them. Automated review rounds are worth it just for the mechanical mistakes.</p><h3>8. TL;DR</h3><p>If you’re using vinext and a package like validator throws a &quot;Cannot find module&quot; error in dev, you don&#39;t need to add anything to your config. Vinext&#39;s noExternal: true setting already routes all deps through Vite&#39;s resolver, which handles extensionless ESM imports correctly. PR #193 documents this behavior, adds a troubleshooting note, and locks it with a CI test.</p><p>The full PR is at <a href="https://github.com/cloudflare/vinext/pull/193">cloudflare/vinext#193</a>. If this helped you, consider starring the repo or opening an issue if you find another package that exhibits the same pattern.</p><p><em>Written by </em><a href="https://github.com/yunus25jmi1"><em>yunus25jmi1</em></a><em> · Merged into </em><a href="https://github.com/cloudflare/vinext"><em>cloudflare/vinext</em></a><em> · March 2026</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e127ef57b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to NOT Use Kafka on OCI: A Cost and Complexity Analysis for Event Streaming Architecture]]></title>
            <link>https://levelup.gitconnected.com/when-to-not-use-kafka-on-oci-a-cost-and-complexity-analysis-for-event-streaming-architecture-c289b63825f7?source=rss-3abf238f1bcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c289b63825f7</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[oracle-cloud]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Md Yunus ]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 16:19:56 GMT</pubDate>
            <atom:updated>2026-03-02T16:19:56.371Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Md Yunus, CTO &amp; Head of Engineering — CloudRelic</em></p><p>Every few months, a post about “LinkedIn evolving beyond Kafka” or “how big tech handles terabytes per second” rises to the top of engineering feeds, and the same questions resurface in architecture review meetings: <em>Should we use Kafka? Is our current setup overkill? Are we paying too much?</em></p><p>These are the right questions. But they are usually answered wrong — with arguments about features rather than constraints. The reality is that LinkedIn isn’t discarding Kafka — they’re evolving its architecture (Kora, tiered storage, protocol proxies). Most major firms are doing the same. The real question isn’t which streaming technology has the most capabilities. It’s which one matches your throughput tier, your operational budget, and your team’s capacity to manage it.</p><p>For cloud architects building on Oracle Cloud Infrastructure, this translates into a concrete three-way decision: <strong>OCI Queue</strong>, <strong>OCI Streaming</strong>, or <strong>self-managed Apache Kafka on OCI Compute</strong>.</p><p>Before we discuss specific services or configuration, we need to understand the system problem that makes this decision consequential.</p><h3>The System Problem: Backpressure and Cascading Failure</h3><p>Event streaming architectures exist to decouple producers from consumers. A user clicks “Place Order,” an event is emitted, and downstream services — inventory, payment, shipping — process it asynchronously. The architecture looks elegant on a whiteboard.</p><p><strong>Consider this scenario:</strong> It’s 3 AM. A payment service deployment goes sideways. The payment consumer stops processing events. The event buffer fills up. Producers start blocking or dropping messages. The inventory service, which shares a database connection pool with another consumer, begins timing out. Within minutes, a single slow consumer has cascaded into a system-wide outage. Your on-call engineer is staring at a dashboard full of red — and the root cause is buried under three layers of backpressure.</p><p>This is the backpressure problem. When downstream consumers cannot keep pace with upstream producers, pressure builds in the system. The streaming layer is the pressure vessel. If it’s undersized, it ruptures. If it’s oversized, you’re paying for capacity you’ll never use. If it’s the wrong type entirely, no amount of tuning will save you.</p><p>The architecture decision — Queue vs. Streaming vs. self-managed Kafka — is fundamentally a decision about <strong>how you want to handle backpressure</strong>, and what trade-offs you’re willing to accept.</p><h3>Constraints: Why This Decision Is Harder Than It Looks</h3><p>Selecting an event streaming primitive on OCI involves navigating constraints that interact in non-obvious ways.</p><h3>Throughput Ceilings Are Not Soft Limits</h3><p>OCI Queue enforces a hard ceiling of <strong>10 MB/s ingress and 10 MB/s egress per queue</strong>, with a maximum of <strong>1,000 API requests per second per queue</strong>. OCI Streaming limits each partition to <strong>1 MB/s writes</strong> and <strong>5 GET requests per second per consumer group per partition</strong>. These are not guidelines — they are service limits that will reject your requests when exceeded.</p><p>This means your throughput tier isn’t a preference; it’s a boundary condition. Exceed it, and your producers start receiving errors. Your architecture must be designed below these ceilings with headroom for spikes.</p><h3>Operational Complexity Has a Real Cost</h3><p>A self-managed Kafka cluster on OCI Compute requires a minimum of three broker nodes and three Zookeeper (or KRaft controller) nodes. Each needs OS patching, JVM tuning, disk monitoring, partition rebalancing, and security updates. The operational overhead for a production Kafka cluster is typically estimated at 0.5–2 FTE of senior engineering time. That’s not infrastructure cost — it’s opportunity cost. Every hour spent debugging a Kafka ISR (In-Sync Replica) shrink is an hour not spent building product features.</p><p>OCI Queue and OCI Streaming are fully managed. Zero infrastructure, zero patching, zero rebalancing. The trade-off is reduced control over tuning parameters and hard service limits that you cannot override.</p><h3>Feature Gaps Are Permanent (Until They’re Not)</h3><p>OCI Streaming is Kafka-compatible — but not Kafka-equivalent. It supports the Producer, Consumer, Connect, Admin, and Group Management APIs. It does <strong>not</strong> support:</p><ul><li><strong>Kafka Streams</strong> (stream processing library)</li><li><strong>Log Compaction</strong> (retaining latest value per key)</li><li><strong>Transactions</strong> (broker-level exactly-once semantics across topics; consumer-side idempotency is still achievable)</li><li><strong>Idempotent Production</strong> (broker-level deduplication)</li><li><strong>Dynamic Partition Addition</strong> (partitions are fixed at stream creation)</li></ul><p>If your architecture requires any of these, OCI Streaming is disqualified regardless of throughput. This is not a limitation that can be worked around — it’s a feature boundary.</p><h3>Retention Is a Hard Wall</h3><p>OCI Streaming enforces a <strong>maximum 7-day retention period</strong>, configured at stream creation and — as of current documentation — <strong>not mutable after creation</strong>. OCI Queue allows retention from <strong>10 seconds to 7 days</strong>. Self-managed Kafka supports configurable, infrastructure-bound retention (limited only by disk capacity and cost, with tiered storage to object storage for cold data).</p><p>If your compliance requirements mandate 30-day event retention for audit, or your event sourcing architecture depends on replaying the full event history, self-managed Kafka is the only option on OCI.</p><h3>The Three Primitives: A Systems-Level Comparison</h3><p>Rather than listing features, let’s examine how each service handles the fundamental operations of an event streaming system.</p><h3>OCI Queue: The Task Buffer</h3><p><strong>Documentation:</strong> <a href="https://docs.oracle.com/en-us/iaas/Content/queue/overview.htm">OCI Queue Overview</a></p><p>OCI Queue is a fully managed serverless message queue designed for decoupled, asynchronous messaging. As of February 2026, OCI Queue supports <strong>multiple consumer groups</strong> (up to 10 per queue) with attribute-based filtering, enabling fan-out delivery patterns that were previously exclusive to streaming architectures.</p><p><strong>How it handles backpressure:</strong> Messages accumulate in the queue (up to 2 GB per queue, unlimited message count). Consumers pull at their own pace. If a consumer fails, the message becomes visible again after the visibility timeout (1 second to 12 hours, configurable). After exceeding the maximum delivery attempts (1–20, configurable), the message moves to a <a href="https://docs.oracle.com/en-us/iaas/Content/queue/deadletterqueues.htm">Dead Letter Queue</a> (DLQ) for isolation and analysis. Multiple consumer groups can process the same messages independently, each maintaining its own delivery tracking.</p><p><strong>Key characteristics:</strong></p><ul><li><strong>Delivery model:</strong> Pull-based, with fan-out via consumer groups (up to 10 per queue). Each group receives its own copy of messages, with optional attribute-based filtering.</li><li><strong>Message size:</strong> Up to 256 KB</li><li><strong>Ordering:</strong> No strict ordering guarantees across multiple consumers (within a single consumer and visibility window, behavior can appear ordered)</li><li><strong>Replay:</strong> Not available — messages are deleted after successful consumption by all consumer groups</li><li><strong>Protocol:</strong> REST API (OpenAPI) + <a href="https://docs.oracle.com/en-us/iaas/Content/queue/messages-stomp.htm">STOMP</a></li><li><strong>Channels:</strong> Up to 256 ephemeral channels per queue for logical message routing</li></ul><p><strong>When to use OCI Queue:</strong></p><ul><li>Background job processing (image resizing, email sending, report generation)</li><li>Order/task dispatch to worker pools</li><li>Fan-out to multiple services via consumer groups with attribute-based filtering</li><li>Decoupling microservices with modest throughput (&lt; 10 MB/s)</li><li>Bursty, unpredictable workloads where serverless pricing avoids idle costs</li></ul><h3>OCI Streaming: The Managed Distributed Log</h3><p><strong>Documentation:</strong> <a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Concepts/streamingoverview.htm">OCI Streaming Overview</a></p><p>OCI Streaming is a fully managed, partitioned, append-only log. It’s architecturally similar to Apache Kafka — and deliberately compatible with Kafka APIs.</p><p><strong>How it handles backpressure:</strong> Producers write to partitions (1 MB/s per partition). Messages are retained for up to 7 days regardless of consumption. If a consumer falls behind, it simply reads from an earlier offset — the data is still there. Consumer groups coordinate partition assignment so that multiple consumer instances can process a stream in parallel. <a href="https://docs.oracle.com/en-us/iaas/Content/connector-hub/overview.htm">Connector Hub</a> can route stream data to downstream services with configurable batch settings that control flow rate.</p><p><strong>Key characteristics:</strong></p><ul><li><strong>Delivery model:</strong> Publish-subscribe (one message → multiple consumer groups)</li><li><strong>Message size:</strong> Up to 1 MB</li><li><strong>Ordering:</strong> Guaranteed within a partition</li><li><strong>Replay:</strong> Full replay within the retention window (24 hours to 7 days)</li><li><strong>Protocol:</strong> REST API + <a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Tasks/kafkacompatibility.htm">Kafka API</a> (SASL_SSL on port 9092)</li><li><strong>Consumer groups:</strong> Up to 50 per stream</li><li><strong>Durability:</strong> Synchronously replicated across 3 availability domains (or 3 fault domains)</li></ul><p><strong>Kafka compatibility details (</strong><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Tasks/kafkacompatibility_topic-Configuration.htm"><strong>Using Kafka APIs</strong></a><strong>):</strong></p><pre>bootstrap.servers=streaming.{region}.oci.oraclecloud.com:9092<br>security.protocol=SASL_SSL<br>sasl.mechanism=PLAIN</pre><p>Existing Kafka producer and consumer applications can point to OCI Streaming with a configuration change — no code rewrite needed. <a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Tasks/kafkacompatibility_topic-Kafka_Connect.htm">Kafka Connect</a> connectors work for interfacing with databases, object stores, and external services.</p><p><strong>When to use OCI Streaming:</strong></p><ul><li>Event-driven architectures with multiple downstream consumers</li><li>Real-time analytics and metric/log ingestion</li><li>Migrating from self-managed Kafka (Kafka API compatibility reduces migration risk)</li><li>Systems requiring event replay for debugging or reprocessing</li><li>Fan-out patterns where the same event feeds multiple services</li></ul><h3>Self-Managed Kafka on OCI Compute: The Full-Control Option</h3><p><strong>What it is:</strong> A full Apache Kafka cluster deployed on OCI Compute instances with complete access to every Kafka feature, including Kafka Streams, log compaction, transactions, exactly-once semantics, and configurable retention (limited only by disk capacity and cost).</p><p><strong>How it handles backpressure:</strong> Producer and consumer quotas control throughput per client. Consumer lag monitoring (via JMX metrics exported to OCI Monitoring or Prometheus) drives autoscaling decisions for consumer instances. Tiered storage offloads cold data to OCI Object Storage. Partition reassignment redistributes load during traffic shifts.</p><p><strong>Typical OCI infrastructure:</strong></p><ul><li><strong>Brokers:</strong> 3–9+ VM.Standard.E4.Flex instances (or BM.Standard.E4.128 bare metal for extreme throughput)</li><li><strong>Storage:</strong> Block Volumes (balanced or high performance) or NVMe local SSDs on Dense I/O shapes</li><li><strong>Controller:</strong> 3 Zookeeper or KRaft controller nodes</li><li><strong>Networking:</strong> Dedicated VCN subnet, Network Security Groups, optional OCI Network Load Balancer</li><li><strong>Monitoring:</strong> Prometheus + Grafana, or OCI Monitoring with custom metrics</li></ul><p><strong>When to use self-managed Kafka:</strong></p><ul><li>You need Kafka Streams, ksqlDB, or Apache Flink for complex event processing</li><li>Log compaction is required for event sourcing (retaining latest state per key)</li><li>Broker-level exactly-once transactional semantics across topics</li><li>Retention &gt; 7 days (configurable, bounded by disk and tiered storage lifecycle)</li><li>Throughput &gt; 200 MB/s sustained (where partition limits of OCI Streaming become awkward, assuming even key distribution)</li></ul><h3>The Decision Framework: Throughput Tiers</h3><p>Here’s where the abstract comparison becomes a concrete decision. Your throughput tier — the sustained data rate your system must handle — is the primary discriminator.</p><p>The following diagram illustrates the decision flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnTU4RPTr1oACGwqDo_0oQ.png" /></figure><h3>Tier 1: &lt; 1 MB/s (roughly &lt; 1,000 events/second at 1 KB each)</h3><p><strong>→ Use OCI Queue</strong></p><p>At this throughput, you’re processing background tasks, order queues, or low-volume integrations. OCI Queue’s serverless model means you pay per request with zero idle cost. No partitions to provision, no retention to configure. Dead Letter Queues handle poison messages automatically.</p><p><strong>Monthly cost estimate:</strong> Minimal — serverless pricing with zero idle cost.</p><p><strong>What you give up:</strong> Replay, ordering guarantees. (Note: OCI Queue now supports fan-out via consumer groups, but without the replay and offset-tracking capabilities of OCI Streaming.)</p><p><strong>Example use case:</strong> An e-commerce platform processing 500 orders/minute. Each order is a task dispatched to a worker pool via OCI Queue. Failed orders go to the DLQ for manual review.</p><h3>Tier 2: 1–50 MB/s (roughly 1,000–50,000 events/second at 1 KB each)</h3><p><strong>→ Use OCI Streaming</strong></p><p>This is the sweet spot for OCI Streaming. You need replay for debugging, multiple consumer groups for fan-out, and Kafka compatibility for existing tooling. Provision 10–50 partitions (1 MB/s each) and scale consumer groups as needed.</p><p><strong>Monthly cost estimate:</strong> ~$150–750/month for 10–50 partitions (region-dependent), plus data transfer and storage. Verify against <a href="https://www.oracle.com/cloud/cloud-native/streaming/pricing/">current OCI pricing</a>.</p><p><strong>What you give up:</strong> Kafka Streams, compaction, transactions, dynamic partition scaling.</p><p><strong>Example use case:</strong> A real-time analytics pipeline ingesting clickstream data at 20 MB/s. <a href="https://docs.oracle.com/en-us/iaas/Content/connector-hub/overview.htm">OCI Streaming feeds data to Connector Hub</a>, which routes it to Object Storage for batch analytics and to OCI Functions for real-time alerting. Existing Kafka producers require only a bootstrap server and authentication change.</p><h3>Tier 3: 50–500 MB/s (roughly 50,000–500,000 events/second at 1 KB each)</h3><p><strong>→ OCI Streaming (high partition count) OR Self-Managed Kafka</strong></p><p>This is the decision boundary. At 100 MB/s, you need 100+ partitions on OCI Streaming — assuming even key distribution and optimal producer batching; partition skew and variable message sizes reduce effective throughput. The default limit at time of writing is 200 partitions per tenancy (Monthly Universal Credits) / 50 (PAYG), though these limits are requestable increases and may change — <a href="https://docs.oracle.com/iaas/Content/General/Concepts/servicelimits.htm">check the current service limits page</a>.</p><p><strong>Choose OCI Streaming if:</strong></p><ul><li>You don’t need Kafka Streams, compaction, or transactions</li><li>You want zero operational overhead</li><li>You can work within the 7-day retention limit</li><li>Your team would rather build product than manage Kafka</li></ul><p><strong>Choose self-managed Kafka if:</strong></p><ul><li>You need any unsupported feature (Streams, compaction, transactions, exactly-once)</li><li>Retention &gt; 7 days is a hard requirement</li><li>You have dedicated infrastructure engineers for Kafka management</li><li>Custom partition strategies or broker tuning are essential</li></ul><p><strong>Monthly cost estimate (self-managed):</strong></p><ul><li>3 broker VMs (8 OCPU, 128 GB RAM each): ~$1,200–1,800/month</li><li>3 Zookeeper VMs: ~$200–400/month</li><li>Block Volumes (150 GB): ~$75–150/month</li><li>Total infrastructure: ~$1,700–2,500/month minimum</li><li>+ 0.5–2 FTE operational cost (not included above)</li></ul><p><em>Based on E4.Flex shapes with moderate memory and standard block volumes at list pricing. Actual costs vary significantly by shape, storage profile (high-performance block volumes or Dense I/O NVMe), region, and commitment discounts. Verify against </em><a href="https://www.oracle.com/cloud/cloud-native/pricing/"><em>current OCI pricing</em></a><em> before making budget decisions.</em></p><h3>Tier 4: &gt; 500 MB/s</h3><p><strong>→ Self-Managed Kafka on Bare Metal</strong></p><p>At this throughput, you’re operating at a scale where OCI Streaming’s per-partition model becomes cost-inefficient (500+ partitions). Deploy Kafka on BM.Standard.E4.128 bare metal instances with local NVMe storage for maximum disk throughput.</p><p><strong>Warning:</strong> If you’re at this tier and don’t have a dedicated platform engineering team, you have a bigger problem than technology selection.</p><h3>Backpressure Patterns by Service</h3><p>The decision framework tells you <em>which</em> service to use. These patterns show you <em>how</em> to handle backpressure once you’ve chosen.</p><h3>Pattern 1: Queue-Based Backpressure (OCI Queue + OCI Functions)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfY2cz4CgKayf_H6659e9g.png" /></figure><p>Multiple consumer groups receive independent copies of each message, enabling fan-out without a streaming layer. Attribute-based filters allow each group to receive only relevant messages. The visibility timeout prevents duplicate processing within each group. The DLQ isolates poison messages. OCI Functions concurrency limits prevent downstream database overwhelm. This is the simplest backpressure pattern and requires zero custom code for the buffering layer.</p><h3>Pattern 2: Stream-Based Backpressure (OCI Streaming + Connector Hub)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awyC3vfxTw7SW6kMh50iSA.png" /></figure><p>Consumer groups read independently. If Consumer Group A falls behind, it reads from an earlier offset — data is retained for up to 7 days. Connector Hub’s <a href="https://docs.oracle.com/en-us/iaas/Content/connector-hub/overview.htm">batch settings</a> (configurable by size and time) control the rate at which data flows to downstream services. The stream acts as a shock absorber: producers are never blocked by slow consumers.</p><h3>Pattern 3: Kafka-Native Backpressure (Self-Managed)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*XECT_Zkt1x0ZLSLi8AVkhw.png" /></figure><p>Producer and consumer quotas enforce per-client throughput limits. Consumer lag metrics (exposed via JMX) trigger auto-scaling of consumer instances on OCI Compute. Tiered storage moves older data to OCI Object Storage, reducing disk pressure on brokers. This pattern requires the most operational investment but provides the finest-grained control.</p><h3>The Integration Layer: Connector Hub as the Glue</h3><p>Regardless of whether you choose OCI Queue or OCI Streaming as your primary event layer, <a href="https://docs.oracle.com/en-us/iaas/Content/connector-hub/overview.htm">OCI Connector Hub</a> acts as the integration fabric for routing events to OCI-native services.</p><p>Connector Hub supports both Queue and Streaming as sources, and can route data to:</p><ul><li><strong>OCI Functions</strong> (serverless processing with custom logic)</li><li><strong>Object Storage</strong> (long-term archival)</li><li><strong>Log Analytics</strong> (search and analysis)</li><li><strong>Streaming</strong> (cross-stream routing)</li><li><strong>Notifications</strong> (alerting via email, Slack, PagerDuty)</li><li><strong>Monitoring</strong> (custom metric ingestion)</li></ul><p>Key behaviors to understand:</p><ul><li><strong>Delivery:</strong> At-least-once. Plan for idempotent consumers.</li><li><strong>Batching:</strong> Configurable by size and time. The first limit reached triggers a flush.</li><li><strong>Failure handling:</strong> Failed operations are retried; subsequent batches are blocked until the retry succeeds. After 7 consecutive days of failure, the connector is automatically deactivated.</li><li><strong>Reset on update:</strong> Modifying a connector’s source or target configuration causes an internal reset — potentially reprocessing data. Create new connectors instead of updating existing ones.</li></ul><h3>The Real Cost Comparison: Total Cost of Ownership</h3><p>Infrastructure costs tell only half the story. The real comparison requires total cost of ownership that includes operational overhead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c344a58362acb07361897e0803827280/href">https://medium.com/media/c344a58362acb07361897e0803827280/href</a></iframe><p><em>Infrastructure cost estimates are approximate. Streaming costs vary by partition count and region. Kafka costs assume E4.Flex shapes at list pricing. Verify against </em><a href="https://www.oracle.com/cloud/cloud-native/pricing/"><em>current OCI pricing pages</em></a><em> before budget decisions.</em></p><p>The inflection point is clear: <strong>self-managed Kafka only makes economic sense when you need features that OCI Streaming doesn’t support AND your throughput justifies the operational investment.</strong></p><p>For workloads common in most organizations — event-driven microservices, analytics pipelines, IoT ingestion, log aggregation — OCI Streaming covers the majority of Kafka’s functional surface area while eliminating the operational cost entirely. The gap narrows to the specific features (Streams, compaction, transactions) that your architecture either needs or doesn’t.</p><h3>Lessons Learned: What Production Teaches You</h3><ol><li><strong>Start with OCI Queue, graduate to OCI Streaming.</strong> Most teams overestimate their throughput requirements. Consider: 10,000 requests per second at 1 KB per message is only 10 MB/s — well within OCI Queue’s ceiling. Even 50,000 RPS at 1 KB is just 50 MB/s, which is mid-range for OCI Streaming. Begin with the simplest primitive that satisfies your constraints. Migrating from Queue to Streaming is a well-defined upgrade path. Migrating from Kafka to OCI Streaming is a painful downgrade.</li><li><strong>Partition count is your capacity plan.</strong> OCI Streaming partitions are immutable after creation. Over-provision by 50% — it’s cheaper than recreating streams under production load. A 20-partition stream at 10 MB/s costs far less than an incident caused by hitting the write ceiling.</li><li><strong>Consumer lag is your most important metric.</strong> Whether you use OCI Streaming or self-managed Kafka, consumer lag (the offset difference between the latest produced message and the latest consumed message) is the early warning system for backpressure. Monitor it. Alert on it. Build dashboards around it.</li><li><strong>Dead Letter Queues are not optional.</strong> Every production event pipeline has poison messages — events that will never process successfully due to schema mismatches, null fields, or encoding errors. OCI Queue provides DLQs natively. On OCI Streaming, build a DLQ pattern using Connector Hub to route failed events to a separate stream or Object Storage bucket.</li><li><strong>Kafka compatibility ≠ Kafka equivalence.</strong> OCI Streaming’s Kafka API support means existing Kafka producers and consumers can connect with a configuration change. It does not mean OCI Streaming behaves identically to Kafka. Test thoroughly before migrating — especially patterns that rely on compaction, transactions, or Kafka Streams.</li></ol><h3>Conclusion: The Right Tool for the Right Tier</h3><p>The narrative around “LinkedIn evolving past Kafka” isn’t about replacement — it’s about specialization. LinkedIn built Kora; most large-scale firms are investing in tiered storage, protocol proxies, and purpose-built primitives rather than discarding Kafka wholesale. The real evolution is the industry moving away from one-size-fits-all event streaming toward primitives matched to specific throughput tiers and operational constraints.</p><p>On OCI, this means:</p><ul><li><strong>&lt; 1 MB/s:</strong> OCI Queue. Zero ops, zero idle cost, DLQ built-in.</li><li><strong>1–50 MB/s:</strong> OCI Streaming. Kafka-compatible, fully managed, replay-capable.</li><li><strong>50–500 MB/s:</strong> OCI Streaming (high partition count) or self-managed Kafka if you need full Kafka features.</li><li><strong>&gt; 500 MB/s:</strong> Self-managed Kafka on bare metal. But if you’re here, you already have a platform team.</li></ul><p>The worst architectural decision isn’t choosing the wrong technology. It’s choosing a technology based on what you might need someday, rather than what your system actually requires today. Start with constraints. Match to throughput. Graduate when the data demands it.</p><h3>References</h3><h3>OCI Documentation</h3><ul><li><a href="https://docs.oracle.com/en-us/iaas/Content/queue/overview.htm">OCI Queue — Overview</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/queue/deadletterqueues.htm">OCI Queue — Dead Letter Queues</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/queue/channels.htm">OCI Queue — Channels</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/queue/messages-stomp.htm">OCI Queue — STOMP Protocol</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Concepts/streamingoverview.htm">OCI Streaming — Overview</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Concepts/streamingoverview_topic-Limits_on_Streaming_Resources.htm">OCI Streaming — Resource Limits</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Tasks/kafkacompatibility.htm">OCI Streaming — Kafka Compatibility</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Tasks/kafkacompatibility_topic-Configuration.htm">OCI Streaming — Using Kafka APIs</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Tasks/kafkacompatibility_topic-Kafka_Connect.htm">OCI Streaming — Kafka Connect</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Streaming/Concepts/streamsecurity.htm">OCI Streaming — Security Best Practices</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/connector-hub/overview.htm">OCI Connector Hub — Overview</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/connector-hub/scenarios.htm">OCI Connector Hub — Scenarios</a></li><li><a href="https://docs.oracle.com/en-us/iaas/Content/Functions/Concepts/functionsconcepts.htm">OCI Functions — Concepts</a></li><li><a href="https://docs.oracle.com/iaas/Content/General/Concepts/servicelimits.htm">OCI Service Limits</a></li></ul><h3>OCI Reference Architectures</h3><ul><li><a href="https://docs.oracle.com/en/solutions/streaming-data-to-an-adb/index.html">Stream Data to Autonomous Database in Real Time</a></li><li><a href="https://docs.oracle.com/en/solutions/iot-streaming-oci/index.html">Stream IoT Data to ADB Using Serverless Functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c289b63825f7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/when-to-not-use-kafka-on-oci-a-cost-and-complexity-analysis-for-event-streaming-architecture-c289b63825f7">When to NOT Use Kafka on OCI: A Cost and Complexity Analysis for Event Streaming Architecture</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>