<?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 Ashutosh Kumar Singh on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Kumar Singh on Medium]]></description>
        <link>https://medium.com/@ashutoshongithub?source=rss-617d2822745b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wvE4m7zio2q52jOCw5oTgw.jpeg</url>
            <title>Stories by Ashutosh Kumar Singh on Medium</title>
            <link>https://medium.com/@ashutoshongithub?source=rss-617d2822745b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:41:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutoshongithub/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[Read Replica Staleness: The Silent Liar in Distributed Databases]]></title>
            <link>https://medium.com/@ashutoshongithub/read-replica-staleness-the-silent-liar-in-distributed-databases-bd0603d17de5?source=rss-617d2822745b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd0603d17de5</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Singh]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 03:40:53 GMT</pubDate>
            <atom:updated>2026-01-06T03:51:48.928Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“The write succeeded. The read said it didn’t.”<em><br> If you’ve ever seen this in production, you’ve met read replica staleness.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*vTlrnMgMUpOjWwTwiR2a_w.gif" /></figure><p>At scale, databases rarely run as a single node.<br> To handle read traffic, teams introduce <strong>read replicas</strong>.<br> Performance improves. Costs go down. Everything looks fine — until it doesn’t.</p><p>This article breaks down <strong>why read replicas return stale data</strong>, the underlying database mechanics, and how this silently breaks real systems.</p><h3>What Is a Read Replica?</h3><p>A <strong>read replica</strong> (also called a follower or secondary) is a copy of the primary database that:</p><ul><li>Receives data changes from the primary</li><li>Serves read-only queries</li><li>Is typically used to scale read traffic</li></ul><h3>Why replicas exist:</h3><ul><li>Reads scale better than writes</li><li>Writes must go to one authority (the primary)</li><li>Replicas reduce load on the primary</li></ul><p>However, replicas are <strong>not</strong> updated instantly.</p><h3>How Database Replication Actually Works</h3><p>Most relational databases (MySQL, PostgreSQL, Aurora, etc.) use <strong>log-based replication</strong>.</p><h3>Write flow:</h3><ol><li>Client sends write to primary</li><li>Primary commits transaction</li><li>Change is written to a <strong>write-ahead log (WAL / binlog)</strong></li><li>Replica asynchronously reads this log</li><li>Replica replays the changes locally</li></ol><p>Between steps <strong>3 and 5</strong>, the replica is <strong>behind</strong>.</p><p>That gap is called <strong>replication lag</strong>.</p><h3>What Is Replication Lag?</h3><p><strong>Replication lag</strong> is the delay between:</p><ul><li>A transaction being committed on the primary</li><li>The same transaction being visible on a replica</li></ul><p>It can be:</p><ul><li>Milliseconds (normal case)</li><li>Seconds or minutes (during spikes)</li><li>Unbounded (during failures)</li></ul><h3>Causes of replication lag:</h3><ul><li>High write throughput</li><li>Slow disk IO on replicas</li><li>Network latency</li><li>Long-running transactions</li><li>Replica CPU pressure</li></ul><p>Replication lag is <strong>not an error</strong>.<br> It is an expected property of async replication.</p><h3>Asynchronous vs Synchronous Replication</h3><h3>Asynchronous Replication (default)</h3><ul><li>Primary does <strong>not wait</strong> for replicas</li><li>Low latency, high availability</li><li>Replicas may be stale</li></ul><h3>Synchronous Replication</h3><ul><li>Primary waits for replica acknowledgment</li><li>Stronger consistency</li><li>Higher latency</li><li>Lower availability</li></ul><p>Most production systems choose <strong>async replication</strong> because:</p><blockquote><em>Availability and latency matter more than perfect freshness.</em></blockquote><h3>Eventual Consistency Explained</h3><p><strong>Eventual consistency</strong> means:</p><blockquote><em>If no new updates are made, all replicas will eventually converge to the same state.</em></blockquote><p>Key properties:</p><ul><li>Temporary inconsistencies are allowed</li><li>No guarantee on <em>when</em> data becomes consistent</li><li>Reads may return old data</li></ul><p>This is acceptable for:</p><ul><li>Feeds</li><li>Analytics</li><li>Reporting</li></ul><p>It is dangerous for:</p><ul><li>Payments</li><li>Authentication</li><li>Inventory</li><li>Order state</li></ul><h3>The “Read-After-Write” Fallacy</h3><p>Many systems assume <strong>read-after-write consistency</strong>:</p><blockquote><em>After a successful write, the next read returns the updated data.</em></blockquote><p>Read replicas <strong>do not provide this guarantee</strong>.</p><h3>Example failure:</h3><ol><li>User creates order</li><li>Order is written to primary</li><li>Read request is routed to replica</li><li>Replica hasn’t applied the write yet</li><li>API returns “order not found”</li></ol><p>The system appears broken — but it’s behaving correctly.</p><h3>Why This Bug Is So Hard to Reproduce</h3><ul><li>Local environments rarely use replicas</li><li>Lag is usually very small</li><li>Unit tests don’t model distributed timing</li><li>Load tests don’t simulate IO contention</li></ul><p>The bug appears:</p><ul><li>Under peak traffic</li><li>During deployments</li><li>During failovers</li></ul><p>This makes it <strong>production-only</strong> and <strong>non-deterministic</strong>.</p><h3>Replica Staleness in Real Systems</h3><h3>Common symptoms:</h3><ul><li>Login succeeds, profile fetch fails</li><li>Payment completed, status shows pending</li><li>Duplicate inserts due to missing reads</li><li>Flaky 404s right after writes</li></ul><p>These are not random.<br> They are <strong>consistency mismatches</strong>.</p><h3>Why Monitoring Often Misses It</h3><p>Teams monitor:</p><ul><li>CPU</li><li>Memory</li><li>QPS</li><li>Latency</li></ul><p>They often ignore:</p><ul><li>Replica lag</li><li>Log replay delay</li><li>Apply queue depth</li></ul><p>The system looks healthy while serving <strong>incorrect data</strong>.</p><h3>Correct Design Patterns</h3><h3>1. Read Routing Based on Consistency</h3><ul><li>Reads after writes → primary</li><li>Background reads → replica</li></ul><h3>2. Session Stickiness</h3><ul><li>Route user to primary for a short window after write</li></ul><h3>3. Consistency-Aware APIs</h3><ul><li>Return “processing” instead of “not found”</li></ul><h3>4. Idempotent Writes</h3><ul><li>Prevent duplicate side effects</li></ul><h3>5. Lag-Based Circuit Breaking</h3><ul><li>Stop using replicas when lag crosses threshold</li></ul><h3>The Real Lesson</h3><p>Read replicas don’t lie.<br> They <strong>eventually</strong> tell the truth.</p><p>The real problem is designing systems that:</p><ul><li>Assume consistency</li><li>Without enforcing or modeling it</li></ul><p>At scale, <strong>consistency is not free</strong>.<br>If you don’t design for it explicitly, your users will discover the gaps for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0603d17de5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Rare Database Failure: Auto-Increment Integer Exhaustion]]></title>
            <link>https://medium.com/@ashutoshongithub/a-rare-database-failure-auto-increment-integer-exhaustion-2dcfa67b7e8e?source=rss-617d2822745b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dcfa67b7e8e</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Singh]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 13:28:34 GMT</pubDate>
            <atom:updated>2026-01-03T16:11:55.842Z</atom:updated>
            <content:encoded><![CDATA[<p>Most backend systems rely on a simple assumption:</p><blockquote><em>“Auto-increment IDs will just keep increasing forever.”</em></blockquote><p>That assumption is wrong.</p><p>In this article, we’ll break down:</p><ul><li>What happens when an auto-increment integer <strong>hits its maximum limit</strong></li><li>Why databases behave the way they do</li><li>What failures you’ll actually see in production</li><li>And most importantly — <strong>what to do when (not if) this happens</strong></li></ul><p>This is not theoretical. This is a <strong>real production failure mode</strong> that only shows up at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*RU4AX0x0S6X607de_xQdtA.gif" /></figure><h3>The Setup: Auto-Increment IDs</h3><p>A very common schema looks like this:</p><pre>CREATE TABLE users (<br>  id INT AUTO_INCREMENT PRIMARY KEY,<br>  name VARCHAR(255) NOT NULL<br>);</pre><p>This seems harmless — and it is, for a long time.</p><p>By default in MySQL:</p><ul><li>INT is <strong>4 bytes</strong></li><li>It is <strong>signed</strong></li><li>The maximum value is:</li></ul><pre>2,147,483,647 (2^31 - 1)</pre><p>Once you reach that number, the database has <strong>nowhere to go</strong>.</p><h3>What Actually Happens at the Limit?</h3><p>Let’s walk through it step by step.</p><h3>Normal Inserts</h3><pre>INSERT INTO users (name) VALUES (&#39;A&#39;);<br>INSERT INTO users (name) VALUES (&#39;B&#39;);</pre><p>IDs are assigned:</p><pre>1, 2</pre><p>Everything works.</p><h3>Manually Inserting a Higher ID</h3><pre>INSERT INTO users (id, name) VALUES (100, &#39;C&#39;);</pre><p>Now the auto-increment counter jumps to 100.</p><p>Next insert:</p><pre>INSERT INTO users (name) VALUES (&#39;D&#39;);</pre><p>Result:</p><pre>ID = 101</pre><p>This is expected behavior.</p><h3>Inserting the Maximum Integer</h3><pre>INSERT INTO users (id, name)<br>VALUES (2147483647, &#39;MAX&#39;);</pre><p>This insert <strong>succeeds</strong>.</p><p>Now the table is at the limit.</p><h3>The Breaking Point</h3><p>Try inserting one more row:</p><pre>INSERT INTO users (name) VALUES (&#39;FAIL&#39;);</pre><p>The insert fails.</p><p>But here’s the surprising part.</p><p>Instead of an “integer overflow” error, MySQL throws:</p><pre>Duplicate entry &#39;2147483647&#39; for key &#39;PRIMARY&#39;</pre><h3>Why a Duplicate Key Error?</h3><p>This is unintuitive, but critical to understand.</p><p>In many programming languages:</p><ul><li>Integer overflow <strong>wraps around</strong></li><li>MAX_INT + 1 becomes MIN_INT</li></ul><p>But MySQL does <strong>not</strong> wrap.</p><p>Instead:</p><ul><li>Auto-increment <strong>stops increasing</strong></li><li>MAX_INT + 1 = MAX_INT</li><li>The database keeps generating the <strong>same value</strong></li><li>Inserts fail due to <strong>primary key collision</strong></li></ul><p>So what looks like a “duplicate key problem” is actually an <strong>exhausted ID space</strong>.</p><h3>Why This Is Dangerous in Production</h3><p>This failure mode is especially dangerous because:</p><ul><li>It happens <strong>only at very large scale</strong></li><li>It is <strong>not obvious from the error</strong></li><li>It often affects <strong>critical write paths</strong></li></ul><p>And unless you are explicitly monitoring for it, it arrives as a surprise.</p><h3>Prevention: What You Should Always Do</h3><h3>1. Monitor Auto-Increment Usage</h3><p>For tables with:</p><ul><li>High insert rate</li><li>Long lifespan</li><li>Shared usage across services</li></ul><p>You should <strong>monitor ID exhaustion</strong>.</p><p>A good rule of thumb:</p><ul><li>Alert at <strong>70–80%</strong> of the maximum range</li></ul><p>This gives you <strong>time to migrate safely</strong> instead of reacting during an outage.</p><h3>Mitigation Strategy #1: Increase the ID Range</h3><h3>Option A: Use UNSIGNED INT</h3><p>Signed INT:</p><pre>-2^31 → 2^31 - 1</pre><p>Unsigned INT:</p><pre>0 → 4,294,967,295</pre><p>That’s <strong>double the space</strong> immediately.</p><pre>ALTER TABLE users<br>MODIFY id INT UNSIGNED NOT NULL AUTO_INCREMENT;</pre><h3>Option B: Use BIGINT (Recommended)</h3><pre>ALTER TABLE users<br>MODIFY id BIGINT NOT NULL AUTO_INCREMENT;</pre><p>BIGINT gives you:</p><pre>2^63 - 1 possible values</pre><p>For practical purposes, this is <strong>effectively infinite</strong>.</p><h3>Important Caveat</h3><p>ALTER TABLE on a <strong>large, hot table</strong> is risky:</p><ul><li>It may lock the table</li><li>It may take hours or days</li><li>It may worsen an ongoing outage</li></ul><p>This approach works best when:</p><ul><li>The table is small</li><li>You catch the issue early</li><li>You can afford maintenance time</li></ul><h3>Mitigation Strategy #2: Table Swapping</h3><h3>High-Level Idea</h3><ol><li>Create a <strong>new table</strong> with the same schema</li><li>Use a <strong>larger ID type</strong></li><li>Start auto-increment <strong>past the old limit</strong></li><li>Swap tables instantly</li><li>Backfill data asynchronously</li></ol><h3>Step-by-Step</h3><ol><li>Create a new table:</li></ol><pre>CREATE TABLE users_new LIKE users;</pre><p>2. Increase ID size:</p><pre>ALTER TABLE users_new<br>MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT;</pre><p>3. Set auto-increment start:</p><pre>ALTER TABLE users_new AUTO_INCREMENT = 2147483648;</pre><p>4. Swap tables:</p><pre>RENAME TABLE users TO users_old,<br>             users_new TO users;</pre><p>Writes resume immediately<br>Old data lives in users_old<br>Backfill data gradually in the background</p><p>This approach:</p><ul><li>Minimizes downtime</li><li>Avoids long locks</li><li>Is commonly used in large-scale systems</li></ul><h3>Long-Term Architectural Alternatives</h3><p>If your system is <strong>insert-heavy</strong> and <strong>globally distributed</strong>, consider:</p><ul><li>UUIDs</li><li>Snowflake-style ID generators</li><li>Dedicated ID services</li><li>Sharded ID ranges</li></ul><p>Auto-increment IDs are simple — but simplicity has limits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dcfa67b7e8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is a Thread Pool? Why Do We Need It, Why It Exists, and How to Size It Optimally]]></title>
            <link>https://medium.com/@ashutoshongithub/what-is-a-thread-pool-why-do-we-need-it-why-it-exists-and-how-to-size-it-optimally-8f321d7f643b?source=rss-617d2822745b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f321d7f643b</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Singh]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 16:55:53 GMT</pubDate>
            <atom:updated>2026-01-02T17:00:19.515Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrency is one of those concepts every backend engineer <em>uses</em> daily -but often doesn’t fully reason about.<br> Thread pools sit quietly behind web servers, async frameworks, schedulers, and SDKs, making systems scalable and stable.</p><h3>What Is a Thread Pool?</h3><p>A <strong>thread pool</strong> is a managed collection of worker threads that are <strong>created once and reused</strong> to execute multiple tasks over time.</p><p>Instead of creating a new thread for every incoming task, your application:</p><ol><li>Submits tasks to a queue</li><li>Idle threads from the pool pick tasks from the queue</li><li>Threads execute the task and return to the pool</li></ol><p>Think of it like a <strong>team of fixed employees</strong> handling incoming work, instead of hiring a new person for every request.</p><h3>Why Do We Need a Thread Pool?</h3><h3>1. Thread creation is expensive</h3><p>Creating a thread isn’t free:</p><ul><li>Memory allocation for stack</li><li>OS scheduling overhead</li><li>Context switching cost</li></ul><p>If you create threads per request:</p><ul><li>CPU time is wasted on thread management</li><li>Memory usage explodes</li><li>System becomes unstable under load</li></ul><p>A thread pool <strong>amortizes this cost</strong> by reusing threads.</p><h3>2. Unbounded threads can crash your system</h3><p>Without a thread pool:</p><ul><li>Each request → new thread</li><li>High traffic → thousands of threads</li></ul><p>Leads to:</p><ul><li>OutOfMemoryError</li><li>Excessive context switching</li><li>CPU thrashing</li></ul><p>Thread pools introduce <strong>backpressure</strong>:</p><ul><li>Limited threads</li><li>Tasks wait in a queue</li><li>System stays alive instead of collapsing</li></ul><h3>3. Controlled concurrency</h3><p>Thread pools allow you to say:</p><ul><li><em>“At most N tasks can run concurrently”</em></li><li><em>“Extra tasks must wait”</em></li></ul><p>This protects:</p><ul><li>Databases</li><li>External APIs</li><li>CPU</li><li>Memory</li></ul><p>Without thread pools, concurrency is <strong>accidental</strong>.<br> With thread pools, concurrency is <strong>intentional</strong>.</p><h3>Why Does the Thread Pool Concept Exist?</h3><p>Thread pools exist because of a fundamental mismatch:</p><blockquote><strong><em>Workload scales faster than hardware resources</em></strong></blockquote><p>Requests can spike instantly.<br> CPU cores, memory, and IO bandwidth cannot.</p><p>Thread pools are a <strong>throttling mechanism</strong> between:</p><ul><li>Unlimited demand</li><li>Finite resources</li></ul><p>That’s why you’ll find thread pools everywhere:</p><ul><li>Web servers (Tomcat, Netty)</li><li>Executors in Java</li><li>Async task schedulers</li><li>Database connection pools (same idea, different resource)</li></ul><h3>How a Thread Pool Works (High Level)</h3><ol><li>A fixed or bounded number of threads is created</li><li>Tasks are submitted to a queue</li><li>Free threads pick tasks from the queue</li><li>If all threads are busy:</li></ol><ul><li>Task waits in queue</li><li>Or gets rejected (depending on policy)</li></ul><p>This model gives:</p><ul><li>Predictable performance</li><li>Stability under load</li><li>Easier tuning</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*iWnH33OcpDXApkVQjwaYkg.png" /></figure><h3>How to Find the Optimal Thread Pool Size</h3><p>This is the most misunderstood part.</p><p>There is <strong>no single magic number</strong>, but there <em>is</em> a formula-driven approach.</p><h3>Step 1: Understand Your Task Type</h3><p>There are two broad categories:</p><h4>1. CPU-bound tasks</h4><ul><li>Heavy computation</li><li>Minimal IO</li><li>Examples: image processing, encryption, data crunching</li></ul><h4>2. IO-bound tasks</h4><ul><li>Waiting on network / disk</li><li>CPU mostly idle</li><li>Examples: DB calls, HTTP calls, file reads</li></ul><h3>Step 2: Use the Core Formula</h3><p>A widely accepted sizing formula:</p><pre>Thread Pool Size = Number of Cores × (1 + Wait Time / Compute Time)</pre><h3>For CPU-bound workloads</h3><p>Since wait time ≈ 0:</p><pre>Thread Pool Size ≈ Number of CPU cores</pre><p>Example:</p><ul><li>8-core machine</li><li>Optimal threads: <strong>8 to 9</strong></li></ul><p>Why?</p><ul><li>More threads just increase context switching</li><li>CPU cannot execute more than core count simultaneously</li></ul><h3>For IO-bound workloads</h3><p>Threads spend a lot of time waiting.</p><p>Example:</p><ul><li>90% waiting on IO</li><li>10% actual CPU work</li></ul><pre>Wait / Compute = 9<br>Thread Pool Size = Cores × (1 + 9)</pre><p>On an 8-core machine:</p><pre>8 × 10 = 80 threads</pre><p>This allows other threads to run while some are blocked on IO.</p><h3>How to Tune in Real Systems</h3><ol><li>Start with theory-based sizing</li><li>Load test your system</li><li>Monitor:</li></ol><ul><li>CPU utilization</li><li>Queue length</li><li>Task latency</li></ul><ol><li>Increase threads <strong>only if CPU is underutilized</strong></li><li>Decrease threads if:</li></ol><ul><li>Context switching spikes</li><li>Latency increases under load</li></ul><p><strong>More threads ≠ more performance</strong></p><p>Thread pools are not just a performance optimization — they are a <strong>safety mechanism</strong>.</p><p>They exist because:</p><ul><li>Threads are expensive</li><li>Resources are limited</li><li>Traffic is unpredictable</li></ul><p>Understanding thread pools helps you:</p><ul><li>Design stable systems</li><li>Avoid production outages</li><li>Make informed performance tradeoffs</li></ul><p>If you don’t control concurrency, concurrency will control you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f321d7f643b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded Databases: What They Are, Why They Exist, and When to Use Them]]></title>
            <link>https://medium.com/@ashutoshongithub/embedded-databases-what-they-are-why-they-exist-and-when-to-use-them-1b382f9def9c?source=rss-617d2822745b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b382f9def9c</guid>
            <dc:creator><![CDATA[Ashutosh Kumar Singh]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 16:57:14 GMT</pubDate>
            <atom:updated>2026-01-01T16:57:14.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Most backend engineers learn databases in a very specific order:<br> first MySQL or Postgres, then maybe MongoDB, and eventually something distributed.</p><p>But there’s an entire class of databases that quietly power tools, SDKs, and local systems — <strong>embedded databases</strong>.</p><p>I only started appreciating them when I needed persistence <strong>without</strong> running a database server.<br> That’s when embedded databases started to make a lot of sense.</p><h3>What Are Embedded Databases?</h3><p>An <strong>embedded database</strong> is a database that runs <strong>inside your application process</strong> as a library.</p><p>There is:</p><ul><li>No separate database server</li><li>No network communication</li><li>No external deployment</li></ul><p>Your application directly interacts with the database through in-process function calls, and data is typically stored in <strong>local files</strong>.</p><p>A simple mental model looks like this:</p><p>Application<br> ├── Business Logic<br> ├── Embedded Database (Library)<br> └── Local Disk</p><p>From the application’s point of view, the database is just another dependency — but one that provides persistence, transactions, and durability.</p><h3>Why Was There a Need for Embedded Databases?</h3><p>Not every problem needs a client-server database.</p><p>Embedded databases exist because:</p><ul><li>Running a full database server is <strong>operationally heavy</strong></li><li>Network calls add <strong>latency and complexity</strong></li><li>Many applications are <strong>single-node by design</strong></li></ul><p>Typical situations where server databases feel excessive:</p><ul><li>Local developer tools</li><li>CLI applications</li><li>Desktop apps</li><li>SDKs and agents</li><li>Test environments</li><li>Edge or IoT devices</li></ul><p>In these cases, embedded databases provide:</p><ul><li>Persistence without ops</li><li>Extremely low latency</li><li>Simple deployment</li></ul><p>They trade <strong>distributed scale</strong> for <strong>simplicity and locality</strong> — and that trade-off is often worth it.</p><h3>When Should You Use an Embedded Database?</h3><p>Embedded databases work best when:</p><ul><li>Your application runs on a <strong>single machine</strong></li><li>You control the lifecycle of the database</li><li>You need fast local reads and writes</li><li>High availability is not critical</li><li>Concurrency requirements are limited</li></ul><p>Concrete use cases include:</p><ul><li>Feature flag storage</li><li>Local caches and indexes</li><li>Request or event logging</li><li>Observability agents</li><li>Developer tooling</li><li>Offline-first applications</li></ul><p>In practice, many modern tools quietly rely on embedded databases because they simplify architecture significantly.</p><h3>When You Should Avoid Embedded Databases</h3><p>They are not meant for everything.</p><p>Avoid embedded databases if:</p><ul><li>Multiple services need shared access</li><li>You require heavy concurrent writes</li><li>Horizontal scaling is a requirement</li><li>Strong HA and replication are mandatory</li></ul><p>Embedded databases are <strong>not replacements</strong> for server databases — they are <strong>a different tool for a different problem</strong>.</p><h3>Different Categories of Embedded Databases</h3><p>Understanding categories is more important than memorizing names.</p><h3>1. Relational (SQL) Embedded Databases</h3><p>These databases offer SQL, schemas, and transactions.</p><p><strong>Characteristics</strong></p><ul><li>Familiar query model</li><li>ACID guarantees</li><li>Strong consistency</li><li>Limited concurrency</li></ul><p><strong>Implementation insight</strong><br> Most SQL embedded databases allow:</p><ul><li>Only one writer at a time</li><li>Multiple concurrent readers</li><li>Explicit transaction control</li></ul><h3>2. Key-Value Embedded Databases</h3><p>These databases focus on simple access patterns and performance.</p><p><strong>Characteristics</strong></p><ul><li>Very fast writes</li><li>Simple APIs (put, get, delete)</li><li>No joins or schemas</li><li>Application manages structure</li></ul><p><strong>Implementation insight</strong><br> Many key-value stores use:</p><ul><li>Log-Structured Merge (LSM) trees</li><li>Append-only writes</li><li>Background compaction</li></ul><p>This makes them ideal for high-throughput workloads.</p><h3>3. Object or Collection-Based Databases</h3><p>These databases persist objects or collections directly.</p><p><strong>Characteristics</strong></p><ul><li>Minimal boilerplate</li><li>Object-centric APIs</li><li>Faster development for small systems</li></ul><p><strong>Trade-off</strong></p><ul><li>Less transparent storage model</li><li>Potential vendor lock-in</li></ul><h3>Common Examples of Embedded Databases</h3><p>Here are some widely used embedded databases and where they fit best:</p><h3>Relational</h3><ul><li><strong>SQLite</strong> — mobile apps, tools, local persistence</li><li><strong>H2</strong> — testing, lightweight JVM apps</li><li><strong>Apache Derby</strong> — legacy Java systems</li></ul><h3>Key-Value</h3><ul><li><strong>RocksDB</strong> — high-performance local storage</li><li><strong>LevelDB</strong> — simple KV persistence</li><li><strong>LMDB</strong> — memory-mapped key-value store</li></ul><h3>Object / Collection</h3><ul><li><strong>MapDB</strong> — Java collections with persistence</li><li><strong>Realm</strong> — mobile applications</li></ul><p>Each of these databases exists because a server-based alternative would be unnecessary or inefficient.</p><h3>Final Thoughts</h3><p>Embedded databases taught me an important lesson:</p><blockquote><em>Not every system needs to be distributed.<br> Sometimes, the simplest architecture is the most powerful one.</em></blockquote><p>They force you to think about:</p><ul><li>Storage engines</li><li>Durability trade-offs</li><li>Concurrency limits</li><li>Performance at the disk level</li></ul><p>And in doing so, they make you a <strong>better backend engineer</strong>.</p><p>If you ever find yourself spinning up a database server “just because” — <br> it might be worth asking whether an embedded database is all you actually need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b382f9def9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Mini-Netflix Backend in Java: Design Patterns in Action]]></title>
            <link>https://medium.com/@ashutoshongithub/building-a-mini-netflix-backend-in-java-design-patterns-in-action-592bcbd2f072?source=rss-617d2822745b------2</link>
            <guid isPermaLink="false">https://medium.com/p/592bcbd2f072</guid>
            <category><![CDATA[netflix-lld]]></category>
            <category><![CDATA[low-level]]></category>
            <category><![CDATA[specificartion-pattern]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <dc:creator><![CDATA[Ashutosh Kumar Singh]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 03:51:22 GMT</pubDate>
            <atom:updated>2025-07-16T06:35:57.454Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Ever wondered how Netflix manages users, movies, and playback progress across devices? In this article, I’ll walk you through a hands-on Java project where I designed a simplified backend for a Netflix-like platform. We’ll explore the architecture, the core services, and — most importantly — how <strong>design patterns like Specification and Strategy</strong> make the system flexible and robust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*UX_dp8Q2KQ864TUSz_RsNw.png" /></figure><h3>Project Overview</h3><p>The goal was to design a backend system that could:</p><ul><li>Register users and manage multiple profiles per user (think: Kids, Family, etc.)</li><li>Allow uploading and filtering of movies by actor, genre, and rating</li><li>Track and sync playback progress across devices (TV, mobile, etc.)</li></ul><p>The project is organized into three main layers:</p><ul><li>Entities: Core data models (User, Profile, Movie, Actor, PlaybackProgress)</li><li>Services: Business logic and orchestration</li><li>Repositories: Data storage and retrieval (in-memory for simplicity)</li></ul><h3>Deep Dive: Design Patterns That Power the System</h3><h4>1. Specification Pattern</h4><h4>What is it?</h4><p>The Specification Pattern lets you encapsulate business rules (criteria) and combine them flexibly. It’s perfect for filtering collections based on different, combinable criteria.</p><h4>Logic Analogy</h4><p>&gt; Think of filtering movies like building a custom playlist:</p><p>&gt; You might want only “Action” movies, or only movies with “Brad Pitt,” or only those rated above 8.0. Each of these is a filter (specification), and you can combine them to get exactly what you want — just like stacking filters in a music app.</p><h4>How it works in the project</h4><p>Specification Interface:</p><pre>public interface Specification&lt;T&gt; {<br>    boolean isSatisfiedBy(T item);<br>}</pre><p>Concrete Specifications:</p><pre>public class ActorSpecification implements Specification&lt;Movie&gt; {<br>    private String actor;<br><br>    public ActorSpecification(String actor) {<br>        this.actor = actor;<br>    }<br><br>    @Override<br>    public boolean isSatisfiedBy(Movie movie) {<br>        for(Actor actor1: movie.getActors()){<br>            if(actor1.getName().equals(actor)){<br>                return true;<br>            }<br>        }<br>      return false;<br>    }<br>}</pre><pre>public class GenreSpecification implements Specification&lt;Movie&gt; {<br>    private String genre;<br><br>    public GenreSpecification(String genre) {<br>        this.genre = genre;<br>    }<br><br>    @Override<br>    public boolean isSatisfiedBy(Movie movie) {<br>        return movie.getGenre().equalsIgnoreCase(genre);<br>    }<br>}</pre><pre>public class RatingSpecification implements Specification&lt;Movie&gt; {<br>    private String minRating;<br><br>    public RatingSpecification(String minRating) {<br>        this.minRating = minRating;<br>    }<br><br>    @Override<br>    public boolean isSatisfiedBy(Movie movie) {<br>        return Float.parseFloat(movie.getRating()) &gt; Float.parseFloat(minRating);<br>    }<br>}<br></pre><p>Combining Specifications:</p><pre>public class ANDspicification&lt;T&gt; implements Specification&lt;T&gt; {<br>    private Specification&lt;T&gt; spec1;<br>    private Specification&lt;T&gt; spec2;<br><br>    public ANDspicification(Specification&lt;T&gt; spec1, Specification&lt;T&gt; spec2) {<br>        this.spec1 = spec1;<br>        this.spec2 = spec2;<br>    }<br><br>    @Override<br>    public boolean isSatisfiedBy(T item) {<br>        return spec1.isSatisfiedBy(item) &amp;&amp; spec2.isSatisfiedBy(item);<br>    }<br>}</pre><p>Usage in Filtering:</p><pre><br>    public List&lt;Movie&gt; filter(String actorName,String genre,String rating) {<br><br>        List&lt;Specification&lt;Movie&gt;&gt; specs = new ArrayList&lt;&gt;();<br><br>        if(!actorName.isEmpty()){<br>            specs.add(new ActorSpecification(actorName));<br>        }<br>        if(!genre.isEmpty()){<br>            specs.add(new GenreSpecification(genre));<br>        }<br>        if(!rating.isEmpty()){<br>            specs.add(new RatingSpecification(rating));<br>        }<br><br>        Specification&lt;Movie&gt; finalSpec = specs.stream()<br>                .reduce(ANDspicification::new)<br>                .orElse(movie -&gt; true);<br><br>        List&lt;Movie&gt; movies = movieRepository.getMovie();<br><br>        return movies.stream()<br>                .filter(finalSpec::isSatisfiedBy)<br>                .collect(Collectors.toList());<br>    }</pre><h3>2. Strategy Pattern</h3><h4>What is it?</h4><p>The Strategy Pattern lets you define a family of algorithms, encapsulate each one, and make them interchangeable. The client can choose which strategy to use at runtime.</p><h4>Logic Analogy</h4><p>&gt; Think of playback sync like choosing a delivery method:</p><p>&gt; Sometimes you want your package delivered instantly (real-time sync), other times you want it delivered only when you’re home (on-pause sync). The delivery method (strategy) can be swapped out as needed.</p><h4>How it works in the project</h4><p>Strategy Interface:</p><pre>public interface ProgressSyncStrategy {<br>    void sync(PlaybackProgress progress);<br>}</pre><p>Concrete Strategies:</p><pre>public class OnPauseProgressSyncStrategy implements ProgressSyncStrategy {<br>    @Override<br>    public void sync(PlaybackProgress progress) {<br>        if(progress.isPaused()) {<br>            InMemoryPlaybackRepository.save(progress);<br>            System.out.println(&quot;Paused and synced&quot;);<br>        }else{<br>            System.out.println(&quot;Not paused and not synced&quot;);<br>        }<br>    }<br>}<br><br>public class RealTimeSyncStrategy implements ProgressSyncStrategy {<br>    @Override<br>    public void sync(PlaybackProgress progress) {<br>        System.out.println(&quot;Synced realtime&quot;);<br>        InMemoryPlaybackRepository.save(progress);<br>    }<br>}</pre><p>Usage in Service:</p><pre>public class PlaybackTrackerService {<br>    private final ProgressSyncStrategy syncStrategy;<br><br><br>    public PlaybackTrackerService(ProgressSyncStrategy syncStrategy) {<br>        this.syncStrategy = syncStrategy;<br>    }<br><br>    public void updateProgress(PlaybackProgress progress) {<br>        syncStrategy.sync(progress);<br>    }<br><br>    public PlaybackProgress getProgress(String userId, String videoId) {<br>        return InMemoryPlaybackRepository.get(userId, videoId);<br>    }<br>}</pre><pre>                    [PlaybackTrackerService]<br>                               |<br>                               v<br>                       +---------------------+<br>                       | ProgressSyncStrategy|<br>                       +---------------------+<br>                          /             \<br>                         /               \<br>                    [RealTimeSync]   [OnPauseSync]<br>                         |               |<br>                         v               v<br>                    [Sync Now]     [Sync Only If Paused]</pre><h3>Wrapping Up</h3><p>By leveraging the Specification and Strategy patterns, this mini-Netflix backend achieves:</p><ul><li>Extensibility: Add new filters or sync strategies with minimal code changes.</li><li>Separation of Concerns: Each class has a single responsibility.</li><li>Maintainability: The codebase is easy to understand and extend.</li></ul><p>Want to see the code?</p><p><a href="https://github.com/hskci25/Netflix-LLD">GitHub - hskci25/Netflix-LLD</a></p><h3>Let’s Connect!</h3><p>https://www.linkedin.com/in/ashutosh-kumar-singh-49baa8178/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=592bcbd2f072" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>