<?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 Vipulbest on Medium]]></title>
        <description><![CDATA[Stories by Vipulbest on Medium]]></description>
        <link>https://medium.com/@vipulbest1?source=rss-77fbc8d68e9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kwtKd-DRcUBaCSHM.jpg</url>
            <title>Stories by Vipulbest on Medium</title>
            <link>https://medium.com/@vipulbest1?source=rss-77fbc8d68e9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:41:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vipulbest1/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[Chaos of OLAP Ecosystem and some hidden patterns]]></title>
            <link>https://vipulbest1.medium.com/chaos-of-olap-ecosystem-and-some-hidden-patterns-71bee6f7c313?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/71bee6f7c313</guid>
            <category><![CDATA[clickhouse]]></category>
            <category><![CDATA[columnar-databases]]></category>
            <category><![CDATA[starrocks]]></category>
            <category><![CDATA[olap]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 10:29:52 GMT</pubDate>
            <atom:updated>2026-09-29T10:29:52.332Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Start researching an analytical database today, and you might end the day with more browser tabs than architectural clarity.</li><li>Google BigQuery, Snowflake, ClickHouse, StarRocks, Apache Pinot, Apache Doris. Then the conversation expands to open lakehouses, Apache Iceberg, Delta Lake, and query engines running over object storage. You came looking for a database. You leave evaluating an ecosystem.</li><li>For anyone who remembers the JavaScript framework explosion, the feeling is familiar. Just as you became comfortable with one framework, another appeared with a compelling explanation of what the previous generation had missed. The analytical data world can feel much the same: another engine, another benchmark, another promise of faster queries and lower costs.</li></ul><blockquote><strong>Forget keeping with AI for a moment, Keeping up with OLAP itself feels like a complex task</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*te1YMGPJw95CNwpv55F9cg.png" /><figcaption>A rich ecosystem with multiple options</figcaption></figure><p>The abundance now spans every layer of the analytical stack: storage options, analytical databases, compute engines, and open formats such as Parquet, Iceberg, and Delta Lake. As storage and compute become more independent, teams gain more freedom to combine these building blocks around their workloads. That flexibility creates room for innovation — and leaves practitioners evaluating an expanding set of combinations, each with its own performance, cost, and operational trade-offs.</p><h3>The Architectural Shifts Behind OLAP’s Abundance</h3><p>Several architectural shifts help explain why the OLAP ecosystem supports so many engines, platforms, and deployment models:</p><ol><li><strong>Cheaper, scalable object storage.</strong> AWS reported an approximately <strong>85% reduction in S3 storage pricing since its 2006 launch</strong>, illustrating how the economics of retaining large datasets have changed.</li><li><strong>Separation of storage and compute.</strong> Persistent data and query execution can scale independently. Architectures such as BigQuery’s allow compute capacity to grow with processing demand, without requiring proportional growth in storage — or vice versa.</li><li><strong>Open file and table formats.</strong> Parquet standardizes columnar files, while table formats such as Iceberg and Delta Lake add table-level metadata and transaction semantics.</li><li><strong>Freedom to choose the compute engine.</strong> With compatible formats and integrations, teams can apply different engines to shared datasets — for example, using one for batch processing and another for interactive SQL.</li><li><strong>Reusable open-source building blocks.</strong> Shared libraries and standardized representations reduce the amount of infrastructure that each new engine must implement independently. Apache Arrow, for example, provides a language-independent columnar memory format designed for vectorized processing and SIMD operations. My view is that such foundations leave more engineering effort available for optimizers, execution strategies, and workload-specific improvements.</li><li><strong>Caching that makes remote storage practical.</strong> Separating storage from compute introduces network access costs and latency. Memory and local-disk caches help compensate by keeping frequently accessed data close to execution. StarRocks’ shared-data architecture illustrates this approach, combining remote object storage with local caching and prefetching.</li><li><strong>BYOC and separation of control and data planes.</strong> Bring Your Own Cloud lets vendors offer managed software while running the data plane inside a customer’s cloud account. ClickHouse BYOC, for example, keeps storage and compute in the customer’s VPC.</li><li><strong>Workload diversity that rewards specialization.</strong> Historical scans, complex joins, streaming ingestion, and highly concurrent dashboards place different demands on a system. Those differences create room for distinct indexing strategies, data layouts, execution models, and pre-computation techniques — helping explain why multiple architectures remain useful under the same OLAP umbrella.</li></ol><h3>Coming Next: Hidden Patterns and an OLAP Decision Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvsZWVmwwtw-P7kUx2hlhA.png" /></figure><p>Beneath the abundance of OLAP products lies a recurring set of architectural choices. In the next part, we will explore these <strong>hidden patterns</strong> and turn them into a practical decision matrix:</p><ol><li><strong>Inserts vs. updates:</strong> Is your workload predominantly append-only, or does it require frequent updates and upserts?</li><li><strong>Delete workloads:</strong> Do you expire entire partitions, delete individual records, or perform large conditional deletions?</li><li><strong>Atomicity and transactions:</strong> What must succeed or fail together — a batch, a table update, or changes across multiple tables?</li><li><strong>Storage–compute separation:</strong> Do storage and compute need to scale independently, and what latency trade-offs can your workload tolerate?</li><li><strong>Indexing:</strong> Which indexing techniques support your filters and access patterns, and what maintenance costs do they introduce?</li><li><strong>Partitioning, bucketing, and clustering:</strong> How should data be organized to enable pruning, distribute work evenly, and reduce data movement?</li><li><strong>Materialized views:</strong> Which repeated computations can be precomputed, and what refresh cost and freshness lag are acceptable?</li><li><strong>Storage formats and compression:</strong> How do format compatibility, encoding, and compression affect storage footprint, scan efficiency, and interoperability?</li><li><strong>The legacy of OLAP cubes:</strong> Where do predefined dimensions and pre-aggregations still help, and where does flexible exploration take priority?</li><li><strong>Caching:</strong> What is cached — data, metadata, or query results — and how does performance change when the cache is cold?</li><li><strong>Colocated joins:</strong> Can frequently joined tables share a compatible data distribution to reduce network shuffles?</li><li><strong>When to build your own lakehouse:</strong> At what scale and workload complexity do control over data, engine flexibility, and potential cost savings justify owning the integration, governance, and operational overhead?</li></ol><p>These dimensions — and others we will explore — form a <strong>decision matrix that helps architects choose the right analytical storage and query platform for their workload</strong>, with explicit trade-offs around performance, correctness, cost, and operations.</p><blockquote><strong>Keep an eye out for Part 2, where we’ll unpack these hidden patterns and build a practical decision matrix for choosing your OLAP platform.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71bee6f7c313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Complexity of Simple Data Pipelines: Part 2 — Critical Consumption Inconsistencies]]></title>
            <link>https://vipulbest1.medium.com/the-hidden-complexity-of-simple-data-pipelines-part-2-critical-consumption-inconsistencies-966fd575cf7e?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/966fd575cf7e</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 19:40:47 GMT</pubDate>
            <atom:updated>2026-07-09T19:40:47.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deTpUjQlD65evF1zJX-m0Q.png" /></figure><p>This is Part 2 of a 3-part series on the hidden complexity of simple data pipelines.</p><p>In Part 1, I discussed <strong>publishing inconsistencies</strong> — the failures and edge cases that can happen before an event safely reaches the topic or queue.</p><p>You can read Part 1 here:<br><a href="https://vipulbest1.medium.com/the-hidden-complexity-of-simple-data-pipelines-part-1-20559a9b7f8f?sharedUserId=vipulbest1">https://vipulbest1.medium.com/the-hidden-complexity-of-simple-data-pipelines-part-1-20559a9b7f8f?sharedUserId=vipulbest1</a></p><h3>Consumer Inconsistencies: What Can Go Wrong After an Event Is Published?</h3><p>Once an event safely reaches the topic or queue, the reliability problem shifts to the consumer side. At this stage, the key question is no longer just “was the event published?” but “was the event consumed, processed, committed, and written safely?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TThlgfNKlK4DHb2koPd0Ig.png" /></figure><p>This article will talk about each of the above concerns and standard approach to design the pipeline in an ideal way. Lets get started..</p><h3><strong>1. Duplicate Consumption</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JwdONDBObpEiFaP-yDIbw.png" /></figure><ul><li>In most production systems, publishing is designed as <strong>at-least-once</strong>, not exactly-once. This means the same logical event can appear more than once in the topic/queue.</li><li>For example, Entity A Created may be present twice because of publisher retry, ACK uncertainty, broker redelivery, replay, or duplicate publishing.</li><li>If the consumer processes both copies blindly, it can create duplicate records, repeated side effects, wrong counters, or inconsistent downstream state.</li><li>The consumer should therefore maintain a <strong>de-dup store / inbox table</strong> to track events that have already been processed.</li><li>De-duplication should usually happen on a stable <strong>event_id</strong> generated by the publisher/outbox, not on payload comparison.</li><li>If event_id is not available, use a deterministic idempotency key such as:<br>source_system + entity_id + event_type + entity_version.</li><li>The consumer flow should be: <strong>receive event → check inbox/de-dup store → process only if new → mark event as processed → commit/ack message</strong>.</li><li>The safest design is: <strong>stable event identity + consumer inbox table + idempotent write to consumption DB</strong>.</li></ul><h3><strong>2. Idempotent Consumption: Why having de-dup is not enough and how de-dup key is different from idempotent key</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SK__gEWlj-l6n4m4xfLaIQ.png" /></figure><h3>3. Consumer processing Timeouts and misconfigured visibility timeout window</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lS4-Bk3FOt-Mscf8SVHXgw.png" /></figure><h3>4. Message got consumed, but dequeuing/ACK failed. So message still stays in the queue!</h3><ul><li>When processing succeeds but ACK/dequeue fails, the queue will redeliver the same message even though the side effect has already happened.</li><li>This is why consumers must not rely only on broker delivery state. The consumer should maintain its own durable processing state using de-dup/idempotency records or, better, an inbox table.</li><li>On redelivery, the consumer can safely detect that the event was already processed and skip duplicate side effects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qq5rDbJCl-wzlmOBPe6Z0A.png" /></figure><h3>5. Event consumed, but write to downstream DB Fails. (In our example, write to ElasticSearch fails)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56djsK0ac89yKE58R8z0XQ.png" /></figure><h3>6. Stale or outdated event consumption: Need for optimistic version control and a versioning store.</h3><ul><li>A version store helps the consumer remember the <strong>latest applied version</strong> for every entity, such as employee_id → current_version.</li><li>Before applying any incoming event, the consumer compares the event version with the stored version. If the incoming version is older or equal, the event is treated as stale and ignored.</li><li>This prevents older events like employeeCreated(VK, 10:00:00) from recreating or overwriting state after a newer event like employeeDeleted(VK, 10:00:05) has already been applied.</li><li>The version store can live inside the downstream DB itself, for example Elasticsearch optimistic concurrency control using _version / sequence metadata, or as a separate store like Postgres, Redis, or DynamoDB.</li><li>The ideal consumer-side reliability design is: <strong>dedup + idempotency + inbox + version store in the downstream DB</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NUHHdzAD7v_Ky3wnfnmdg.png" /></figure><h3>7. Versioning Store is great, but why cannot we get exact ordering guarantee while consumption</h3><ul><li>Exact consumption ordering is hard to guarantee in distributed systems.</li><li>Brokers can usually guarantee <strong>dequeue order</strong> within a partition, shard, or FIFO group.</li><li>But <strong>dequeue order is not the same as processing completion order</strong>.</li><li>With horizontally scaled consumers, E1 may be picked first, but E2 may finish first.</li><li>Even with the same partition/FIFO group, ordering can break if processing is parallel, slow, retried, or fails independently.</li><li>For strict ordering, use: <strong>same ordering key + one active processor per key + sequential processing + version checks</strong>.</li><li>In practice, aim for <strong>scoped ordering where needed</strong> and use <strong>versioning as the safety net</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciRyH3aB2IMBG5oGwU1hzA.png" /></figure><h3>8. Delete events missed, Ghost records remain: The need for “tombstones(deletion markers)”</h3><ul><li>A very interesting scenario where an entity is deleted in source transaction DB, but still exists on the consumption DB. The consumer decides to restore and somehow the deletion does not happen</li><li>This is a nuanced scenario that impacts a lot of data sync pipelines</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pn_mtWG5bRixJ7UlZ8m6JQ.png" /></figure><h3>9. Finally, always have a dead letter queue and parked store for manual investigation , incase of failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lY0_zdxITfzwL65rVHNKQ.png" /></figure><h3>Conclusion</h3><ul><li>Consumer-side reliability is where a simple streaming pipeline starts becoming a real distributed system problem.</li><li>Once an event reaches the topic or queue, the challenge is not just to consume it. The real challenge is to consume it safely, handle duplicates, protect downstream state, survive retries, preserve correctness during failures, and still keep the system observable and recoverable.</li><li>This is why patterns like <strong>deduplication, idempotency, inbox tables, version stores, DLQs, retry relays, and parked stores</strong> are not optional design details. They are the reliability foundation for any production-grade event consumption system.</li><li>In Part 1, we discussed <strong>publishing inconsistencies</strong>.<br>In Part 2, we covered <strong>critical consumption inconsistencies</strong>.</li><li>In Part 3, I will move beyond publisher and consumer boundaries and discuss the broader cross-domain NFRs and operational challenges: replay strategy, reconciliation, observability, schema evolution, backpressure, ownership, audits, and production recovery.</li><li>Stay tuned for Part 3.</li></ul><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=966fd575cf7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Complexity of Simple Data Pipelines: Part 1]]></title>
            <link>https://vipulbest1.medium.com/the-hidden-complexity-of-simple-data-pipelines-part-1-20559a9b7f8f?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/20559a9b7f8f</guid>
            <category><![CDATA[data-consistency]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 12:23:00 GMT</pubDate>
            <atom:updated>2026-07-09T12:23:00.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hAJ1K6_mhXCa1KI3KWF7g.png" /></figure><p>At first glance, a data streaming system looks deceptively simple: a publisher emits an event, the event lands in a topic or queue, a consumer picks it up, processes it, and finally stores the result somewhere.</p><p>But in real production systems, this simple flow quickly becomes a reliability, consistency, scalability, and operability problem. Events can be duplicated, delayed, reordered, lost, retried, partially processed, or consumed by multiple workers at the same time. Downstream stores can fail, schemas can evolve, queues can build up, and consumers can fall behind</p><blockquote>This article is not about choosing Kafka, SQS, Pub/Sub, RabbitMQ, or any specific technology.</blockquote><blockquote>Instead, the goal is to build a practical checklist of non-functional requirements that senior engineers and architects should evaluate whenever they move data from point A to point B</blockquote><h3>A Failure-First Checklist for Data Streaming Systems</h3><p>For this article, I am separating the checklist into three categories: publishing inconsistencies, consumption inconsistencies, and other reliability NFRs.</p><ul><li>Publishing inconsistencies cover failures before or during event emission</li><li>Consumption inconsistencies cover duplicate, stale, out-of-order, or partially processed events</li><li>The final category captures cross-cutting capabilities such as smart retries, replay, DLQ handling, and inbox tables that help the system recover cleanly when failures inevitably happen</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7I5xroBAhnqktVq6ZEXnjg.png" /></figure><p>This article is first part in three part series which focusses on publishing inconsistencies</p><h4>1. Event E1 Publish fails</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFupoh6eAL9NVQXqFenBMw.png" /></figure><h4>2. Publish Succeeds but acknowledgment not received</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhTiE545GL3cv0ShisvawQ.png" /></figure><ul><li>ACK reception is a critical part of the publishing contract. Until the publisher receives a successful acknowledgement from the broker, it cannot safely know whether the event was actually persisted or not.</li><li>The Outbox pattern guarantees <strong>at-least-once publishing</strong>, not true <strong>exactly-once publishing</strong>. Its main value is that the event is durably stored before publishing, so data loss does not happen even if the publisher, broker, or network fails.</li><li>The ideal solution for duplicate publishing is a combination of:<br><strong>Outbox pattern + stable event ID + bounded retries + broker-side idempotence/deduplication where supported + idempotent consumers + consumer-side inbox/dedup table.</strong></li></ul><h4>3. Duplicate Publishing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1wA86bVM0nHZE58j7RQDA.png" /></figure><ul><li>This duplicate is caused by the application/publisher logic itself, not by broker ACK uncertainty.</li><li>The same publish module may get called multiple times due to retries, race conditions, duplicate hooks, or parallel workers.</li><li>A stable event_id is required so the system can identify the same logical event.</li><li>A publisher-side de-dup store helps block the second publish before it reaches the topic/queue.</li><li>In short: <strong>stable event ID + de-dup store + idempotent consumer</strong> is the safer design.</li></ul><h4>4. Ordering Guarantees While Publishing ( Not consumption ordering!)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbeMU9aJ415qI_2ZFUHrvQ.png" /></figure><ul><li>Not every event stream needs strict ordering. For example, Employee A Created and Employee D Updated are independent events, so their relative order usually does not matter.</li><li>Ordering becomes important when multiple events belong to the same business entity or transaction. For example, in payments, Payment Initiated → Payment Authorized → Payment Captured → Payment Settled must be observed in the same sequence.</li><li>The core problem is this: even if the source DB transaction writes events in the correct order, the publishing pipeline must ensure that the same order is preserved when events reach the topic/queue.</li><li>An Outbox table helps because events can be inserted in the same DB transaction with a clear sequence, such as created_at, auto_increment_id, version, or sequence_number.</li><li>The Outbox relay should publish events in that same deterministic order, usually by polling with ORDER BY sequence_number or ORDER BY outbox_id.</li><li>But the broker also matters. If events are published to different partitions, shards, or queues, global ordering is usually not guaranteed.</li><li>For ordering-sensitive flows, all events for the same ordering scope should go to the same partition or FIFO group. The ordering key could be transaction_id, payment_id, order_id, or any entity key where sequence matters.</li><li>The practical design is: <strong>Outbox table with sequence + single relay ordering per scope + broker partition/FIFO key based on the same scope + consumer processes that scope sequentially.</strong></li><li>The goal is not global ordering across the entire system. The goal is scoped ordering: preserve order only where the business domain actually requires it.</li></ul><p>This brings us to the end of Part 1 of this three-part series on data streaming design NFRs.</p><p>In this part, we focused on publishing inconsistencies — what can go wrong before an event safely reaches the topic or queue. We looked at publish failures, uncertain acknowledgements, duplicate publishing, and ordering guarantees.</p><p>In Part 2, I will move to the consumer side and discuss critical consumption inconsistencies: duplicate consumption, idempotency, timeouts, visibility windows, stale events, failed commits, and failed writes to the consumer store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20559a9b7f8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A structured roadmap to replication in distributed systems]]></title>
            <link>https://vipulbest1.medium.com/a-structured-roadmap-to-replication-in-distributed-systems-dc5b2e22b381?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5b2e22b381</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 12:05:43 GMT</pubDate>
            <atom:updated>2026-02-27T12:05:43.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ly2dqUVq7aEpjF8ffAlcNw.png" /></figure><h4>Introduction — Why Replication Deserves a Structured Understanding</h4><ul><li>Today, almost every serious backend system we build is distributed.</li><li>Whether it’s a micro-services architecture running on Kubernetes, a globally replicated database like DynamoDB, a Kafka cluster handling event streams, or a data lake backed by object storage — we are operating in a distributed world by default.</li><li>This blog is not about explaining replication at a surface level. It is about building a <strong>structured mental framework</strong> to reason about replication in distributed systems.</li></ul><blockquote>Instead of memorizing how “System X does replication,” we will discuss:</blockquote><blockquote><strong>How to think about replication as a systems architect so that you can form your own informed opinions about different replication strategies and confidently reason about which model is right for your system.</strong></blockquote><h4>A Visual Roadmap to Replication</h4><ul><li>I’ve created a diagram that represents the structured roadmap of replication concepts covered in this article.</li><li>The topics are intentionally numbered — I encourage you to follow them in order, as each concept builds on the previous one.</li><li>Use this diagram as a mental map when thinking about replication. My hope is that it helps you approach replication with structure and clarity — especially when designing systems or choosing the right database and components.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwfbO_tkYiBsjSVz-lgtaA.png" /><figcaption>Mental Map when thinking about replication</figcaption></figure><h4>Replication Strategies — The Three Major Models</h4><p>At a high level, most replication approaches in distributed systems fall into <strong>three fundamental categories</strong>:</p><ul><li><strong>Single Leader Replication</strong></li><li><strong>Multi Leader Replication</strong></li><li><strong>Leaderless Replication</strong></li></ul><p>Lets dive into each of the three models. As I mentioned, in this blog we will cover all the important topics for each of these replication models</p><h3><strong>Single Leader Replication:</strong></h3><ul><li>One of the node is designated as the leader and other nodes are simple followers/replicas. The leader, you might also hear it called the master or primary</li><li>Leader is the single point of entry for anything that changes the data. All the write queries are handled by the leader.</li><li>Imagine a user, let’s say user 1234, updates their profile picture,that write request, it hits the leader.The leader updates his own database, sure, but it also creates a really detailed record of that change. We’re talking about which table, the specific row via its primary key, what column change, the old value, the new value, even a transaction ID to keep things ordered.It’s like a super precise log</li><li>And this log with all recorded changes, get streamed out to all the follower replicas</li></ul><blockquote>So all the replicas are synced with the changes done on the master/leader. but the interesting question is : How does the replica get all the changes.</blockquote><p>Replica Syncing also has 3 important models</p><h4>Synchronous Replication</h4><ol><li>The leader , once it has committed the write in its own store, will push the changes to all replicas. Which means: the client get a write acknowledgment only after all the nodes (leader + replicas) have executed the operation.</li><li>It is great for durability. If the leader suddenly fails, you’re pretty confident that the latest write is safe on replicas.</li><li>But there’s a big downside.<br>a. Latency! And what if that sync follower/replica has a problem, like network issue.<br>b. Performance and availability are the downside.<br>c. If the follower has network issues, leader will keep waiting on the follower to commit and it will lead to failed write operation.</li></ol><h4><strong>Asynchronous Replication</strong></h4><blockquote>Asynchronous is more like fire and forget.</blockquote><p>1. The leader sends the update out to the followers, but it doesn’t wait around. It assumes that the replicas will eventually catch up and get synced with all the changes<br>2. Much lower latency for writes is a huge plus. The leader stays responsive,even if followers are lagging a bit or having temporary network hiccups.<br>3. But the trade-off is : weaker consistency, meaning if the leader fails after telling the user the write was successful, but before that change actually made it to all the asynchronous followers, you could lose that write.</p><h4>Semi Synchronous Replication</h4><blockquote>Let the data get committed on at least N nodes to maintain a fine balance between consistency, durability and latency!</blockquote><ol><li>Lets say you have a distributed system with one leader and 3 replicas.</li><li>Semi Sync Replication allows us to have a control by configuring that the write must be synchronously synced to alreast n nodes. If n is 2, it means, the write must be committed to the leader and one replica. Other replicas can be asynchronously synced</li><li>This strategy allows us to maintain a fine balance between data consistency and write availability and latency</li><li>At a broader level, this idea aligns with the <strong>quorum principle</strong>, where stronger consistency can be achieved by ensuring:</li></ol><blockquote>W + R &gt; N,</blockquote><ul><li>W = number of replicas that must acknowledge a write</li><li>R = number of replicas consulted during a read</li><li>N = total number of replicas</li></ul><h3>Handle Failure in Single Leader Replication</h3><blockquote>One of the fundamental goal of distributed systems: <strong>system resilience despite component failures</strong></blockquote><h4>Scenario 1: Follower Crashes</h4><p>Let’s start with a relatively simple scenario: what happens if a follower node fails?</p><ul><li>In a leader-based replication setup, each follower maintains its own local log of the data changes it receives from the leader. This log represents the follower’s history of processed updates.</li><li>If a follower crashes or temporarily loses its connection to the leader, it stops receiving new updates. However, when the follower restarts or the network connection is restored, it can check its local log to identify the last successfully processed change.</li><li>The follower then reconnects to the leader and requests all updates that occurred after that point. In other words, it asks for the changes it missed while it was offline.</li><li>The leader responds by sending those missing updates. Once the follower processes them, it becomes fully synchronized again and resumes receiving the ongoing stream of changes.</li><li>This catch-up mechanism makes follower recovery relatively straightforward and helps minimize disruption to the overall system.</li></ul><h4>Scenario 2: Leader Crashes</h4><p>When the leader fails, the system enters a more complex process called <strong>failover and leader-reelection . This has three phases</strong></p><p>1. Detect the Leader Failure</p><ul><li>Nodes periodically exchange heartbeat messages.</li><li>If the leader does not respond within a configured timeout (for example, 10–30 seconds), the other nodes assume it has failed.</li><li>Failure detection sounds simple, but in distributed systems, it is tricky. A slow network, temporary partition, or overloaded node can make a healthy leader appear dead.</li></ul><p>2. Choose a New Leader</p><ul><li><strong>Election-based approach</strong>: Followers vote, and the one with majority support becomes the new leader.</li><li><strong>Controller-based approach</strong>: A designated controller node selects and appoints a new leader.</li><li>However, getting distributed nodes to agree on a new leader is a fundamental challenge known as the <strong>consensus problem</strong>. Because networks are unreliable and nodes may fail independently, achieving agreement safely is non-trivial.</li></ul><p>3. Reconfigure the System</p><ul><li>After a new leader is selected, the system must redirect all write traffic to it. Clients, services, and routing layers need to update their understanding of which node is responsible for writes.</li><li>A critical concern arises if the old leader comes back online. It must <strong>not</strong> resume leadership automatically. Instead, it must step down and rejoin as a follower.</li><li>If the old leader continued accepting writes, the system could end up with split-brain — two leaders accepting conflicting writes — leading to serious data inconsistencies.</li></ul><blockquote>Hey, “Split Brain sounds interesting and dramatic as well. What is this?”</blockquote><ul><li>A <strong>split-brain</strong> scenario occurs when different nodes in the system incorrectly believe they are the active leader at the same time.</li><li>Think of it like two generals both assuming command and issuing conflicting orders. In distributed systems, this means two leaders accepting writes independently — a direct threat to data integrity.</li><li>The Subtle Risk: detecting split-brain reliably is difficult.If the detection logic is flawed:<br>a. Both nodes might mistakenly believe another leader exists and shut themselves down.<br>b. The system could go fully offline even when only one node actually failed.</li><li>In other words, the safeguard itself can trigger an outage.</li><li>This highlights the delicate balance between automated protection and system availability. Even leader-failure timeouts (e.g., 10–30 seconds) must be carefully tuned — too aggressive, and you risk false elections; too slow, and failover becomes sluggish</li></ul><h3>Multi Leader Replication</h3><ul><li>In multi-leader replication, <strong>multiple nodes have write authority</strong>. Each leader can accept writes independently, and changes are propagated between leaders.</li></ul><p>Why Do We Need Multi-Leader Replication?</p><ul><li>The leader becomes a <strong>single write bottleneck</strong>.</li><li>If the leader disconnects, write operations stop until failover and leader-reelection completes.</li><li>Even in a sharded database, each shard (e.g., S1) still has its own single leader — so if that shard leader fails, writes to that shard are disrupted.</li></ul><p>How Multi-Leader Works: If we have two masters, <strong>M1 and M2</strong>:</p><ul><li>Both can accept writes.</li><li>Each acts as a leader for its local clients.</li><li>Changes written to M1 are replicated to M2.</li><li>Changes written to M2 are replicated to M1.</li></ul><blockquote>Replication between leaders is typically asynchronous.</blockquote><p>When Do We Need Multi-Leader Replication?</p><ol><li>Multi-Region Deployments</li></ol><ul><li>Consider a database deployed across <strong>EU, US, and APAC</strong>. Each region has its own local leader. Writes are committed locally and then asynchronously propagated to other regions.</li><li>This provides:<br>a. Lower regional write latency<br>b. Better tolerance to cross-region network interruptions</li></ul><p>2. Offline-Capable Applications</p><ul><li>In some systems, each client device maintains its own local database that acts as a master.</li><li>When the device reconnects to the internet, its changes are asynchronously replicated to other masters (e.g., a central database).</li></ul><p>3. Real-Time Collaboration Systems</p><ul><li>Applications like <strong>Google Docs</strong> allow multiple users to edit the same document simultaneously.</li><li>Each client may commit changes locally, and those changes must be propagated to others.</li></ul><h4><strong><em>One of the main challenge in Multi Leader Replication: How do we maintain consistency with concurrent writes across multiple leaders without strict locking? And how do resolve conflicts especially when there are multiple writers!</em></strong></h4><ul><li>Complexities with multi leader replication<br>a. Too much complexity and overhead in monitoring and deployment<br>b. Data consistency<br>c. Maintaining orders</li></ul><h4>Conflict Resolution in Multi Leader replication</h4><p>When multiple leaders can accept writes, <strong>conflicts are inevitable</strong>.</p><p>The real question is not <em>whether</em> conflicts happen — but <em>how they are resolved</em>.</p><ol><li><strong>Last-Write-Wins (LWW)</strong></li></ol><ul><li>Whichever write has the latest timestamp overwrites the previous value.</li><li>But there is a problem: An older write can arrive later due to network delays. In that case, a “logically older” update might overwrite a newer one.</li><li>To make LWW safe, the system must rely on <strong>strict and reliable ordering guarantees</strong>, which are difficult in distributed environments</li></ul><p><strong>2. Replica/Leader Priority (Higher ID Wins)</strong></p><ul><li>Each leader is assigned a unique ID.</li><li>If conflicting writes occur, the system resolves the conflict by favoring the leader with the higher (or predefined priority) ID.</li><li>This avoids timestamp dependence but suffers from the same core issue as LWW: “The “winning” write may not reflect the user’s intended final state.”</li></ul><p><strong>3. Record and Delegate Conflict: Simplest and some thing that makes sense in a lot of applications</strong></p><ul><li>Instead of automatically resolving conflicts, the system detects and records them.</li><li>If M1 writes v1 to object O1 and M2 concurrently writes v2, the system stores both versions and marks the object as conflicted</li><li>The application code resolves the conflict OR the system presents both versions to the user for manual resolution</li></ul><p><strong>4. CRDTs (Conflict-Free Replicated Data Types)</strong></p><ul><li>CRDTs are specially designed data structures that can merge concurrent updates automatically and deterministically — without coordination.</li><li>They are mathematically structured so that replicas eventually converge to the same state.</li><li>Would request users to read their research papers and related articles on CRDTs</li></ul><p><strong>5. Operational Transformation (OT)</strong></p><ul><li>Instead of resolving final values, OT transforms operations themselves.</li><li>Each incoming operation is adjusted relative to other concurrent operations so that the final state remains consistent.</li><li>This shifts the focus from “which value wins?” to: “<strong><em>How do we transform concurrent operations so they all make sense together?</em></strong>”</li></ul><h3>Leader-Less Replication</h3><ul><li>In leaderless replication, there is <strong>no designated leader</strong> responsible for coordinating writes. Instead, clients send read and write requests directly to multiple replicas.</li><li>Each Node can accept writes independently, and consistency is achieved using <strong>quorum-based coordination</strong> rather than a central authority.</li></ul><blockquote>Ok!. But How….?</blockquote><ul><li>No single node controls writes</li><li>Clients write to <strong>W replicas</strong> and read from <strong>R replicas</strong></li><li>Consistency is enforced using quorum rules such as: W+R&gt;N<br>where N = total number of nodes, R = nodes consulted during reads and W = write acknowledgments required</li><li>If read and write quorums overlap, the system can provide strong consistency without a leader.</li></ul><p>Leaderless replication shifts the design question from:</p><p>“Who is the leader?”</p><p>to</p><p>“How many nodes must agree for read and write operations?”</p><p>I would like to end this article with one of the interesting concepts in leader -less replication i/e Sloppy Quorum and Hinted Handoff</p><h4>LeaderLess Replication: Sloppy Quorom and Hinted Handoff</h4><ul><li><strong>Sloppy quorum</strong> allows read and write requests to be handled by any <strong>W reachable nodes for writes</strong> and any <strong>R reachable nodes for reads</strong>, even if those nodes are not the originally designated replicas for that particular piece of data.</li><li>If the server that is supposed to store data <strong>D1</strong> is unreachable, the system will still write <strong>D1</strong> to other available <strong>W nodes</strong>, even if those nodes are not the designated replicas for D1.</li><li>For example, Node <strong>Ny</strong> may temporarily store D1 even though it is not the intended shard for that data.</li></ul><p>Advantages</p><ul><li>Increased write availability. Even if the leader to which D1 should be written is down, the write still succeeds, because that write is done on other available node designated for write.</li></ul><p>Trade-Offs of Sloppy Quorum &amp; Introduction to Hinted Handoff</p><ul><li>One downside of sloppy quorum is the possibility of <strong>stale reads</strong>.</li><li>If the primary node responsible for data <strong>D1</strong> is down, the write may be temporarily stored on another node (e.g., <strong>Ny</strong>). However, until D1 is transferred back to its original designated node, some reads may not reflect the latest value.</li><li>When the original node comes back online, the temporarily stored updates are transferred back to it. This process is known as <strong>hinted handoff</strong>.</li><li>Hinted handoff improves availability by allowing writes to succeed during failures, but it introduces a window of potential inconsistency — where different replicas may temporarily hold different versions of the data.</li><li>This is the fundamental trade-off:</li></ul><blockquote>“Sloppy quorum favors availability, but at the cost of temporary inconsistency.”</blockquote><h3>Final Thoughts</h3><ul><li>This article aimed to cover the most important foundational concepts behind replication in distributed systems</li><li>The goal was not just to explain how different systems implement replication, but to provide a <strong>structured way to think about it</strong>.</li><li>I hope this article gives you a clearer mental framework to reason about replication — and helps you approach distributed system design with more structure, confidence, and curiosity.</li></ul><blockquote><strong><em>Replication is complex.<br> But with the right structure, it becomes understandable — and designable.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5b2e22b381" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Engineering Decisions behind introducing transactions in AWS DynamoDB]]></title>
            <link>https://vipulbest1.medium.com/engineering-decisions-behind-introducing-transactions-in-aws-dynamodb-3466a89af4e5?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3466a89af4e5</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[scale]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 18:39:51 GMT</pubDate>
            <atom:updated>2025-10-07T18:41:30.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sWkTnaghw6woEe4HtF6Fw.png" /></figure><p>Ten years ago, I was working on a mission-critical cloud platform with one uncompromising requirement: <strong>data consistency</strong>.<br> Performance could slide, scale could wait — but <strong>ACID</strong> had to hold, no matter what.</p><p>We lived and breathed finely normalized schemas, carefully designed associations, and layers of <strong>pessimistic locking</strong> to prevent even the slightest data anomaly. Every transaction was sacred; every constraint enforced.</p><p>Fast-forward to around <strong>2018</strong>, and the world had flipped.<br>The new mantra was simple: <strong>Scale. Scale. And scale some more.<br></strong>Our systems were ingesting <strong>10+ million records per day</strong>, and read traffic was growing exponentially. Traditional RDBMSs started to crumble under the pressure — vertical scaling hit its limits.</p><p>That’s when we turned to <strong>NoSQL</strong>.<br>Simple, schema-light <strong>key–value stores</strong> that could shard and distribute data seamlessly across clusters. The focus shifted from strict consistency to <strong>high availability, low latency, and horizontal scalability</strong> — and it worked.</p><blockquote><strong><em>And then I built systems which had even more stricter requirements: “</em>Unbounded Scale and ACID Guarantees , both!<em>”</em></strong></blockquote><p>Most NoSQL databases struggled here. MongoDB added multi-document transactions; Cassandra introduced lightweight transactions. They helped — but only to an extent.</p><p>And then came a database that <strong>quietly nailed both worlds</strong> — <br> designed for web-scale workloads, yet capable of delivering <strong>fully atomic, consistent, isolated, and durable</strong> operations across distributed partitions.</p><blockquote><strong><em>And that database was AWS DynamoDB!</em></strong></blockquote><h4><strong><em>Agenda of this article is to explain how AWS DynamoDB give you all “Scale”, “Flexible Schemas”, Distributed Sever less Scaling ,Sharding, predictable performance and “ACID” as well!</em></strong></h4><p>Before we deep dive, have a look at the below stats</p><p>“In 2022, During Prime Day, DynamoDB served at a peak of 102 Million Requests per second, delivering single digit millisecond response, while maintaining high availability”</p><p><em>So the challenge was to “Provide and retain the same performance i.e. around 100 Million request per second with single digit millisecond response with ACID” i.e. even if all those requests are transactional requests, the response time should not change.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o3RBy5ZuXZTvl9MQdbKclg.png" /></figure><p>So lets deep dive into how AWS team added ACID and what were the architectural choices and tenets that were prioritized</p><blockquote><strong>1. Decision 1: Transaction is sent as one single request in DynamoDB</strong></blockquote><p>a. In traditional RDBMS, transaction has been designed as one single unit of work containing multiple operation.<br>b. In RDBMS, each individual operation within transaction is submitted individually over the network<br>c. A single TCP connection is maintained between client and RDBMS.<br>Each operation is sent as a fresh request over the same TCP connection<br>So it follows the classic design, of one TCP connection and multiple requests over the same TCP connection.<br>d. In DynamoDB, all operations are sent together in one single HTTP API call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eimiepljuJK8r7tKL-5qkg.png" /><figcaption>Each operation is a separate network request in RDBMS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwroZS2RLlchoveESL5Afw.png" /><figcaption>All operations of a transaction are bundled into one single unit and sent to DynamoDB in one single http call</figcaption></figure><blockquote><strong>2. Decision 2: AWS uses a transaction coordinator service for all transactional queries.</strong></blockquote><p>. All transactional requests go through the coordinator service. <br>. All non-transactional requests like individual “gets” and “puts” by-pass coordinator service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8S47aXFUdVnAQ5yWmaObw.png" /></figure><blockquote><strong>3. Decision 3: DynamoDB does not use MVCC (Multi Version Concurrency Control) which means there is only one version of a record present at any point in time. (I think a very well balanced decision)</strong></blockquote><p><strong>MVCC = Multi-Version Concurrency Control<br></strong>Every write creates a <em>new version</em> of a row (often with a commit timestamp).<br>Old versions stay around so that readers can see the database “as of” their transaction’s start time.<br>That’s how Postgres/MySQL/InnoDB give <strong>snapshot isolation</strong>:</p><ul><li>Reader gets the version that existed when it started, even if writers commit newer versions later.</li><li>The cost: storage overhead (multiple row versions), and a background vacuum process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKY0SKB99gz0aupRQYDalQ.png" /><figcaption>MVCC followed by multiple innoDB based databased like Mysql, Postgres!</figcaption></figure><blockquote><strong><em>DynamoDB doesn’t use MVCC. It uses a single version storage model</em></strong></blockquote><p>. DynamoDB updates the item in place!<br>. It stores exactly one version of each item — the latest committed state.<br>. <strong><em>Log Sequence Number</em></strong>: Each time an item in DynamoDB is written or updated, it receives a new <strong>Log Sequence Number (LSN)</strong> — a strictly monotonically increasing commit marker. LSN serves as the item’s version token.</p><p>Now, Refer below Diagram to understand a how simple write/update of an item happens in DynamoDB. <strong><em>Do note, how the LSN changes post the update!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oD55YhnVPNL36tacVL-hgg.png" /><figcaption>NO MVCC in DynamoDB. In Place updates of the same item!</figcaption></figure><blockquote><strong>4. Decision 4: TransactionWriteItem Protocol: AWS choose the battle tested protocol of 2PC i.e two phase commit protocol to execute a distributed transaction across distributed nodes.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mQSL9NorA8K5O8YXyMfRg.png" /><figcaption>Flow Diagram of how a Write transaction is executed using a two phase commit protocol</figcaption></figure><p>Lets go through each step of the above flow diagram</p><p><strong><em>Step 1:</em></strong><em> </em><br>. The user application calls the <strong>AWS SDK API</strong>, assembling all write operations (e.g., PutItem, UpdateItem, DeleteItem) into a single TransactWriteItems request.<br> . The SDK packages the operations, assigns client-side identifiers, and sends one atomic request to DynamoDB.</p><p><strong><em>Step 2:</em></strong><br>. The SDK transmits the composed <strong>TransactWriteItems payload</strong> (containing op1, op2, …) over HTTPS to the DynamoDB service endpoint.<br> . This request represents the <em>entire transaction</em> — DynamoDB treats it as a single atomic unit rather than multiple sequential writes.</p><p><strong><em>Step 3:</em></strong><br>. The <strong>Request Routers</strong> receive the transaction and inspect each item’s <strong>partition key</strong> to determine which internal <strong>storage node cluster</strong> holds the data.<br> . The router forwards the request to the <strong>Transaction Coordinator</strong> that will orchestrate the two phase commit protocol</p><p><strong><em>Step 4:<br>. </em></strong>The coordinator breaks the transaction into per-partition sub-operations.<br> For example, op1 targets items on <strong>Storage Cluster 1</strong>.<br> . The coordinator begins a distributed <strong>two-phase commit</strong>, starting with a <em>prepare</em> message to those nodes.</p><p><strong><em>Step 5:</em></strong> <br>. Each storage node participating in <strong>Cluster 1</strong> runs through the standard phases:<br>. <strong>Prepare</strong> — verify preconditions, acquire short-term write locks, and reserve space.<br>. <strong>Accept/Reject</strong> — reply to coordinator with readiness status.<br>. <strong>Execute</strong> — once all participants are ready, apply the write to their local replicas.<br>. <strong>Complete</strong> — acknowledge durable commit back to the coordinator.</p><p><strong><em>Step 6, Step 7:</em></strong> Similar protocol for Ops2 is executed on storage node 3</p><p><strong><em>Step 8:<br>. </em></strong>After receiving successful completion from all involved partitions, the <strong>Transaction Coordinator</strong> finalizes the transaction log and returns a <strong>single success response</strong> to the <strong>Request Router</strong>, which in turn responds to the SDK.<br> . <em>The SDK unpacks the result and marks the transaction as </em><strong><em>atomically committed</em></strong><em> — all operations succeeded together or none were applied.</em></p><blockquote><strong>5. Decision 5: TransactionReadItem: Read transactions are performed using a slightly tweaked version of two-phase protocol which AWS devised: Two phase “writeLess” Protocol.</strong></blockquote><p>DynamoDB offers <strong>read transactions</strong> that guarantee <em>serializable isolation</em> — meaning the reads see a perfectly consistent snapshot, even across partitions, <strong>without doing writes</strong>.</p><p><em>But in distributed storage, guaranteeing that without locking or timestamp writes is tricky. So DynamoDB invented a </em><strong><em>“two-phase write-less protocol.”</em></strong><em><br> It’s like a two-phase commit, but for read-only transactions.</em></p><p>Let me explain the same in better words<br>. AWS DynamoDB must ensure “serializable” consistency so that all items are read from a single, stable snapshot<br>. But as mentioned before, DyanamoDB does not store MVCC and does not persist read timestamp. So can it gurantee a stable snapshot?<br>. <strong><em>It solves this by doing two round of reads and comparing “Log Sequence Number” for each item</em></strong><br>. <em>If LSN changes in between the two reads, then the transaction aborts and retries</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cw6rgi3B5N9yrTV1rd6Zng.png" /></figure><blockquote><strong>6. Decision 6: No Locks! Locking limits concurrency and leads to deadlocks. AWS team decided to go with simple version based Optimistic Concurrency Control</strong></blockquote><blockquote><strong>7. Decision 7: Ordering of transactions using timestamps. This is serialization. Though serialization is not new, AWS has twisted the timestamp ordering to be compatible with key/value store</strong></blockquote><p>This is one of the critical decision related to ordering of transaction that guarantees serializability.<br>Since this is a wider topic, it will need more in-depth explanation for which please look out for Part 2 of this blog.</p><blockquote><strong><em>Simple architectural decisions like have a transaction coordinator, Not using MVCC etc helped DynamoDB team to maintain predictable and consistent performance at a very high scale, even for transactional requests.</em></strong></blockquote><blockquote>The lesson for us: keep the core path simple, choose only what you truly need, plan for tail latency, and make trade-offs obvious to everyone.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3466a89af4e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding NodeJs Event Loops, Phases and beyond…(Part1)]]></title>
            <link>https://vipulbest1.medium.com/understanding-nodejs-event-loops-phases-and-beyond-part1-e87f40d0e3c6?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e87f40d0e3c6</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[queue-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prioritization]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 18:58:22 GMT</pubDate>
            <atom:updated>2025-01-14T18:59:11.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJ91yLhUK13THuIrG_Q8AA.png" /><figcaption><strong>Well… you see, the Event Loop is one busy multitasker!</strong></figcaption></figure><h3>Target Audience</h3><p>This article is designed for engineers who have practical experience working with Node.js but feel there is an academic gap in their understanding of the Event Loop.</p><p>While it dives into advanced concepts, it remains approachable for beginners who are curious to gain a deeper understanding of how Node.js handles asynchronous operations.</p><p>Whether you’re looking to solidify your knowledge or take your skills to the next level, this article aims to provide clarity and insight.</p><h3>High level Definition of NodeJs Event Loop</h3><p>Different engineers, based on their experiences, often describe the “Node.js Event Loop” in various ways.</p><blockquote>From my perspective, <strong><em>the Event Loop is a singular process operating on a single thread that functions as a remarkably intelligent queue manager</em></strong>. It adeptly consumes, processes, and prioritizes messages and tasks from multiple queues, ensuring smooth operation.</blockquote><blockquote>This is where the true magic of Node.js lies. The Event Loop’s intelligence in prioritizing the <strong><em>“execution of messages from multiple queues”</em></strong> forms the core of its non-blocking nature, enabling it to handle asynchronous operations seamlessly and efficiently.</blockquote><h3>Event Loop is a smart task processor. So what are those tasks which it processes</h3><p>Lets first get a clarity on all the different types of Tasks that event loop manages.<br>Tasks are categorized broadly into below</p><ol><li><strong>MacroTasks</strong> =&gt; includes all your IO operations, callbacks, timers etc.</li><li><strong>Microtasks</strong> =&gt; includes process.nextTick, Promises.then.catch.finally etc.</li></ol><p>Lets pause here for a couple of minutes and again summarize it.</p><ol><li><em>Event loop is a very smart task manager that executes tasks which are distributed across multiple queues</em></li><li><em>Tasks are broadly divided into “microtasks” and “macrotasks”</em></li><li><em>Now lets go ahead and understand “macrotasks” and “microtasks” by taking an example of Sprint Board..Yes our very own agile sprint board.!</em></li></ol><h3>Understanding Macrotasks and Microtasks Through a Jira Scrum Board Analogy 😃</h3><p>Let me take a minute to give a simple analogy of macrotasks/microtasks by taking an example of jira board.</p><blockquote>Please refer the below diagram which represents a typical 3 day sprint plan for a feature. Please note its a 3 day sprint. So on day 4, the sprint restarts…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6YOtwS2lnDmy3szDpGYuVQ.png" /></figure><p>Allow me a couple of minutes to explain the above diagram.</p><p>You , “dear reader” is the star engineer who is working on a very important feature.</p><p><em>Day 1 of sprint -&gt; you would execute api tasks</em></p><p><em>Day 2 of sprint -&gt; you would execute DB modelling tasks</em></p><p><em>Day 3 of sprint -&gt; you would execute let say “UI tasks”</em></p><p>So the first three days of the sprint ,things go as planned. Each day is dedicated to a certain section(Api/DB/UI) of the feature .</p><blockquote>Now lets say you restart sprint on Day 4 and as planned, you are about to pick up a task from api board.</blockquote><blockquote><strong>But before you start work, you get to know there is a customer bug which is creating a lot of bad impact on the business.</strong></blockquote><p><strong><em>So what do you do now?</em></strong></p><blockquote>You jump/switchContext and dePrioritise the “UI” phase tasks and fix the customer Bug first!!</blockquote><p>So this was a very unexpected stuff that you did not plan for. But this was a learning.</p><blockquote>You now understand that anticipating and planning for customer defects is an important part of the sprint.<br>So you decide to go through tasks for each days, but before starting the day , you check the customer Bug Board to see if there is any burning customer issue. And you do this now repeatedly at beginning of each day .</blockquote><h3>Wait, I Came Here to Learn About the Event Loop, Not Sprint Planning… Right?</h3><p>Dear readers, so if you understood the above sprint structure, below is the analogy and comparison with event Loop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZqWSanh6j8d8lTXTcoyrw.png" /><figcaption><strong>Comparison of terms for jira vs nodeJs Event Loop Analogy (vk)</strong></figcaption></figure><p>So you as a star engineer is capable of doing very efficient context switching between each phases/days of the sprint and prioritize tasks to make sure</p><ol><li>performance of the sprint deliverable is not impacted. Basically feature is delivered on time</li><li>You know how to context switch between phases (each day). Lets say tasks for apis are done on Day 1 by lunch time, so you can context switch to DB tasks post lunch on Day1</li><li>Now you also know when to stop everything and concentrate on customer bugs (microtasks)</li></ol><h3><strong>Now that we understood the important terms with the sprint board analogy, lets deep dive into the actual phases that holds all the macrotasks</strong></h3><p>Please pause here for a moment and understand the below relation again :</p><blockquote>“Each macrotask belongs to a phase , and each phase has a dedicated queue.”</blockquote><blockquote><strong><em>“macro task” -&gt; belongsTo -&gt; “phase” -&gt; hasA -&gt; “dedicated Queue”</em></strong></blockquote><p>Below are the different phases which event loop(our smart queue processor) iterates over periodically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtImNbk8hY4Ldqhd88Y4cw.png" /></figure><h3><strong><em>Timers Phase (has a dedicated Timers queue)</em></strong></h3><p>a. Any function which will be executed in future using setTimeout or setInterval will be placed into Timer queue.</p><p>b. All callbacks from setTimeout and setInterval are enqueued in the timers phase queue.</p><p>c. These callbacks are not executed until their delay threshold has been met.</p><p>d.The event loop enters the timers phase and processes these callbacks only when it reaches this phase in the loop cycle.</p><h3><em>Poll Phase(has a dedicated Poll queue)</em></h3><p>a. Most non-blocking I/O operations (e.g., file system operations, network requests) are processed in the poll phase.</p><p>b. Their associated callbacks are queued in the poll phase queue once the I/O operation is complete. -&gt; Please give attention to this line.<br>So lets say ` fs.readFile()` which is an asyn IO operation and the callback function to executed once this ` fs.readFile()` completes, both are enqueued into Poll phase</p><h3>Pending CallBack Phase (has a dedicated pendingCallback queue)</h3><p>a. This phase is used to handle callbacks for deferred system-level operations. These operations are generally low-level and related to errors or specific events that some systems (e.g., Unix-like systems) handle differently.</p><p>b. It’s not as commonly encountered as other phases like timers or poll because it deals with edge cases, such as: TCP socket errors like ECONNREFUSED (e.g., when trying to connect to an unavailable server), DNS lookup issues, Other system-level callbacks</p><h3>Check Phase (has a dedicated check queue)</h3><p>a. The check phase provides an opportunity for the event loop to execute setImmediate() callbacks immediately after the poll phase.</p><p>b.It ensures that certain callbacks (like setImmediate) don’t have to wait for the next tick of the event loop.</p><p>c. Unlike setTimeout, which operates in the <strong>timers phase</strong>, setImmediate is executed in the <strong>check phase</strong>, which comes <strong>immediately after the poll phase</strong>.</p><h3>Close Callback Phase (has a dedicated closeCallbackQueue)</h3><p>a. The <strong>close callbacks phase</strong> is the final phase of the Node.js event loop and is responsible for handling cleanup tasks related to abruptly closed sockets or other handles.</p><p>b.If a resource like a TCP socket is forcibly closed using methods like socket.destroy(), Node.js schedules the ‘close’ event to be emitted during the <strong>close callbacks phase</strong>.</p><p>c. This phase ensures that any registered listeners for the ‘close’ event (e.g., socket.on(‘close’, …)) are executed.</p><p>d. If the socket or handle is closed <strong>gracefully</strong> (e.g., through socket.end()), the ‘close’ event is <strong>not deferred to the close callbacks phase</strong>.</p><blockquote>Cool. So we now, know all the macrotasks and the different queues/phases in which they reside. But there must be some rules or order in which eventLoop must be processing “macrotasks” from these queues!<br>Because if there are no rules, no orders, then there will be chaos.</blockquote><blockquote>And this is where the magic happens. EventLoop makes sure there is no chaos. Each queue is given the perfect time and priority to get serviced and context switching rules from one queue to another are designed to make sure that performance is not impacted.</blockquote><p>The Node js event loop design can teach us a lot about designs where we have one single container processing multiple queues. So some queues might have high priority tasks, another queue might have lower priority tasks, May be there is one queue which is a showStopper.<br>If any task is enqueued in this queue, then every current operation should stop and the showStopper task must be serviced at the earliest. <br><strong><em>By now, I am sure you would have got the gist of it.</em></strong></p><h3>Lets now divert our attention for a bit to “Microtasks”</h3><blockquote>Microtasks provide a unique mechanism within the Event Loop to execute tasks that are deemed highly important, even among all pending macrotasks. They ensure that urgent operations, such as resolving promises or executing process.nextTick, are addressed immediately after the current operation completes and before moving to the next phase</blockquote><p>This allows the Event Loop to reevaluate its state and handle critical updates that might otherwise be overlooked due to the sequential nature of macrotask phases. By giving microtasks such priority, Node.js guarantees responsiveness and precision in handling asynchronous tasks.</p><p>So think of microtasks as an opportunity to remind nodejs event loop that there is something really critical and burning which needs attention. For example, as a software enginner i might be working on the planned jira tickets for a feature(macrotasks), but every morning i check first if there is any customer issue(microtasks) . And if there is any customer issue(microtask), I have to first solve that and then get back to the planned jira tickets(macrotasks)</p><p>This is very similar to our sprint board analogy where the engineer(eventLoop) always checked the customerBugBoard(Microtask Queue) for any customer issues (microtasks)</p><p>If it found any microtask/customerIssue -&gt; <strong><em>stop everything and fix the bug….!</em></strong></p><p>And that wraps up Part 1 of our deep dive into the Node.js Event Loop! But we’re just getting started. Follow and Stay tuned for upcoming parts, where we’ll explore:</p><ol><li>How the Event Loop efficiently handles context switching between multiple queues.</li><li>A detailed example of task prioritization across different phases, including a comparison of process.nextTick (queued in the microtask queue) versus setImmediate (queued in the macrotask queue of the check phase).</li><li>How timers like setTimeout and setInterval interact with the Event Loop and what really happens when their thresholds are met.</li><li>The nuances of I/O callbacks and their role in the poll phase.</li><li>Common pitfalls and performance bottlenecks related to the Event Loop — and how to avoid them.</li><li>Advanced use cases: Breaking down long-running tasks to prevent Event Loop blocking.</li><li>And most importantly: <strong><em>codeSnippets that can unknowingly block the event loop…..!!!</em></strong></li></ol><p>Thank you for all the support and time to read this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e87f40d0e3c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Concurrency through database in rails: Part 2]]></title>
            <link>https://vipulbest1.medium.com/handling-concurrency-through-database-in-rails-part-2-136e5420bce0?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/136e5420bce0</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[rdbms]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 08:15:58 GMT</pubDate>
            <atom:updated>2020-08-29T10:37:48.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*UZ9hu7Cvq88WrR52Jbm1Vg.jpeg" /></figure><blockquote><a href="https://medium.com/@vipulbest1/handling-concurrency-through-database-in-rails-part-1-8619ffe75f2d">In Part 1</a>, we had a brief introduction to different isolation levels and we also observed how the Serializable isolation level provides the highest level of isolation between concurrent running transactions.</blockquote><p>Let&#39;s get back the same account balance update examples that we played around in <a href="https://medium.com/@vipulbest1/handling-concurrency-through-database-in-rails-part-1-8619ffe75f2d">Part 1</a>.</p><p>Consider a scenario where you receive two concurrent transactions to your rails application which updates the same account record.</p><p>So keep two terminals open side by side in rails console and try the below code.</p><p>Keep the setup ready with the account model that we had in Part 1. If not, you can do it again as below</p><pre><br>rails generate model Account account_id:integer balance:integer</pre><pre>rails db:migrate</pre><pre>If you want to run just the specific Account migration</pre><pre>rails db:migrate:up VERSION=&lt;version_of_above_migration_file&gt;</pre><pre>Lets create one account with initial balance</pre><pre>Account.create(account_id: 999, balance: 100)</pre><p>In the first terminal, initiate transaction 1.</p><pre>ActiveRecord::Base.transaction do<br>  p &quot;starting Transaction T1&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance+=500<br>  l.save!<br>  sleep(60)<br>end</pre><p>In the second terminal, initiate transaction 2 while the above transaction 1 is sleeping.</p><pre>ActiveRecord::Base.transaction do<br>  p &quot;Starting Transaction T2&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance+=1000<br>  l.save!<br>end</pre><p>So what do you observe? Let’s use our understanding of isolation levels that we discussed in Part 1. Do give close attention to the below points:</p><ol><li>We have two concurrent transactions trying to update the same record.<br>So by default, there will be some isolation level guaranteed to these transactions. As I mentioned, the default isolation level in rails will be the default isolation level provided by the underlying database(I am using Mysql which will be:<strong><em> repeatable_read </em></strong><em>).</em></li><li>In cases where multiple transactions are trying to update the same object, your database does provide<strong><em> some level of safety by using database Locks.</em></strong></li><li>Now database locks are of two types</li></ol><p>. <em>Shared Locks</em>( also known as read lock): multiple transactions can get shared lock to read the same object.</p><p>. <em>Exclusive Locks</em> (also known as write lock): if one of the transaction wants to update a record, it acquires an exclusive write lock and all other transactions(whether they want to read/write) are blocked and put in waiting state.</p><p>So, after understanding the above two points, what the output of the above code would be?</p><blockquote>How will rails ecosystem along with the underlying database react to the above code ?</blockquote><p>Here is the sequence in which both the above transactions are executed.</p><ol><li>Transaction T1 is the initial request.</li></ol><pre><strong>l = Account.find_by(account_id: 999) </strong><br><em># reads the initial balance 100</em></pre><pre><strong>l.balance+=500 </strong> <br><em>#updates balance to 600 in active record object</em></pre><pre><strong>l.save! </strong> <br><em>#runs the update statement but yet not committed</em></pre><pre><strong>sleep(60) </strong><br><em># So the transaction did not yet commit and instead it goes off to sleep</em></pre><p>2. While transaction T1 is sleeping, there comes one more concurrent request transaction T2 to update the same account’s balance</p><pre><strong>l = Account.find_by(account_id: 999) </strong></pre><pre><em># So what do you think will be the value of l.balance. As Isaid, postgress by default uses read_committed isolation level, so T2 will see the committed value i.e. 100 not 600(which got updated by T1 but not yet committed as T1 is sleeping)</em></pre><pre><strong>l.balance+=1000</strong></pre><pre><em># Now here T2 waits..it keeps on waiting till T1 wakes after sleeping for 60 seconds and does a commit. </em></pre><pre><strong><em>l.save!</em></strong></pre><pre># <em>Once T1 is done, T2 resumes and updates the balance to  1100</em></pre><blockquote>Cool, so what&#39;s the final balance in Account 999. <br>It is 1100 which is insanely wrong…..<br>The initial balance was 100, T1 wanted to deposit 600 and T2 wanted to deposit 1000. In the end, we should have had 1700 but we have 1100.</blockquote><p><strong><em>Its a classic race condition</em></strong> which in most scenarios will be solved by using application-level Mutex/Semaphores and what not. <br>But these are application-level constructs and this article wants to use the capabilities of the underlying database to handle concurrency.</p><p>We know that while transaction T1 is in the middle of updating an account, T2 waits for T1 to complete.</p><p>So give close attention to the word wait in the above statement which is the behavior of default exclusive lock used by Postgres. Exclusive locks are of different types.</p><p>Have a look at this page to understand all kinds of exclusive locks used by Postgres: <a href="https://www.postgresql.org/docs/9.1/explicit-locking.html">https://www.postgresql.org/docs/9.1/explicit-locking.html</a></p><p>By default, Postgres uses <strong>FOR UPDATE</strong> mode for locking selected rows which is fine, but the transaction does wait for the running transaction to release the lock.</p><p>Our solution will be to not let transaction T2 wait, instead, it should report an error and not continue further.</p><p>So change the code for the transaction as below:</p><p>Transaction T1</p><pre>ActiveRecord::Base.transaction do<br>  p &quot;starting Transaction T1&quot;<br>  l = Account<strong>.lock(&quot;</strong><strong>FOR UPDATE NOWAIT&quot;)</strong>.find_by(account_id: 999)<br>  l.balance+=500<br>  l.save!<br>  sleep(60)<br>end</pre><p>Transaction T2</p><pre>ActiveRecord::Base.transaction do<br>  p &quot;Starting Transaction T2&quot;<br>  l = Account<strong>.lock(&quot;FOR UPDATE NOWAIT&quot;)</strong>.find_by(account_id: 999)<br>  l.balance+=1000<br>  l.save!<br>end</pre><p>You will observe, that while T1 sleeps, T2 initiates and T2 does not wait for T1 to finish, instead it crashes with the below error:</p><pre>(PG::LockNotAvailable: ERROR:  could not obtain lock on row in relation &quot;accounts&quot;</pre><p>which is fine for maintaining consistency, reliability, and accuracy in our system. It prevents T2 from overwriting the balance and we make sure there is only one transaction that ultimately succeeds.</p><p><strong>Conclusion:</strong></p><p>Most of the web applications on the internet today (<strong><em>especially in the B2B Segment</em></strong>) are not safe for concurrent transactions.</p><blockquote>It&#39;s just that, the possibility of two concurrent transactions trying to update the same record is really really less. So we dont run into production issues that frequently. <br>I mean I will never have multiple guys trying to deposit money to my account exactly at the same time to be considered concurrent. Though I do wish that happens :P</blockquote><p>However, applications that operate under huge traffic and operate on the same records like(ticket booking system, banking) really have well-defined strategies to make them concurrent safe even to one-tenth of a second.</p><p>I hope you guys like this. Do share kind feedback and your observations as well. Keep exploring….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=136e5420bce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Concurrency through database in rails: Part 1]]></title>
            <link>https://vipulbest1.medium.com/handling-concurrency-through-database-in-rails-part-1-8619ffe75f2d?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8619ffe75f2d</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[isolation-level]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Sun, 09 Aug 2020 08:10:18 GMT</pubDate>
            <atom:updated>2020-08-14T03:40:41.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*wNHhOXPXa3Yd3uytwQP3vQ.jpeg" /></figure><blockquote>This article deals with the fundamentals of how concurrent requests (let me say concurrent transactions) are dealt at the database level. <br>Please note, I will not be talking about optimized design to create a super concurrent online ticket booking system but will try laying out all the foundational stuff that as a developer you should be aware of if you are creating highly concurrent systems or maybe something even more complex.<br>Ok, let&#39;s start…..</blockquote><p>How concurrent transactions behave with each other? So let me put forward a question as below :</p><blockquote><strong>Lets says your database receives two concurrent transaction requests T1 and T2. So how much of T1 will be exposed or isolated to T2 and vice versa….?</strong></blockquote><p>We are aware that the ACID properties of RDBMS provide isolation levels.</p><blockquote><strong>Isolation levels</strong><em> determine how and how much of the changes being made by a transaction T1 is visible or hidden to/from another running transaction T2.</em></blockquote><p><strong>We have 4 different isolation levels in traditional RDBMS.</strong> So I am not gonna give any definition of these levels, but instead jump directly to example codes so that you can self derive and understand what each one of them does.</p><blockquote>So turn on your terminals, open rails console, and time to do some epic stuffs which is … <strong>copy the code, paste the code, and explore</strong>….</blockquote><p>Lets set up some sample data. A simple Account model with one account and an initial balance.</p><p>Please note: I am using MySQL as my underlying database. You can use Postgress as well. However, Postgress does not support one of the isolation levels as we will see later in the article.</p><pre><strong>rails generate model Account account_id:integer balance:integer</strong></pre><pre><strong>rails db:migrate</strong></pre><pre><em>If you want to run just the specific Account migration</em></pre><pre><strong>rails db:migrate:up VERSION=&lt;version_of_above_migration_file&gt;</strong></pre><pre><em>Lets create one account with initial balance in rails console as below:</em></pre><pre><strong>Account.create(account_id: 999, balance: 100)</strong></pre><blockquote><strong>Note</strong>: Better to have two terminals/rails console open side by side so that we can mimic concurrent requests/transactions</blockquote><p><strong>1. Read Uncommitted</strong></p><blockquote>Postgress does not support Read Uncommitted. If used, it will be defaulted to Read Committed</blockquote><p>In the first terminal lets initiate transaction 1.</p><pre>ActiveRecord::Base.transaction(isolation: :read_uncommitted) do<br>  p &quot;starting Transaction T1&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance = 500<br>  l.save!<br>  sleep(60)<br>end</pre><p>While it sleeps for 1 mt, initiate transaction 2 in another terminal</p><pre>ActiveRecord::Base.transaction(isolation: :read_uncommitted) do<br>  p &quot;Starting Transaction T2&quot;<br>  p Account.find_by(account_id: 999).balance<br>end</pre><p>Heres the output of transaction 2,</p><pre>Starting Transaction T2<br>500 </pre><p>So, T2 reads 500 which is <strong><em>yet not committed by transaction T1</em></strong>, because transaction T1 is still sleeping and it will commitonce it wakes up. So that is why the name: read_uncommitted as it is able to read uncommitted records by other ongoing transactions.</p><p><strong>2. Read Committed</strong></p><p>In the first terminal lets initiate transaction 1.</p><pre>#<em>Reset balance to 100</em><br>Account.first.update(balance: 100)</pre><pre>ActiveRecord::Base.transaction(isolation: :read_committed) do<br>  p &quot;starting Transaction T1&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance = 500<br>  l.save!<br>  sleep(60)<br>end</pre><p>While it sleeps for 1 mt, initiate transaction 2 in another terminal</p><pre>ActiveRecord::Base.transaction(isolation: :read_committed) do<br>  p &quot;Starting Transaction T2&quot;<br>  p Account.find_by(account_id: 999).balance<br>end</pre><p>Heres the output of transaction 2,</p><pre>Starting Transaction T2<br><strong>100</strong></pre><p>So, T2 reads 100 which is the committed value. It does not read the uncommitted value i.e. 500 which transaction T1 has updated but not committed yet as it is sleeping.</p><p><em>Cool so guys stay with me... <br></em><strong><em>You now are aware of what read uncommitted vs read committed is.</em></strong><em> <br>We will discuss which one to use, which is the industry standard for DBMS. but before that let&#39;s complete the last two isolation levels</em></p><p><strong>3. Repeatable Read</strong></p><p>In the first terminal lets initiate transaction 1.</p><pre>#<em>Reset balance to 100</em><br>Account.first.update(balance: 100)</pre><pre>ActiveRecord::Base.transaction(isolation: :repeatable_read) do<br>  p &quot;starting Transaction T1&quot;<br>  l = Account.find_by(account_id: 999)<br>  p &quot;balance from first read is #{l.balance}&quot;<br>  p &quot;sleeping....&quot;<br>  sleep(60)<br>  p &quot;woke up. I am sure by now T2 would have done an update&quot;<br>  l1 = Account.find_by(account_id: 999)<br>  p &quot;balance from second read is #{l1.balance}&quot;<br>  p &quot;total rows in accounts table&quot;<br>  p Account.count<br>end</pre><p>While it sleeps for 1 mt, initiate transaction 2 in another terminal</p><pre>ActiveRecord::Base.transaction(isolation: :repeatable_read) do<br>  p &quot;Starting Transaction T2&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance = 1000<br>  l.save!<br>  Account.create({id: 1999, balance: 10})<br>end</pre><p>Heres the output of transaction 1,</p><pre>Starting Transaction T1<br>balance from first read is 100<br>sleeping....<br>woke up. I am sure by now T2 would have done an update<br><strong>balance from second read is 100</strong><br>total rows in accounts table<br>2</pre><p>What… but while T1 was asleep, T2 went ahead and actually committed the balance to 1000. So when T1 again read the record, it should have read 1000. but it read 100. <strong><em>That is what is called a repeatable read.</em></strong><br>One more thing to notice is T1 after waking up does acknowledge the fact there is a new row entered and that is why it gives total rows as 2.</p><p>T1 would have read 1000 in the second fetch if isolation level was read_committed. Go ahead, change the isolation level to read_committed in the above code and check for yourself…Ok.. let&#39;s jump to the last isolation level</p><p><strong>4. Serializable.</strong></p><p>To understand serializable, copy the above code for repeatable read and run them in the same order by making isolation level as serializable .<br>The output from Transaction 1 will be</p><pre>Starting Transaction T1<br>balance from first read is 100<br>sleeping....<br>woke up. I am sure by now T2 would have done an update<br>balance from second read is 100<br>total rows in accounts table<br><strong>1</strong></pre><p>So as a keen observer, you must have noticed serializable is the same as repeatable read but with one distinction.</p><p>T1 does not acknowledge the new row entered by T2. so it totally ignores what other transactions are doing which brings us to one more important distinction and behavior of serializable.</p><blockquote>Serializable does not allow concurrent requests/transactions to update the same record. So yeah its the highest level of isolation.</blockquote><p>Let&#39;s get back to understanding stuff with code. Hold on guys, Serializable is still not finished….</p><p>In the first terminal lets initiate transaction 1.</p><pre>ActiveRecord::Base.transaction(isolation: :serializable) do<br>  p &quot;starting Transaction T1 which is trying to update account 999&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance = 1000<br>  l.save!<br>  sleep(60)<br>end</pre><p>While it sleeps for 1 mt, initiate transaction 2 in another terminal</p><pre>ActiveRecord::Base.transaction(isolation: :serializable) do<br>  p &quot;Starting Transaction T2 which also is trying to update account 999&quot;<br>  l = Account.find_by(account_id: 999)<br>  l.balance = 2000<br>  l.save!<br>end</pre><p>Cool. so what did you get? which one of the transaction passes under serializable.</p><p>The answer is: T1 passes and updates balance to 1000 while transaction 2 fails with the below message</p><pre><strong>Mysql2::Error::TimeoutError: Lock wait timeout exceeded; try restarting transaction</strong></pre><pre><em>If you were using Postgress you would have got the below</em></pre><pre><strong>PG::TRSerializationFailure: ERROR: could not serialize access due to concurrent update`</strong></pre><blockquote>Note: both transactions will pass successfully if they were trying to update two different records. Needless to say, but I just thought to put this here.</blockquote><p>Serializable saved us from concurrent requests trying to update the same record. So yeah, this isolation level can be used while building complex ticket booking systems, as they also have the challenge to stop concurrent requests for reserving the same object(seat/ticket).</p><p>To some extent, using the Serializable isolation level is one perfect theoretical approach to handle concurrency. But implementing such level of isolation has huge database performance overheads because of which you might not end up using this approach as your final solution.</p><h4>Which isolation level to use…..?</h4><p>That depends on your system requirements. The idea here is we want to minimize dirty reads, nonrepeatable reads, and phantom reads. In case you are not aware of these, you can google them out. Also, I will be creating one more article on these reads. Do watch the space !!!</p><p>As you use a higher isolation level, you end up minimizing all the above bad reads. But using a higher isolation level has overhead and its not advisable for good performance. So you need to find a balance.</p><h4>Which one does rails use….?</h4><p>You can tell rails to use an isolation level explicitly as we did in the above code. But the default value is decided by the underlying database.</p><p>If its Postgres<strong>,<em> they use read_committed.</em></strong></p><p>If its MySQL,<strong><em> they use repeatable_read.</em></strong></p><p><a href="https://medium.com/@vipulbest1/handling-concurrency-through-database-in-rails-part-2-136e5420bce0?source=friends_link&amp;sk=d75262f6f04e1bfd0ce433e4e113a239">Read Part 2</a> here which continues the discussion on how to use database locks to achieve concurrent safe code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8619ffe75f2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Locks Using Ruby and Redis]]></title>
            <link>https://vipulbest1.medium.com/distributed-locks-using-ruby-and-redis-2e0a2c7b9765?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0a2c7b9765</guid>
            <category><![CDATA[redlock]]></category>
            <category><![CDATA[distributed-locking]]></category>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 19:06:05 GMT</pubDate>
            <atom:updated>2020-07-19T19:14:36.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*5D9tnqvzEx3Bt1-bCoAZmQ.jpeg" /></figure><p>Designing distributed systems often leads to resource contention where multiple systems own the same resource and do updates to it.</p><p>This is a common scenario which we encounter while designing multithreaded applications that are fighting for single resource contention.<br>The solution here is to use locks/mutex/semaphores so that there is only one active thread accessing the resource.</p><blockquote><strong>So how to design these locks for distributed systems where you want only one system to have access to a resource at any point in time using some basic ruby and Redis as cached data storage.</strong></blockquote><p>Let me start with a very basic distributed system as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*2aYmiv-Dtoa1vAB7hhS7sQ.jpeg" /></figure><ol><li>We have three server instances S1, S2, S3. These servers pick a file from AWS S3 or any other file storage system and process that file and write to a common output file with the same name.<br>Pretty simple right…..</li><li>Ok. now let’s take this scenario. Where requests come first from Server S1, it gains access to file_1.input and starts processing it and writing the output to file_1.output.</li><li>Meanwhile, S1 is processing it, S2 plans to process the same file file_1.input as well. It also gains access to this file from the shared file system and starts processing it.</li><li>So what do we have now? We have two systems writing to the same output file at the same time which can easily corrupt/overwrite the data in the file_1.output thereby compromising the reliability and efficiency of our distributed system.</li></ol><p>Let&#39;s try solving the above scenario by making sure a system gains exclusive access/right (yeah we can call it lock as well) before accessing the resource.</p><p>We will be using Redis for our data storage as it is efficient for multiple reads and writes and faster than a traditional database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*DOfOrFZPos05GDbjKp9LJg.jpeg" /></figure><ol><li>Server S1 before accessing our file storage directly. now goes through a new entity in our design called the<strong><em> Lock Manager </em></strong>whose sole responsibility is to give individual machines exclusive rights to access resources.</li><li>Lock Manager is a ruby application that is connected to a Redis instance. <br>For the first incoming request from S1 for file1.input, Lock Manager does the below operation on Redis<br> SET &quot;file_1.input_picked&quot; &quot;Server_S1&quot; PX 30000</li><li>The above command sets the above key in Redis cache with time to expiry(TTL) of 30000 milliseconds.</li><li>Lock Manager then returns an acknowledgment message back to system S1 saying it has access to file_1.input .</li><li>An acknowledgment message can be as below<br>{lock_given: true, lock_name: “file_1.input_picked”}</li><li>Now while Server S1 is processing, file_1.input, one more request for file1.input comes from Server S2.</li><li>The request goes through the Lock Manager. Lock Manager checks that there is already a key set for this file, which implies there is some other system(Server S1) processing the file at this point in time. It sends a denial/negative message to Server S2. Server S2 can choose to read some other file or retry after some time.</li><li>Once S1 completes processing, it sends a message to the lock manager to delete the key.<br>DELETE “file_1.input_picked”</li></ol><h4>All Good …right ?….</h4><p>Yeah (to some extent) we have managed to give exclusive grants to multiple requests from different systems. Well… there is one (or maybe more…) important edge case that we missed. Let&#39;s consider the below scenario</p><ol><li>Server S1 gains access to the file1.input and Lock Manager has set a key as below in Redis<br>SET &quot;file.input_picked&quot; &quot;Server_S1&quot; PX 30000</li><li>Server S1 takes 60 seconds to complete the job. However, the cache key set in the above step has a TTL of 30 seconds. Consider this time stamp flow as below:</li><li>Redis deletes this key at 30 seconds while the processing goes on by S1.</li><li>At 45th second, there comes a request from system S2. Lock Manager checks that there is no key “file1.input_picked” set in Redis. <br>So it sets the key and gives access to Server S2.</li><li>At the 60th Second, Server S1 completes its processing and notifies Lock Manager to delete “file_1.input”</li><li><strong><em>Lock Manager deletes the key without realizing that it is deleting the key set by Server S2 but on completion of a job by Server S1.</em></strong></li><li>While Server S2 is still processing the job, there might be other requests from Server S3 to gain access, and Lock Manager will happily give access to it as well thereby increasing chances of collision and data corruption.</li><li>However, we have protection for this scenario as well. <strong><em>Give attention to the cache key value that we have designed</em></strong><br> {&quot;file_1.input_picked&quot; : &quot;Server_S1&quot;}</li><li>The value of the above key gives the system that actually initiated the request. So for the above flow, at 60th second, when S1 notifies Lock Manager of job completion, the key would be as below<br>{“file_1.input_picked” : “Server_S2”}</li><li>Lock Manager will check if the value is the same as the system which has sent the job completion signal. In our case, since it will be different as S1 != “server_S2”, Lock Manager decides to ignore and does not delete the key.</li></ol><blockquote>Ok … But what about fault tolerance. We have a single instance of redis. Its a single point of failure and surely someday in our most scary dreams it will go down…..!!!</blockquote><p><strong><em>Yeah, We know…….. Replication is the solution.</em></strong></p><blockquote>But replication between redis instances in a cluster is async and based more on a pull model where the slave run threads to sync themselves with master.<br>At any point in time, there can be delays and lags in syncing the data. so we are not guaranteed of data reliability.</blockquote><p>So is there anything else we can do to coordinate between multiple Redis instances….?</p><p><strong>Yes…..The RedLock Algorithm is at your disposal !</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*c10Zu0nUIxftX2SaG8WhQA.jpeg" /></figure><p>Important Points</p><ol><li>System S1 is granted the lock only when the lock manager sets the cache key in the majority of the Redis instances in our horizontally scaled environment. In our case, we have used 3 instances.</li><li>On completion of the job, the system notifies the lock manager, and its the responsibility of the lock manager to delete the key from all the Redis instances.</li><li>This way, we are not dependent on the async replication of Redis in a cluster. Instead, we are being proactive and making sure to push out keys to multiple instances at the same time which is considered an atomic operation.</li></ol><blockquote>We can write Lock Manager as an independent ruby application where we can expose APIs to write and delete to multiple Redis instances. <br>However, this feature and algorithm is already abstracted into a ruby gem<br><a href="https://github.com/antirez/redlock-rb"><strong>https://github.com/antirez/redlock-rb</strong></a></blockquote><p>Distributed Locks are something that we encounter always while designing good resource contention models in distributed systems.</p><p>Hope this article introduced the topic in an easy way to ones who have not designed distributed systems yet and would have surely resonated with other devs who design these complex systems on a daily basis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0a2c7b9765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thread Safety in Ruby and the GIL]]></title>
            <link>https://vipulbest1.medium.com/thread-safety-in-ruby-and-the-gil-884b6bc47219?source=rss-77fbc8d68e9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/884b6bc47219</guid>
            <category><![CDATA[global-interpreter-lock]]></category>
            <category><![CDATA[gil]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Vipulbest]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 09:19:41 GMT</pubDate>
            <atom:updated>2020-06-28T10:37:46.188Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thread Safety in Ruby and the mystical GIL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eciMa86kQgNP9XhTrCm5OQ.png" /></figure><p>We might be getting regarded as one of those lucky developers if we have not faced any scary scenarios of writing multithreaded applications.</p><p>But if we are of one those who write highly multithreaded applications, then we need to deal with some really scary and unpredictable kind of stuff.</p><blockquote>Because writing multithreaded applications is complex and more error prone. You never know when your code can run into race conditions, deadlocks etc. Everything might seem great and then one fine evening on a weekend your thread safe production code goes into a deadlock</blockquote><p>Let’s try understanding this threaded ecosystem in ruby’s MRI and the famous/infamous GIL(<strong><em>Global Interpreter Lock</em></strong>) with this classic bank transaction example. Spawning 100 threads, each thread incrementing my account balance by $1 10000 times.</p><pre># no_race_condition.rb</pre><pre>account_balance = 0<br>100.times.map do<br> Thread.new do<br>   10000.times do<br>     value = account_balance<br>     value = value + 1<br>     account_balance = value<br>   end<br> end<br>end.each(&amp;:join)</pre><pre>p “expected is 1 million”<br>p “final balance in bank account is #{account_balance}”</pre><p>Just at one look, any experienced developer can rightly say that this program is not thread-safe as we are spawning 100 threads and each thread accesses this common variable account_balance giving an invitation to race conditions.<br>However, when we run the above code, it never runs into race condition and we always get 1 million in the account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*ZYALsk-7xjrYIhQY8FLGrA.png" /></figure><p>Let’s refactor the above code a bit where we abstract read and update of account_balance for better readability.</p><pre># refactored.rb</pre><pre>account_balance = 0</pre><pre><strong>def get_current_balance<br> account_balance<br>end</strong></pre><pre><strong>def update_balance(value)<br> account_balance = value<br>end</strong></pre><pre>100.times.map do<br> Thread.new do<br>   10_000.times do<br>     value = <strong>get_current_balance</strong><br>     value = value + 1<br>     <strong>update_balance(value)</strong><br>   end<br> end<br>end.each(&amp;:join)</pre><pre>p “final balance in bank account is #{account_balance}”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*8EI0iDI1tC0e1sJGfW5P4Q.png" /></figure><p>Strange … Right? The second run credited 960 thousand into my account. Not fair…!!!<br>Just a simple and a nice refactor crashed my code and brought race conditions into play.</p><blockquote><strong>What the heck is Ruby’s MRI actually doing?</strong></blockquote><p>Yeah .. we know it would have done context switching between multiple threads. But why it did not do with our initial non refactored code.</p><p>Well one of the rules of MRI says:</p><blockquote><strong>Ruby’s MRI does context switching every time the running thread calls a function or returns from a function</strong></blockquote><p>This explains pretty much why our refactored code ran into race conditions.<br>I bet the second rule of MRI is more interesting</p><blockquote><strong>Ruby’s MRI coupled with OS Scheduler can do context switching between threads at any point in time and on any line of your code…</strong></blockquote><p>So does that ring a bell…? Yes. We as developers don’t have any control over when context switching can happen and are solely responsible for making our ruby code thread-safe.</p><blockquote>But wait … <br>Isn’t ruby thread safe and the mystical GIL was supposed to protect us ? <br>I read that GIL will make ruby thread safe…..<br>Why did it not prevent me from race condition (…..may be because it was never meant to do that).</blockquote><h4>Clearing the doubts regarding GIL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*gPT0pLGNw2U7cvxSOZeDSw.png" /></figure><p>GIL (Global Interpreter Lock) is a lock that every ruby code or every thread running ruby code needs to acquire from MRI to run.</p><p>So what does it mean…</p><blockquote>It implies at any point in time, there will be only one active running thread.<br>So if u have 4 threads, and a quad(4 core) box , ruby MRI with GIL will make sure only one thread will be active at any given point in time. So a single thread will just utilize 1/4rth of the processing power of your box.</blockquote><p><strong>So GIL does not provide thread safety and it truly renders the developer helpless when they want to use parallelism.</strong> Then why did the MRI developers even include GIL in the codebase …</p><ul><li>They used GIL as a solution to protect the internal state of the system. It made the internal data structures of Ruby MRI (mostly implemented in C) likeArrayclass thread-safe.<br>So, if you spawn 100 of threads and each thread appends to the same shared Array instance 100 times, you will always get 10,000 entries in that array and will never run into race conditions. because GIL provides thread safety for the internal data structures. Go ahead and try for your self….</li><li>GIL does not guarantee thread safety for any external ruby code that we write</li><li>Though the core MRI team took this approach they did achieve thread-safety for internal data structures but compromised with parallelism.</li><li><strong><em>There are talks of removing GIL in ruby 3 and the final decision is awaited.</em></strong></li></ul><p>So I would summarise the below key takeaways from this article</p><ul><li>Ruby MRI coupled with OS Scheduler will do unpredictable Context switching and prevention from race conditions is the sole responsibility of the developer.<br>One example of handling race conditions using Mutex is given below. <strong>However, I assume you would have a fair idea of how using locks are expensive.</strong> Look for better models like Queues and other concurrency models like actors <strong>(check celluloid in ruby</strong>), channels (<strong>Read Guild in Ruby</strong> ), etc to handle race conditions.</li></ul><pre>account_balance = 0</pre><pre><a href="http://twitter.com/mutex">@mutex</a> = Mutex.new</pre><pre>def get_current_balance<br> account_balance<br>end</pre><pre>def update_balance(value)<br> account_balance = value<br>end</pre><pre>100.times.map do<br> Thread.new do<br>   10_000.times do<br>     <a href="http://twitter.com/mutex">@mutex</a>.synchronize do<br>       value = get_current_balance<br>       value = value + 1<br>       update_balance(value)<br>     end<br>   end<br> end<br>end.each(&amp;:join)</pre><pre>p “final balance in bank account is #{account_balance}”</pre><ul><li>A new principle and concurrency model that industry is adapting is the channel concurrency model where independent threads(called actors) instead of sharing data in memory, communicate data to each other.</li></ul><blockquote><strong>Don’t communicate by sharing state; share state by communicating.</strong></blockquote><p>Multithreading is vast and a lot to explore for. But having a good idea of how your language and your platform deals with it is an important aspect as well….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884b6bc47219" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>