<?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 Shireen Kachroo on Medium]]></title>
        <description><![CDATA[Stories by Shireen Kachroo on Medium]]></description>
        <link>https://medium.com/@kachrooshireen3?source=rss-3bdf82716559------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8ZE7i3ijETJ0723dr0Jy9g.png</url>
            <title>Stories by Shireen Kachroo on Medium</title>
            <link>https://medium.com/@kachrooshireen3?source=rss-3bdf82716559------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:19:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kachrooshireen3/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[Confusion Matrix Explained: Understanding TP, TN, FP and FN]]></title>
            <link>https://medium.com/@kachrooshireen3/confusion-matrix-explained-understanding-tp-tn-fp-and-fn-d6cd16fd663c?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6cd16fd663c</guid>
            <category><![CDATA[false-positive]]></category>
            <category><![CDATA[true-negative]]></category>
            <category><![CDATA[true-positive]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[false-negative]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 13:40:17 GMT</pubDate>
            <atom:updated>2026-11-24T13:40:17.664Z</atom:updated>
            <content:encoded><![CDATA[<p>When a machine learning model makes a prediction, how do we know whether it got it right?</p><p>For a classification model, looking at the number of correct predictions alone doesn’t always tell us the complete story. We also need to understand what kind of mistakes the model makes.</p><p>This is where a <strong>Confusion Matrix</strong> comes in.</p><h3>Why Do We Need a Confusion Matrix?</h3><p>A confusion matrix is a table used to evaluate the performance of a classification model by comparing its actual predictions with the correct outcomes.</p><p>It tells us two things:</p><ul><li>How many predictions were correct?</li><li>How many predictions were incorrect, and what kind of mistakes did the model make?</li></ul><p>To understand this better, let’s consider an email spam classifier.</p><p>Suppose we have a model that predicts whether an email is spam or not spam. After making predictions, we compare them with the actual categories of those emails.</p><p>There are four possible outcomes.</p><h3>Understanding the Four Outcomes</h3><p>Before looking at them individually, remember two things:</p><ul><li><strong>Positive and Negative</strong> refer to the predicted class or outcome. Here, Spam is Positive and Not Spam is Negative.</li><li><strong>True and False</strong> indicate whether the prediction was correct or incorrect.</li></ul><p>Now, let’s break down each outcome.</p><h4>1. True Positive (TP)</h4><p>The model predicts an email as spam, and it actually is spam. The prediction is correct.</p><p><strong>Example:</strong> An unwanted promotional email is correctly identified as spam.</p><h4>2. True Negative (TN)</h4><p>The model predicts an email as not spam, and it actually isn’t spam. Again, the prediction is correct.</p><p><strong>Example:</strong> An important email from your college is correctly identified as legitimate.</p><h4>3. False Positive (FP)</h4><p>The model predicts an email as spam, but it is actually a legitimate email. The model incorrectly classifies something as positive.</p><p><strong>Example:</strong> An important email from your professor ends up in the spam folder.</p><h4>4. False Negative (FN)</h4><p>The model predicts an email as not spam, but it is actually spam. The model fails to identify a positive case.</p><p><strong>Example:</strong> A spam email enters your inbox because the model incorrectly considers it legitimate.</p><h3>Putting Everything Together</h3><p>All four outcomes can be represented in a 2×2 table called a confusion matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ccf9nEXHjjcZiElj5LzTIQ.png" /><figcaption>Confusion Matrix</figcaption></figure><p>The rows represent the actual classes, while the columns represent the predicted classes.</p><p>The diagonal entries (TP and TN) represent correct predictions, whereas the other two entries (FP and FN) represent incorrect predictions.</p><p>This is the basic structure of a confusion matrix for binary classification.</p><h3>Why Do These Four Outcomes Matter?</h3><p>You might wonder why we need to distinguish between two types of incorrect predictions.</p><p>The reason is simple: <strong>not all mistakes have the same consequences.</strong></p><p>In our spam classification example:</p><ul><li>A False Positive means a legitimate email is mistakenly sent to the spam folder.</li><li>A False Negative means an unwanted email is allowed into the inbox.</li></ul><p>Both are mistakes, but their consequences are different.</p><p>This distinction becomes even more important in applications such as medical diagnosis, fraud detection, and cybersecurity, where missing an actual threat can be much more serious than raising a false alarm.</p><p>Understanding these outcomes helps us evaluate what a model is doing well and where it is failing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6cd16fd663c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Apache Kafka: The Distributed Event Streaming Platform]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-apache-kafka-the-distributed-event-streaming-platform-7b270279f9af?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b270279f9af</guid>
            <category><![CDATA[producer]]></category>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[real-time-processing]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 07:37:09 GMT</pubDate>
            <atom:updated>2026-11-24T07:37:09.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine using an online shopping application. You place an order. Within a few seconds:</p><ul><li>The order service records your purchase.</li><li>The inventory service updates the available stock.</li><li>The payment service processes the transaction.</li><li>The notification service sends you a confirmation.</li><li>The analytics system records the purchase for reporting.</li></ul><p>All these operations depend on the same event: <strong>an order was placed</strong>. But should the order service directly communicate with every other service?</p><p>That would create tight dependencies. If one service becomes unavailable, it could affect the entire workflow. As the application grows, managing these connections becomes increasingly difficult.</p><p>What if the order service could simply publish an event, and other services could independently receive and process it?</p><p>This is the problem Apache Kafka helps solve.</p><p>Kafka provides a distributed platform where applications can publish, store, read, and process streams of events in a reliable and scalable manner.</p><p>Let’s understand how it works.</p><h3>What Is Apache Kafka?</h3><p><strong>Apache Kafka is an open-source distributed event-streaming platform used to build real-time data pipelines and streaming applications. </strong>It allows different applications and services to communicate by producing and consuming events.</p><p>An event represents something that has happened.</p><p>Examples include:</p><ul><li>A customer placed an order.</li><li>A payment was completed.</li><li>A user logged into an application.</li><li>A sensor recorded a temperature reading.</li><li>A product’s inventory was updated.</li></ul><p>Kafka acts as an intermediary between the systems generating these events and the systems that need to process them. Instead of directly connecting every application to every other application, systems communicate through Kafka.</p><p>In simple terms:</p><p><strong>Kafka = Event Publishing + Distributed Storage + Event Consumption + Stream Processing</strong></p><p>It is commonly used for:</p><ul><li>Real-time data pipelines</li><li>Microservice communication</li><li>Log aggregation</li><li>Event-driven architectures</li><li>Data integration</li><li>Stream processing</li><li>Real-time analytics</li></ul><h3>Why Do We Need Kafka?</h3><p>Let’s consider an application without Kafka.</p><p>Suppose an e-commerce platform has five independent services:</p><ol><li>Order Service</li><li>Payment Service</li><li>Inventory Service</li><li>Notification Service</li><li>Analytics Service</li></ol><p>Whenever an order is placed, the Order Service needs to communicate with the other services.</p><p>A simplified architecture might look like this:</p><pre>                 Order Service<br>                      |<br>          ┌───────────┼───────────┐<br>          v           v           v<br>       Payment    Inventory   Notification<br>       Service     Service      Service<br>                      |<br>                      v<br>                Analytics Service</pre><p>As the number of services increases, the number of connections and dependencies can become difficult to manage.</p><p>Some common problems include:</p><h4>1. Tight Coupling</h4><p>The Order Service needs to know about multiple downstream services and how to communicate with them. Changes in one service can affect other services.</p><h4>2. Service Availability</h4><p>What happens if the Notification Service is temporarily unavailable? The Order Service may have to handle retries, failures, or delays itself.</p><h4>3. Traffic Spikes</h4><p>Suppose thousands of orders arrive within a few seconds. Downstream services may not be able to process all requests immediately.</p><h4>4. Data Integration</h4><p>Different systems may need access to the same events for different purposes. For example, an order event may be required by both an inventory system and an analytics platform.</p><h3>How Kafka Helps</h3><p>Kafka introduces a central event-streaming layer.</p><pre>                  Order Service<br>                       |<br>                       v<br>                 Kafka Cluster<br>                       |<br>          ┌────────────┼────────────┐<br>          v            v            v<br>      Payment      Inventory    Notification<br>      Service       Service       Service<br>          |<br>          v<br>      Analytics</pre><p>The Order Service publishes an event to Kafka. Other services independently consume that event and process it according to their requirements.</p><p>This provides:</p><ul><li>Loose coupling between services</li><li>Independent event consumption</li><li>Temporary buffering of incoming events</li><li>The ability to replay stored events</li><li>Better scalability for data pipelines</li></ul><p>Kafka does not automatically make every application reliable. Consumers still need to handle failures, retries, duplicate processing, and business-level consistency. But it provides a common infrastructure for managing event flows.</p><h3>Understanding Events</h3><p>Before learning Kafka’s architecture, we need to understand what an event actually contains. An event is a record of something that happened.</p><p>For example:</p><pre>{<br>  &quot;event_id&quot;: 101,<br>  &quot;event_type&quot;: &quot;ORDER_PLACED&quot;,<br>  &quot;customer_id&quot;: 501,<br>  &quot;product_id&quot;: 205,<br>  &quot;amount&quot;: 2500,<br>  &quot;timestamp&quot;: &quot;2026-11-24T10:30:00&quot;<br>}</pre><p>This event tells us that a customer placed an order for a product worth ₹2,500.</p><p>An event commonly contains:</p><ul><li><strong>Key:</strong> An optional identifier used for partitioning and identifying related records.</li><li><strong>Value:</strong> The actual event data.</li><li><strong>Timestamp:</strong> The time associated with the event.</li><li><strong>Headers:</strong> Optional metadata attached to the record.</li></ul><p>Kafka stores events as records. Once written, records are not normally modified in place. Instead, new events can represent subsequent changes.</p><p>For example:</p><pre>ORDER_PLACED<br>      |<br>      v<br>PAYMENT_COMPLETED<br>      |<br>      v<br>ORDER_SHIPPED<br>      |<br>      v<br>ORDER_DELIVERED</pre><p>Each event represents a separate occurrence in the application’s workflow.</p><h3>Core Components of Kafka</h3><p>Kafka uses a few important components to manage event streaming.</p><p>Let’s understand them one by one.</p><h4>1. Producer</h4><p>A producer is an application that publishes events to Kafka.</p><p>For example, when a customer places an order, the Order Service acts as a producer and sends an ORDER_PLACED event.</p><pre>Order Service<br>      |<br>      | Publish Event<br>      v<br>    Kafka</pre><p>A producer can publish events to one or more topics.</p><h4>2. Consumer</h4><p>A consumer is an application that reads events from Kafka.</p><p>For example:</p><ul><li>Payment Service consumes order events.</li><li>Inventory Service consumes order events.</li><li>Analytics Service consumes order events.</li></ul><p>Consumers decide how to process the events they receive.</p><pre>                  Kafka<br>                    |<br>          ┌─────────┼─────────┐<br>          v         v         v<br>       Payment  Inventory  Analytics<br>       Consumer  Consumer  Consumer</pre><h4>3. Broker</h4><p>A broker is a Kafka server responsible for storing and serving event records. A Kafka deployment generally contains multiple brokers working together as a cluster.</p><p>Each broker manages some of the partitions belonging to different topics.</p><h4>4. Topic</h4><p>A topic is a named stream or category of events.</p><p>For example:</p><pre>Kafka Cluster<br>     |<br>     ├── orders<br>     ├── payments<br>     ├── inventory<br>     └── user-activity</pre><p>The Order Service may publish events to the orders topic.</p><p>Consumers interested in order-related events subscribe to that topic.</p><h4>5. Cluster</h4><p>A Kafka cluster is a group of brokers working together.</p><p>Distributing data across brokers helps Kafka scale beyond a single server and supports fault tolerance through replication.</p><h3>Understanding Topics and Partitions</h3><p>A topic is not necessarily stored on a single broker. Kafka divides topics into smaller units called <strong>partitions</strong>. A partition is an ordered sequence of records.</p><p>For example, imagine an orders topic divided into three partitions:</p><pre>                 Topic: orders<br>                       |<br>          ┌────────────┼────────────┐<br>          v            v            v<br>      Partition 0  Partition 1  Partition 2</pre><pre>      Event 1      Event 2      Event 3<br>      Event 4      Event 5      Event 6<br>      Event 7      Event 8      Event 9</pre><p>Each partition maintains its own record order.</p><p>This is important because Kafka guarantees ordering within a partition, not across all partitions of a topic.</p><h3>Why Are Partitions Important?</h3><p>Partitions provide two major benefits.</p><p><strong>1. Scalability</strong></p><p>A topic can be distributed across multiple brokers. This allows Kafka to handle larger volumes of data.</p><p><strong>2. Parallel Processing</strong></p><p>Different consumers in the same consumer group can process different partitions simultaneously.</p><p>For example:</p><pre>              orders Topic<br>                   |<br>          ┌────────┼────────┐<br>          v        v        v<br>       Part 0   Part 1   Part 2<br>          |        |        |<br>          v        v        v<br>       Consumer Consumer Consumer<br>          1        2        3</pre><p>This allows multiple consumers to process events in parallel. However, within one consumer group, a partition is assigned to only one consumer at a time. If a consumer group has more consumers than available partitions, some consumers will remain idle.</p><h3>How Does Kafka Decide Which Partition Gets an Event?</h3><p>A producer can send a record to a specific partition. If a record has a key, Kafka’s partitioning logic can use that key to select a partition.</p><p>For example, if we use customer_id as the key, events belonging to the same customer can be routed to the same partition under a consistent partitioning configuration.</p><p>This is useful when events related to the same entity need to be processed in order.</p><h3>What Is an Offset?</h3><p>Every record in a Kafka partition is assigned a sequential identifier called an <strong>offset</strong>. An offset represents the position of a record within that partition.</p><p>For example:</p><pre>Partition 0</pre><pre>Offset 0  → ORDER_PLACED<br>Offset 1  → PAYMENT_COMPLETED<br>Offset 2  → ORDER_SHIPPED<br>Offset 3  → ORDER_DELIVERED</pre><p>Consumers use offsets to track their reading position. Suppose a consumer has processed records up to offset 2.</p><p>It can continue reading from the next record.</p><p>Offsets are important because they allow consumers to:</p><ul><li>Track progress</li><li>Resume consumption after restarting</li><li>Re-read older records</li><li>Manage event processing independently</li></ul><p>An offset is specific to a partition. Offset 2 in Partition 0 is not the same record as offset 2 in Partition 1.</p><h3>Consumer Groups</h3><p>Kafka allows consumers to work together using a concept called a <strong>consumer group</strong>. A consumer group is a set of consumers that coordinate to consume records from one or more topics.</p><p>For example, suppose three consumers belong to the same group:</p><pre>             Topic: orders<br>                  |<br>        ┌─────────┼─────────┐<br>        v         v         v<br>     Part 0    Part 1    Part 2<br>        |         |         |<br>        v         v         v<br>    Consumer  Consumer  Consumer<br>       A         B         C</pre><pre>       Consumer Group: order-processors</pre><p>Each consumer receives one partition in this example. The group collectively processes the topic.</p><h3>Why Are Consumer Groups Useful?</h3><p>They allow us to scale event processing horizontally. If the event volume increases, we can add more consumers, provided there are enough partitions to distribute.</p><h3>Can Multiple Applications Read the Same Topic?</h3><p>Yes. Consider an orders topic.</p><pre>                  orders<br>                     |<br>          ┌──────────┼──────────┐<br>          v          v          v<br>      Payment    Inventory   Analytics<br>       Group       Group       Group</pre><p>Each consumer group maintains its own reading progress. Therefore, the Payment Service can process an order event independently of the Analytics Service. This is one of Kafka’s most useful features: <strong>multiple applications can consume the same event stream independently.</strong></p><h3>How Does Kafka Store Data?</h3><p>Kafka is not simply a temporary message-passing system. It stores published records on disk using a distributed, partitioned log. Each partition is an ordered sequence of records.</p><p>New records are generally appended to the end of the partition.</p><pre>Partition Log</pre><pre>Offset 0 → Event A<br>Offset 1 → Event B<br>Offset 2 → Event C<br>Offset 3 → Event D<br>Offset 4 → Event E</pre><p>Kafka uses sequential writes and efficient data-transfer techniques to support high-throughput workloads.</p><h3>Is Data Deleted After Consumption?</h3><p>No. This is an important difference between Kafka and many traditional queue-based systems. Reading a record does not normally remove it from Kafka. Instead, records remain available according to the topic’s retention configuration.</p><p>For example, a topic may retain events for seven days.</p><p>Consumers can read those events during that period, including replaying them when necessary. Kafka can also use log compaction for topics where retaining the latest value for each key is more useful than keeping every historical record indefinitely.</p><h3>Why Is Retention Useful?</h3><p>Imagine an analytics application that was unavailable for two hours. Once it becomes available again, it can consume the events it missed, provided those records are still retained.</p><p>Similarly, a new consumer can process older events instead of starting only with newly arriving data. This makes Kafka useful for both real-time processing and historical event replay.</p><h3>Replication and Fault Tolerance</h3><p>What happens if a Kafka broker fails? Kafka supports replication to maintain copies of partition data across brokers.</p><p>A partition can have:</p><ul><li>One leader replica</li><li>One or more follower replicas</li></ul><p>For example:</p><pre>              Partition 0<br>                  |<br>          ┌───────┴───────┐<br>          v               v<br>       Leader          Follower<br>       Broker 1        Broker 2</pre><p>The leader handles reads and writes for that partition under the normal replication model.</p><p>Follower replicas fetch records from the leader and maintain copies.</p><p>If the leader becomes unavailable, Kafka can elect an eligible replica as the new leader.</p><h3>What Is an In-Sync Replica (ISR)?</h3><p>The In-Sync Replicas set contains replicas that are sufficiently caught up with the leader according to Kafka’s replication rules.</p><p>Kafka uses this concept when determining which replicas are eligible for leadership and when evaluating certain durability guarantees.</p><p>The producer’s acknowledgement setting also matters.</p><p>For example:</p><ul><li>acks=0: The producer does not wait for broker acknowledgement.</li><li>acks=1: The producer waits for acknowledgement from the leader.</li><li>acks=all: The producer waits for acknowledgement from the required in-sync replicas.</li></ul><p>The actual durability guarantee depends on the replication factor and broker configuration as well.</p><p>Replication helps Kafka tolerate broker failures, but it does not mean data loss is impossible under every configuration.</p><h3>How Does Kafka Work? Complete Data Flow</h3><p>Let’s connect the components using our e-commerce example. Suppose a customer places an order.</p><h4>Step 1: Producer Generates an Event</h4><p>The Order Service creates an ORDER_PLACED event.</p><h4>Step 2: Event Is Published to a Topic</h4><p>The producer sends the event to Kafka’s orders topic.</p><h4>Step 3: Kafka Stores the Record</h4><p>Kafka writes the event to a partition and assigns it an offset.</p><h4>Step 4: Consumers Read the Event</h4><p>Payment, Inventory, and Analytics consumer groups read the event independently.</p><h4>Step 5: Consumers Process the Event</h4><p>Each service performs its own operation.</p><pre>Customer Places Order<br>          |<br>          v<br>     Order Service<br>          |<br>          v<br>    Kafka Producer<br>          |<br>          v<br>    Topic: orders<br>          |<br>          v<br>    Kafka Partitions<br>          |<br>    ┌─────┼──────┐<br>    v     v      v<br> Payment Inventory Analytics<br>    |     |      |<br>    v     v      v<br> Process Update  Record<br> Payment Stock   Data</pre><p>The important point is that the producer does not need to know how every consumer processes the event. Kafka manages the event stream between them.</p><h3>What Is Kafka Streams?</h3><p>Kafka is not limited to storing and transporting events. Applications can also process event streams. <strong>Kafka Streams</strong> is a Java library for building stream-processing applications using Kafka.</p><p>For example, suppose an e-commerce company wants to calculate the number of orders placed every minute.</p><p>A stream-processing application can:</p><ol><li>Read events from the orders topic.</li><li>Group events by time window.</li><li>Count the number of orders.</li><li>Publish the result to another topic.</li></ol><p>Conceptually:</p><pre>        orders Topic<br>             |<br>             v<br>      Kafka Streams<br>             |<br>       Group by Window<br>             |<br>             v<br>       Count Orders<br>             |<br>             v<br>      order-counts Topic</pre><p>Kafka Streams supports operations such as:</p><ul><li>Filtering</li><li>Mapping</li><li>Grouping</li><li>Aggregation</li><li>Joins</li><li>Windowed processing</li></ul><p>It allows developers to build stream-processing applications without managing a separate processing cluster in the same way as some other stream-processing frameworks.</p><p>Kafka also integrates with external stream-processing systems such as Apache Flink and Spark Structured Streaming.</p><h3>Kafka Connect</h3><p>Another important part of the Kafka ecosystem is <strong>Kafka Connect</strong>. Kafka Connect is a framework used to move data between Kafka and external systems.</p><p>For example, we may want to:</p><ul><li>Import database changes into Kafka.</li><li>Send Kafka events to Elasticsearch.</li><li>Move application logs into Kafka.</li><li>Export processed events to a data warehouse.</li></ul><p>Kafka Connect uses connectors to interact with different systems.</p><p>There are two main types:</p><h4>Source Connector</h4><p>A source connector imports data from an external system into Kafka.</p><pre>Database<br>    |<br>    v<br>Source Connector<br>    |<br>    v<br>  Kafka</pre><h4>Sink Connector</h4><p>A sink connector exports data from Kafka to an external system.</p><pre>  Kafka<br>    |<br>    v<br>Sink Connector<br>    |<br>    v<br>Elasticsearch</pre><p>Kafka Connect makes it easier to build data integration pipelines without writing a separate custom producer or consumer for every integration.</p><h3>Kafka vs Traditional Message Queues</h3><p>Kafka is often compared with traditional message brokers.</p><p>Both help applications communicate asynchronously, but their underlying models are different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*PJyMNq_AB_us_j6IWnd_Mw.png" /></figure><p>A traditional queue is useful when a task should be delivered to a worker for processing. Kafka is particularly useful when multiple independent applications need to consume the same stream of events and may need to replay those events later.</p><p>This does not mean Kafka replaces every message queue. The right choice depends on the communication and processing requirements.</p><h3>Where Is Apache Kafka Used?</h3><p>Kafka is used in several real-world scenarios.</p><h4>1. Real-Time Analytics</h4><p>Applications can publish events to Kafka, allowing analytics systems to process them as they arrive. For example, an e-commerce company can monitor orders, revenue, and user activity in near real time.</p><h4>2. Log Aggregation</h4><p>Logs from multiple servers and applications can be sent to Kafka. They can then be consumed by monitoring, search, or analytics systems.</p><h4>3. Microservices Communication</h4><p>Services can exchange events without maintaining direct dependencies on every other service. For example, an order event can trigger payment, inventory, and notification workflows.</p><h4>4. Fraud Detection</h4><p>Financial transactions can be streamed to a processing application that checks for suspicious patterns.</p><h4>5. IoT Data Pipelines</h4><p>Sensors can continuously publish temperature, location, or device-status events. Kafka can act as the central event-streaming layer for downstream processing.</p><h4>6. Data Integration</h4><p>Kafka can connect operational databases, applications, and analytical systems through event streams. These use cases demonstrate why Kafka is important in modern data engineering.</p><h3>Advantages of Apache Kafka</h3><h4>1. High Throughput</h4><p>Kafka is designed to handle large volumes of event records using partitioning, batching, and efficient storage and transfer mechanisms.</p><h4>2. Scalability</h4><p>Topics can be divided into partitions and distributed across multiple brokers.</p><h4>3. Fault Tolerance</h4><p>Replication helps the system continue operating despite certain broker failures.</p><h4>4. Event Replay</h4><p>Consumers can re-read retained records using offsets.</p><h4>5. Loose Coupling</h4><p>Producers and consumers do not need direct knowledge of one another.</p><h4>6. Multiple Independent Consumers</h4><p>Different applications can consume the same topic using separate consumer groups.</p><h4>7. Integration Support</h4><p>Kafka Connect and the wider ecosystem make it useful for connecting different data systems.</p><h3>Limitations and Challenges of Kafka</h3><p>Kafka is powerful, but it is not free from complexity.</p><h4>1. Operational Complexity</h4><p>Managing brokers, partitions, replication, monitoring, and storage requires careful planning.</p><h4>2. Partition Design</h4><p>An unsuitable partitioning strategy can create uneven workloads or limit parallelism.</p><h4>3. Duplicate Processing</h4><p>Consumers may process an event more than once, especially when failures occur between processing and committing offsets. Applications must consider idempotency and duplicate handling.</p><h4>4. Ordering Limitations</h4><p>Kafka guarantees ordering within a partition, not across all partitions of a topic.</p><h4>5. Retention and Storage Costs</h4><p>Keeping large volumes of events for long periods requires storage planning.</p><h4>6. Not a Replacement for Every Database or Queue</h4><p>Kafka is designed for event streaming. It is not intended to replace relational databases, document databases, or every traditional message broker. Choosing Kafka simply because an application needs fast communication is not always justified.</p><h3>Delivery Semantics in Kafka</h3><p>One important topic in Kafka is how reliably events are delivered and processed.</p><p>Kafka supports different delivery and processing guarantees.</p><h4>At-Most-Once</h4><p>A record is processed zero or one time.</p><p>If a failure occurs at the wrong point, an event may be lost from the application’s processing perspective.</p><h4>At-Least-Once</h4><p>A record is processed one or more times.</p><p>This avoids losing processing work in many failure scenarios, but duplicates are possible.</p><h4>Exactly-Once Semantics</h4><p>Kafka supports mechanisms for exactly-once processing in certain Kafka-to-Kafka workflows using transactions and related producer/consumer configuration.</p><p>However, exactly-once behavior across arbitrary external systems is more complicated.</p><p>For example, writing to an external database and committing a Kafka offset are two separate operations. They need additional coordination or idempotent design to avoid duplicate side effects.</p><p>This is why exactly-once processing should not be treated as a guarantee that every business operation across every connected system happens exactly once automatically.</p><h3>Key Takeaways</h3><ul><li>Apache Kafka is a distributed event-streaming platform.</li><li>Events represent records of things that have happened.</li><li>Producers publish events, while consumers read and process them.</li><li>Brokers are Kafka servers that store and serve records.</li><li>Topics organize events into named streams.</li><li>Partitions distribute topic data and enable parallel processing.</li><li>Offsets track record positions within partitions.</li><li>Consumer groups allow multiple consumers to share the work.</li><li>Multiple consumer groups can independently read the same topic.</li><li>Kafka retains records according to configured policies rather than deleting them simply because they have been consumed.</li><li>Replication helps provide fault tolerance.</li><li>Kafka Streams supports stream-processing applications.</li><li>Kafka Connect integrates Kafka with external systems.</li><li>Kafka is useful for real-time pipelines, microservices, log aggregation, and analytics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5d_AXHgDM6ZGFaeQ0MyHIw.png" /><figcaption>Key Takeaways</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b270279f9af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MongoDB: The Document Database Built for Flexible Data]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-mongodb-the-document-database-built-for-flexible-data-0b9de953c826?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b9de953c826</guid>
            <category><![CDATA[cap]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 06:41:33 GMT</pubDate>
            <atom:updated>2026-11-24T06:41:33.354Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine building an e-commerce application. A product might have a name, price, description, images, and category. But some products also have additional information.</p><p>A laptop may have RAM, processor, and storage details, while a shirt may have size, color, and fabric information.</p><p>If we try to represent every product using exactly the same set of columns in a traditional relational database, we may end up with many optional columns or several related tables.</p><p>What if the database could store each product as a document, allowing different records to have different fields?</p><p>This is one of the ideas behind <strong>MongoDB</strong>.</p><p>MongoDB is a document-oriented NoSQL database designed to store and manage data in flexible, JSON-like documents. It is commonly used in applications where data structures evolve, records contain nested information, and developers need flexible ways to work with application data.</p><p>Let’s understand how MongoDB works and why it became an important part of the NoSQL ecosystem.</p><h3>1. What Is MongoDB?</h3><p><strong>MongoDB is an open-source, document-oriented NoSQL database.</strong></p><p>Instead of organizing data primarily into rows and columns, MongoDB stores data as documents inside collections.</p><p>A document contains fields and their corresponding values.</p><p>For example, a user document might look like this:</p><pre>{<br>  &quot;_id&quot;: 101,<br>  &quot;name&quot;: &quot;Shireen&quot;,<br>  &quot;city&quot;: &quot;Noida&quot;,<br>  &quot;skills&quot;: [&quot;Python&quot;, &quot;C++&quot;, &quot;SQL&quot;]<br>}</pre><p>This document represents one user.</p><p>Another user document can contain additional fields without requiring every document in the collection to have exactly the same structure.</p><p>MongoDB is commonly associated with:</p><ul><li>Document-based data storage</li><li>Flexible schemas</li><li>JSON-like data representation</li><li>Nested objects and arrays</li><li>Powerful querying and aggregation</li><li>Indexing</li><li>Replication and sharding</li></ul><p>In simple terms:</p><p><strong>MongoDB = Document-Oriented Storage + Flexible Data Model + Distributed Database Capabilities</strong></p><h3>2. Why Do We Need MongoDB?</h3><p>Let’s return to our e-commerce application. Suppose we have three products:</p><p><strong>Product A: Laptop</strong></p><pre>{<br>  &quot;name&quot;: &quot;Laptop&quot;,<br>  &quot;price&quot;: 65000,<br>  &quot;ram&quot;: &quot;16GB&quot;,<br>  &quot;storage&quot;: &quot;512GB SSD&quot;<br>}</pre><p><strong>Product B: T-shirt</strong></p><pre>{<br>  &quot;name&quot;: &quot;T-shirt&quot;,<br>  &quot;price&quot;: 799,<br>  &quot;size&quot;: &quot;M&quot;,<br>  &quot;color&quot;: &quot;Blue&quot;<br>}</pre><p><strong>Product C: Book</strong></p><pre>{<br>  &quot;name&quot;: &quot;Book&quot;,<br>  &quot;price&quot;: 499,<br>  &quot;author&quot;: &quot;Example Author&quot;,<br>  &quot;publisher&quot;: &quot;Example Publications&quot;<br>}</pre><p>Each product has different attributes.</p><p>A rigid relational schema could still represent this data, but it might require several tables, optional columns, or additional relationships.</p><p>MongoDB allows these product records to be stored as documents with different fields.</p><p>This makes it convenient for applications where data structures vary or evolve frequently.</p><p>However, flexible schemas do not mean that data modeling becomes unnecessary. Developers still need to decide how documents should be structured, validated, and queried.</p><h3>3. MongoDB vs Relational Databases</h3><p>Before understanding MongoDB’s architecture, let’s compare its basic data model with a relational database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*X5a6QZlYwR7CNBij1RUeow.png" /></figure><p>For example, consider a relational table:</p><p><strong>Users</strong></p><p>user_id name city</p><p>101 Riya Noida</p><p>102 Aditi Delhi</p><p>The equivalent MongoDB collection could contain:</p><pre>[<br>  {<br>    &quot;_id&quot;: 101,<br>    &quot;name&quot;: &quot;Riya&quot;,<br>    &quot;city&quot;: &quot;Noida&quot;<br>  },<br>  {<br>    &quot;_id&quot;: 102,<br>    &quot;name&quot;: &quot;Aditi&quot;,<br>    &quot;city&quot;: &quot;Delhi&quot;<br>  }<br>]</pre><p>The important difference is that MongoDB documents can contain nested structures and arrays directly. This can reduce the need to split closely related information across multiple tables.</p><h3>4. Understanding Documents and Collections</h3><p>Two concepts form the foundation of MongoDB: documents and collections.</p><h3>Documents</h3><p>A document is an individual record stored in MongoDB. It contains fields and values, similar to a JSON object.</p><p>Example:</p><pre>{<br>  &quot;_id&quot;: 101,<br>  &quot;name&quot;: &quot;Riya&quot;,<br>  &quot;age&quot;: 21,<br>  &quot;skills&quot;: [&quot;Python&quot;, &quot;C++&quot;, &quot;SQL&quot;],<br>  &quot;address&quot;: {<br>    &quot;city&quot;: &quot;Noida&quot;,<br>    &quot;state&quot;: &quot;Uttar Pradesh&quot;<br>  }<br>}</pre><p>Notice that the document contains:</p><ul><li>Simple values such as name and age</li><li>An array containing multiple skills</li><li>A nested object containing address information</li></ul><p>This is one of MongoDB’s important features: documents can represent hierarchical data naturally.</p><h3>Collections</h3><p>A collection is a group of MongoDB documents.</p><p>For example:</p><pre>Database: University<br>        |<br>        ├── Collection: Students<br>        |       ├── Document 1<br>        |       ├── Document 2<br>        |       └── Document 3<br>        |<br>        ├── Collection: Courses<br>        |       ├── Document 1<br>        |       └── Document 2<br>        |<br>        └── Collection: Teachers<br>                ├── Document 1<br>                └── Document 2</pre><p>Unlike a relational table, a collection does not require every document to have an identical set of fields by default. MongoDB also supports schema validation when an application needs to enforce particular structures.</p><h3>5. What Is BSON?</h3><p>MongoDB stores documents internally using a format called <strong>BSON</strong>, which stands for Binary JSON.</p><p>Although MongoDB documents are commonly represented using JSON-like syntax, BSON is the binary-encoded format used for storage and data interchange within MongoDB’s document model.</p><p>Why not simply use JSON?</p><p>BSON provides additional data types and a representation designed for efficient processing.</p><p>For example, BSON supports types such as:</p><ul><li>Strings</li><li>Integers</li><li>Doubles</li><li>Booleans</li><li>Dates</li><li>Binary data</li><li>Object identifiers</li><li>Embedded documents</li><li>Arrays</li></ul><p>Consider:</p><pre>{<br>  &quot;name&quot;: &quot;Monika&quot;,<br>  &quot;age&quot;: 21,<br>  &quot;active&quot;: true<br>}</pre><p>This looks like JSON, but MongoDB represents the document using BSON internally.</p><h3>JSON vs BSON</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*_OVL0l_xnqiE2vyA-FcRLg.png" /></figure><p>BSON is not simply a compressed version of JSON. It has its own encoding format and type system.</p><h3>6. The _id Field</h3><p>Every MongoDB document must have a unique _id field within its collection. If an application does not provide one, MongoDB normally generates an ObjectId.</p><p>Example:</p><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;507f1f77bcf86cd799439011&quot;),<br>  &quot;name&quot;: &quot;Riya&quot;,<br>  &quot;city&quot;: &quot;Noida&quot;<br>}</pre><p>An ObjectId is a BSON type commonly used as a document identifier. It is designed to be highly likely to be unique across generated identifiers. The _id field also has a unique index by default, allowing documents to be efficiently retrieved using their identifiers.</p><h3>7. Embedding vs Referencing</h3><p>This is one of the most important decisions in MongoDB data modeling. When documents are related, we can represent those relationships in two main ways.</p><h3>Embedding</h3><p>Embedding means storing related information inside the same document.</p><p>For example:</p><pre>{<br>  &quot;_id&quot;: 101,<br>  &quot;name&quot;: &quot;Riya&quot;,<br>  &quot;address&quot;: {<br>    &quot;city&quot;: &quot;Noida&quot;,<br>    &quot;state&quot;: &quot;Uttar Pradesh&quot;<br>  },<br>  &quot;skills&quot;: [&quot;Python&quot;, &quot;C++&quot;, &quot;SQL&quot;]<br>}</pre><p>The user’s address and skills are stored directly inside the user document.</p><p><strong>Advantages:</strong></p><ul><li>Related information can be retrieved together.</li><li>Fewer separate queries may be required.</li><li>Updates to a single document are atomic.</li></ul><p><strong>Suitable when:</strong></p><ul><li>Related information is frequently accessed together.</li><li>The embedded data has a manageable size.</li><li>The relationship naturally belongs to one document.</li></ul><h3>Referencing</h3><p>Referencing means storing identifiers that point to documents in another collection.</p><p>For example:</p><p><strong>Students collection</strong></p><pre>{<br>  &quot;_id&quot;: 101,<br>  &quot;name&quot;: &quot;Riya&quot;,<br>  &quot;course_id&quot;: 501<br>}</pre><p><strong>Courses collection</strong></p><pre>{<br>  &quot;_id&quot;: 501,<br>  &quot;course_name&quot;: &quot;Computer Science&quot;<br>}</pre><p>The student document stores the course identifier rather than embedding the entire course document.</p><p><strong>Advantages:</strong></p><ul><li>Avoids unnecessary duplication.</li><li>Useful for shared or independently updated information.</li><li>Helps represent certain one-to-many and many-to-many relationships.</li></ul><p><strong>Suitable when:</strong></p><ul><li>Related data is large.</li><li>Data is frequently updated independently.</li><li>Multiple documents share the same related information.</li></ul><p>The decision between embedding and referencing depends on access patterns, update frequency, document size, and relationship structure.</p><p>MongoDB does not require us to avoid relationships. It simply gives us different ways to model them.</p><h3>8. Basic MongoDB Operations</h3><p>MongoDB supports CRUD operations:</p><ul><li>Create</li><li>Read</li><li>Update</li><li>Delete</li></ul><p>Let’s understand them using a students collection.</p><h3>Create: Insert Documents</h3><p>Insert one document:</p><pre>db.students.insertOne({<br>    name: &quot;Riya&quot;,<br>    branch: &quot;CSE&quot;,<br>    city: &quot;Noida&quot;<br>});</pre><p>Insert multiple documents:</p><pre>db.students.insertMany([<br>    {<br>        name: &quot;Aditi&quot;,<br>        branch: &quot;CSE&quot;<br>    },<br>    {<br>        name: &quot;Rahul&quot;,<br>        branch: &quot;ECE&quot;<br>    }<br>]);</pre><h3>Read: Find Documents</h3><p>Retrieve all documents:</p><pre>db.students.find();</pre><p>Find students from CSE:</p><pre>db.students.find({<br>    branch: &quot;CSE&quot;<br>});</pre><p>Retrieve a single matching document:</p><pre>db.students.findOne({<br>    name: &quot;Riya&quot;<br>});</pre><h3>Update: Modify Documents</h3><p>Update a student’s city:</p><pre>db.students.updateOne(<br>    { name: &quot;Riya&quot; },<br>    { $set: { city: &quot;Delhi&quot; } }<br>);</pre><p>Here, $set updates the specified field without replacing the entire document.</p><h3>Delete: Remove Documents</h3><p>Delete a matching document:</p><pre>db.students.deleteOne({<br>    name: &quot;Riya&quot;<br>});</pre><p>These operations form the foundation of working with MongoDB.</p><h3>9. Querying and Filtering Documents</h3><p>MongoDB provides query operators that allow applications to filter documents based on conditions.</p><p>For example, suppose we want to find students whose age is greater than 20.</p><pre>db.students.find({<br>    age: { $gt: 20 }<br>});</pre><p>Some commonly used query operators include:</p><p>OperatorMeaning$eqEqual to$neNot equal to$gtGreater than$gteGreater than or equal to$ltLess than$lteLess than or equal to$inMatches any value in an array$andLogical AND$orLogical OR</p><p>Example using $in:</p><pre>db.students.find({<br>    branch: { $in: [&quot;CSE&quot;, &quot;IT&quot;] }<br>});</pre><p>This retrieves documents where the branch is either CSE or IT.</p><p>MongoDB also supports projections, which allow us to return only the fields we need.</p><pre>db.students.find(<br>    { branch: &quot;CSE&quot; },<br>    { name: 1, city: 1, _id: 0 }<br>);</pre><p>This returns the name and city fields while excluding _id.</p><h3>10. Indexing in MongoDB</h3><p>Imagine a collection containing ten million student documents.</p><p>If we frequently search for a student using their email address, scanning every document would be inefficient.</p><p>This is where indexing helps.</p><p>An <strong>index</strong> is a data structure that allows MongoDB to locate matching documents more efficiently.</p><p>Without an index:</p><pre>Query<br>  |<br>  v<br>Scan Documents<br>  |<br>  v<br>Find Matching Record</pre><p>With an index:</p><pre>Query<br>  |<br>  v<br>Search Index<br>  |<br>  v<br>Locate Matching Document</pre><p>Create an index on the email field:</p><pre>db.students.createIndex({<br>    email: 1<br>});</pre><p>Here:</p><ul><li>1 represents ascending order.</li><li>-1 represents descending order.</li></ul><p>To create a unique index:</p><pre>db.students.createIndex(<br>    { email: 1 },<br>    { unique: true }<br>);</pre><p>This prevents duplicate indexed email values, subject to the index’s handling of missing and null fields.</p><h3>Types of MongoDB Indexes</h3><p>MongoDB supports several index types:</p><p><strong>1. Single Field Index</strong></p><p>Indexes one field.</p><pre>db.students.createIndex({ name: 1 });</pre><p><strong>2. Compound Index</strong></p><p>Indexes multiple fields.</p><pre>db.students.createIndex({<br>    branch: 1,<br>    age: -1<br>});</pre><p><strong>3. Multikey Index</strong></p><p>Used when indexing fields that contain arrays.</p><p><strong>4. Text Index</strong></p><p>Supports text search on indexed string fields.</p><p><strong>5. Geospatial Index</strong></p><p>Supports location-based queries.</p><p>Indexes improve read performance for suitable queries, but they also consume storage and add overhead to writes because the indexes must be maintained.</p><p>Therefore, creating indexes on every field is not a good strategy.</p><h3>11. Aggregation Framework</h3><p>MongoDB is not limited to retrieving individual documents. It also provides an <strong>Aggregation Framework</strong> for processing documents and producing summarized results.</p><p>Aggregation works through a sequence of stages called a pipeline. Each stage performs an operation and passes its output to the next stage.</p><p>For example, imagine an orders collection:</p><pre>[<br>  {<br>    &quot;customer&quot;: &quot;A&quot;,<br>    &quot;amount&quot;: 1000,<br>    &quot;status&quot;: &quot;Completed&quot;<br>  },<br>  {<br>    &quot;customer&quot;: &quot;B&quot;,<br>    &quot;amount&quot;: 1500,<br>    &quot;status&quot;: &quot;Completed&quot;<br>  },<br>  {<br>    &quot;customer&quot;: &quot;A&quot;,<br>    &quot;amount&quot;: 500,<br>    &quot;status&quot;: &quot;Pending&quot;<br>  }<br>]</pre><p>Suppose we want to calculate the total completed order amount for each customer.</p><p>We can use:</p><pre>db.orders.aggregate([<br>    {<br>        $match: {<br>            status: &quot;Completed&quot;<br>        }<br>    },<br>    {<br>        $group: {<br>            _id: &quot;$customer&quot;,<br>            totalAmount: {<br>                $sum: &quot;$amount&quot;<br>            }<br>        }<br>    },<br>    {<br>        $sort: {<br>            totalAmount: -1<br>        }<br>    }<br>]);</pre><p>Let’s understand the stages.</p><h3>$match</h3><p>Filters documents based on conditions. Here, only completed orders are selected.</p><h3>$group</h3><p>Groups documents based on a specified field. Here, documents are grouped by customer.</p><h3>$sum</h3><p>Calculates the total amount for each group.</p><h3>$sort</h3><p>Sorts the resulting groups by total amount in descending order.</p><p>The output would conceptually look like:</p><pre>[<br>  {<br>    &quot;_id&quot;: &quot;B&quot;,<br>    &quot;totalAmount&quot;: 1500<br>  },<br>  {<br>    &quot;_id&quot;: &quot;A&quot;,<br>    &quot;totalAmount&quot;: 1000<br>  }<br>]</pre><p>Other commonly used aggregation stages include:</p><ul><li>$project – selects or reshapes fields.</li><li>$limit – limits the number of output documents.</li><li>$skip – skips a specified number of documents.</li><li>$unwind – expands array elements into separate documents.</li><li>$lookup – performs a left outer join with another collection.</li></ul><p>Aggregation makes MongoDB useful for application-level summaries and data transformation tasks.</p><h3>12. Transactions in MongoDB</h3><p>One common misconception is that NoSQL databases cannot support transactions.</p><p>MongoDB supports atomic operations at the single-document level and also supports multi-document transactions.</p><h3>Single-Document Atomicity</h3><p>Consider a document containing a user’s account details:</p><pre>{<br>  &quot;_id&quot;: 101,<br>  &quot;balance&quot;: 5000,<br>  &quot;status&quot;: &quot;active&quot;<br>}</pre><p>An update to this document is atomic: other operations do not observe a partially applied document update.</p><h3>Multi-Document Transactions</h3><p>Now consider transferring money between two accounts.</p><p>The application must:</p><ol><li>Deduct money from Account A.</li><li>Add money to Account B.</li></ol><p>Both operations should succeed together, or the transaction should be rolled back.</p><p>MongoDB supports multi-document transactions for this type of requirement.</p><p>Conceptually:</p><pre>Start Transaction<br>       |<br>       v<br>Update Account A<br>       |<br>       v<br>Update Account B<br>       |<br>       v<br>Both Successful?<br>     /     \<br>   Yes      No<br>    |        |<br> Commit    Abort</pre><p>Transactions are useful when an operation spans multiple documents or collections and requires atomicity.</p><p>However, they introduce additional coordination and performance costs. Good document modeling can sometimes avoid the need for multi-document transactions.</p><h3>13. Replication in MongoDB</h3><p>What happens if the server storing our database fails?</p><p>MongoDB supports replication through a mechanism called a <strong>replica set</strong>.</p><p>A replica set is a group of MongoDB servers that maintain copies of the same dataset.</p><p>A typical replica set contains:</p><ul><li>One primary</li><li>One or more secondary members</li></ul><p>A simplified architecture:</p><pre>                Replica Set<br>                     |<br>             ┌───────┴───────┐<br>             v               v<br>          Primary         Secondary<br>             |               |<br>             |------&gt;--------|<br>                             |<br>                             v<br>                         Secondary</pre><h3>Primary</h3><p>The primary receives write operations.</p><h3>Secondary</h3><p>Secondary members replicate changes from the primary’s operation log, known as the oplog. They maintain copies of the dataset and can participate in failover.</p><h3>Automatic Failover</h3><p>If the primary becomes unavailable, eligible members can participate in an election to select a new primary. This allows the replica set to continue operating after certain failures.</p><p>Replication supports availability and redundancy, but it does not mean every read from every secondary will always return the latest write. Read preferences, write concerns, and replication lag influence the guarantees.</p><h3>14. Sharding in MongoDB</h3><p>Replication helps maintain copies of data, but what if the dataset becomes too large for one server? This is where <strong>sharding</strong> comes in.</p><p>Sharding distributes data across multiple machines.</p><p>Instead of storing the entire dataset on one server, MongoDB divides it into smaller portions called chunks and distributes them across shards.</p><p>A simplified architecture:</p><pre>              Application<br>                   |<br>                   v<br>              mongos Router<br>                   |<br>          ┌────────┼────────┐<br>          v        v        v<br>        Shard 1  Shard 2  Shard 3<br>          |        |        |<br>        Data A   Data B   Data C</pre><h3>Shard</h3><p>A shard stores a portion of the sharded dataset. In a production sharded cluster, each shard is commonly deployed as a replica set.</p><h3>mongos</h3><p>The query router receives application requests and directs them to the appropriate shard or shards.</p><h3>Config Servers</h3><p>Config servers store metadata about the sharded cluster, including information about data distribution.</p><h3>Shard Key</h3><p>A shard key is the field or combination of fields used to distribute documents across shards.</p><p>Choosing the right shard key is important.</p><p>A poor shard key can create uneven data distribution or concentrate too much traffic on a small number of shards.</p><h3>Why Is Sharding Useful?</h3><ul><li>Distributes large datasets across machines.</li><li>Allows storage capacity to grow horizontally.</li><li>Can distribute read and write workloads.</li><li>Supports applications that need to scale beyond a single server.</li></ul><p>However, sharding also introduces operational and query-routing complexity.</p><h3>15. MongoDB Architecture: Putting It Together</h3><p>Let’s connect the major components.</p><pre>                  Application<br>                       |<br>                       v<br>                  MongoDB Driver<br>                       |<br>                       v<br>                   mongos Router<br>                       |<br>              ┌────────┼────────┐<br>              v        v        v<br>           Shard 1   Shard 2   Shard 3<br>              |        |        |<br>          Replica   Replica   Replica<br>             Set       Set       Set</pre><p>This represents a sharded MongoDB deployment.</p><p>For a simpler, non-sharded deployment, an application can connect directly to a replica set through a MongoDB driver.</p><p>The architecture chosen depends on the application’s scale, availability requirements, and data distribution needs.</p><h3>16. MongoDB and CAP Theorem</h3><p>We previously studied CAP Theorem and PACELC, so let’s connect MongoDB to those concepts.</p><p>MongoDB deployments use replica sets and distributed coordination to support availability and data consistency.</p><p>During normal operation, the primary handles writes, and the system replicates changes to secondary members.</p><p>During a network partition, the system’s ability to accept writes depends on whether a member can maintain the required voting majority and become or remain primary.</p><p>For example:</p><ul><li>A partitioned member without a majority cannot independently continue accepting primary writes.</li><li>A majority partition can elect or retain a primary.</li><li>Some reads may be served by secondary members, depending on read preferences and consistency settings.</li></ul><p>This means MongoDB’s behavior should not be reduced to a simple claim that every deployment is always CP or always AP.</p><p>The actual guarantees depend on replica-set configuration, read preference, read concern, and write concern.</p><p>The broader lesson is that <strong>consistency and availability are influenced by the choices made in a distributed database deployment</strong>.</p><h3>17. MongoDB vs Other NoSQL Databases</h3><p>We have already explored HBase and Redis. Let’s see how MongoDB differs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*v-YdLB1fRBnewan7rt-HTg.png" /></figure><p>These systems solve different problems.</p><p>MongoDB is useful when an application needs flexible document storage and rich document queries.</p><p>HBase is useful for large-scale wide-column workloads.</p><p>Redis is useful when fast access to application state and specialized in-memory data structures is important.</p><h3>18. MongoDB vs SQL Databases</h3><p>Let’s compare MongoDB with a relational database more directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*63fzfgmgtB9uTEM7yRgttg.png" /></figure><p>Neither model is universally better.</p><p>A relational database may be a better choice when data has many complex relationships and the application depends heavily on joins and relational constraints.</p><p>MongoDB may be a better fit when data is naturally represented as documents and the application benefits from flexible structures and document-level operations.</p><p>The decision should come from the application’s data model and access patterns.</p><h3>19. Advantages of MongoDB</h3><h4>1. Flexible Schema</h4><p>Documents in a collection can have different fields, which is useful when application requirements evolve.</p><h4>2. Natural Representation of Hierarchical Data</h4><p>Nested documents and arrays make it easier to represent certain real-world objects.</p><h4>3. Rich Query Capabilities</h4><p>MongoDB supports filtering, sorting, projections, indexes, and aggregation.</p><h4>4. Horizontal Scaling</h4><p>Sharding allows data to be distributed across multiple machines.</p><h4>5. High Availability</h4><p>Replica sets provide redundancy and support automatic failover.</p><h4>6. Developer-Friendly Data Model</h4><p>JSON-like document representation makes MongoDB convenient for many application-development workflows.</p><h3>20. Limitations of MongoDB</h3><p>MongoDB also has limitations.</p><h4>1. Flexible Schema Requires Discipline</h4><p>Without appropriate validation and data-modeling practices, documents can become inconsistent.</p><h4>2. Data Duplication</h4><p>Embedding related information can lead to duplication when the same information appears in multiple documents.</p><h4>3. Complex Relationships</h4><p>Applications with many interconnected entities may find relational databases more natural.</p><h4>4. Indexing Overhead</h4><p>Indexes consume storage and increase the cost of write operations.</p><h4>5. Sharding Complexity</h4><p>Choosing shard keys, balancing data, and handling distributed queries require careful planning.</p><h4>6. Transaction Costs</h4><p>Although MongoDB supports multi-document transactions, using them extensively can introduce coordination overhead.</p><p>MongoDB is powerful, but its flexibility should not be confused with the absence of database-design requirements.</p><h3>21. When Should We Use MongoDB?</h3><p>MongoDB is a good candidate when:</p><ul><li>Data is naturally represented as documents.</li><li>Records contain nested objects or arrays.</li><li>Different records have different attributes.</li><li>The application’s schema evolves frequently.</li><li>Developers need flexible document queries and aggregation.</li><li>The application may benefit from horizontal scaling.</li></ul><p>For example, an e-commerce platform with different product categories can represent each product using a document containing category-specific fields. This avoids forcing every product into exactly the same structure.</p><h3>22. When Should We Avoid MongoDB?</h3><p>MongoDB may not be the best choice when:</p><ul><li>The application depends heavily on complex relational joins.</li><li>Strong relational constraints are central to the data model.</li><li>The workload is naturally suited to a specialized graph or column-family database.</li><li>The application requires analytical capabilities better provided by a dedicated OLAP system.</li><li>The team cannot properly manage document design, indexing, and distributed deployment.</li></ul><p>Choosing a database based only on popularity is not a good engineering decision. The database should match the actual workload.</p><h3>23. How MongoDB Fits into the Big Data Ecosystem</h3><p>Let’s connect MongoDB with the technologies we’ve studied.</p><pre>                 NoSQL Databases<br>                        |<br>          ┌─────────────┼─────────────┐<br>          v             v             v<br>        HBase         Redis        MongoDB<br>          |             |             |<br>     Wide-Column     In-Memory      Document<br>       Storage       Operations     Storage<br>          |             |             |<br>          └─────────────┼─────────────┘<br>                        v<br>              Distributed Applications</pre><p>Each database uses a different data model to solve different problems.</p><ul><li><strong>HBase</strong> is designed for large-scale wide-column data storage.</li><li><strong>Redis</strong> provides fast in-memory operations and specialized data structures.</li><li><strong>MongoDB</strong> provides flexible document-oriented storage.</li></ul><p>Together, they demonstrate why NoSQL is not one single database architecture.</p><p>It is a collection of approaches designed around different application requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QJQFquJiAF2vOHjSArQ1g.png" /><figcaption>Key Takeaways</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b9de953c826" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Redis: The In-Memory Data Store Behind Fast Applications]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-redis-the-in-memory-data-store-behind-fast-applications-9f5953940c7c?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f5953940c7c</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[redis-cluster]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[memcached]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 13:35:23 GMT</pubDate>
            <atom:updated>2026-10-26T13:35:23.724Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine opening an application and expecting your data to load almost instantly.</p><p>You check your notifications, view a product page, log in, or refresh your news feed. Behind the scenes, the application may need to retrieve information thousands or even millions of times.</p><p>Now imagine that every request has to query the main database, process the result, and return it to the user.</p><p>As the number of users grows, this repeated work can increase database load and response time.</p><p>What if frequently accessed data could be stored somewhere that allows extremely fast access?</p><p>This is one of the problems <strong>Redis</strong> helps solve.</p><p>Redis is widely used for caching, real-time data processing, counters, session storage, and other workloads where fast access to data is important.</p><p>But Redis is more than just a cache. Let’s understand how it works.</p><h3>What Is Redis?</h3><p><strong>Redis</strong> is an in-memory data store that supports multiple data structures and provides very fast read and write operations.</p><p>The name originally stood for <em>Remote Dictionary Server</em>.</p><p>Redis is commonly used as:</p><ul><li>A cache</li><li>A key-value data store</li><li>A session store</li><li>A real-time counter system</li><li>A queue or stream data store</li><li>A component in distributed applications</li></ul><p>Its central idea is straightforward: <strong>Store data in structures that can be accessed and updated efficiently, primarily in memory.</strong></p><p>For example, Redis can store a user’s session using a key:</p><pre>Key: session:101<br>Value: user information</pre><p>An application can retrieve the value using the key without performing a more expensive query against its main database. Redis also supports richer structures, including lists, sets, sorted sets, hashes, and streams.</p><h3>Why Do We Need Redis?</h3><p>Consider an e-commerce website with one million users.</p><p>Many users repeatedly access the same information:</p><ul><li>Product details</li><li>Popular categories</li><li>User sessions</li><li>Shopping cart information</li><li>Frequently requested recommendations</li></ul><p>If every request goes directly to the primary database, the database must repeatedly perform similar work.</p><p>A simplified architecture looks like this:</p><pre>            Users<br>               |<br>               v<br>          Application<br>               |<br>               v<br>          Main Database</pre><p>As traffic grows, the database can become a bottleneck.</p><p>Now introduce Redis:</p><pre>             Users<br>               |<br>               v<br>          Application<br>               |<br>               v<br>             Redis<br>           /       \<br>      Cache Hit   Cache Miss<br>          |           |<br>          v           v<br>       Return     Main Database<br>       Result          |<br>                       v<br>                 Store in Redis</pre><p>When the requested data is already in Redis, the application can return it without querying the main database. When the data is missing, the application fetches it from the database and may cache it for future requests. This pattern is called <strong>caching</strong>.</p><h3>What Makes Redis Fast?</h3><p>Redis achieves high performance through several design choices.</p><h4>In-memory data access</h4><p>Redis keeps its active dataset in memory, avoiding the need to access persistent storage for every ordinary operation.</p><h4>Efficient data structures</h4><p>Instead of treating every value as an arbitrary block of data, Redis provides specialized structures such as hashes, lists, sets, and sorted sets.</p><h4>Lightweight operations</h4><p>Many common operations are simple and efficient, such as retrieving a key, incrementing a counter, or adding an item to a set.</p><h4>Event-driven request processing</h4><p>Redis uses an event-driven architecture to handle client connections and requests efficiently.</p><p>The exact performance depends on the operation, data size, hardware, network, persistence settings, and deployment. The key idea is that Redis is optimized for fast access to data and efficient execution of supported operations.</p><h3>Redis as a Key-Value Store</h3><p>At its simplest, Redis stores data using keys and values.</p><pre>Key                 Value<br>--------------------------------<br>user:101            Sakshi<br>user:102            Aditi<br>user:103            Rahul</pre><p>To retrieve a value, the application provides its key.</p><p>For example:</p><pre>GET user:101</pre><p>The result is:</p><pre>&quot;Sakshi&quot;</pre><p>Keys can follow naming conventions that make the data easier to organize.</p><p>Examples:</p><pre>user:101<br>session:abc123<br>product:501<br>cache:homepage</pre><p>This key-value model makes Redis useful for fast lookups.</p><h4>Redis Data Structures</h4><p>One of Redis’s most important features is its support for multiple data structures.</p><p>Different structures are useful for different kinds of problems.<br> <strong>1. Strings: </strong>Store text, numbers, serialized data, or other byte sequences.<br><strong> 2. Lists: </strong>Ordered sequences of strings that support operations at either end.<br><strong> 3. Sets: </strong>Collections of unique strings.<br><strong>4. Sorted Sets: </strong>Unique members associated with scores, ordered by score.<br><strong> 5. Hashes: </strong>Field-value mappings stored under a single key.<br><strong>6. Streams: </strong>Append-oriented data structures for recording ordered entries.</p><p>Choosing the right structure can make an operation much simpler and more efficient.</p><h3>Basic Redis Commands</h3><p>Let’s look at a few common commands.</p><h4>Strings</h4><p>Set and retrieve a value:</p><pre>SET user:101 &quot;Shreya&quot;<br>GET user:101</pre><p>Output:</p><pre>&quot;Shreya&quot;</pre><h4>Counters</h4><p>Redis can increment a numeric value atomically:</p><pre>SET page_views 0<br>INCR page_views<br>INCR page_views<br>GET page_views</pre><p>Result:</p><pre>&quot;2&quot;</pre><p>This is useful for counters, provided the application’s durability and correctness requirements are also considered.</p><h4>Expiration</h4><p>Set a value that expires after 60 seconds:</p><pre>SET otp:101 &quot;482913&quot; EX 60</pre><p>After the expiration period, the key becomes eligible for removal. This is useful for temporary values, such as one-time codes and short-lived cache entries.</p><h4>Hashes</h4><p>Store multiple fields under one key:</p><pre>HSET user:101 name &quot;Shreya&quot; city &quot;Noida&quot;<br>HGET user:101 name<br>HGETALL user:101</pre><h4>Sets</h4><p>Store unique members:</p><pre>SADD course:redis user:101 user:102 user:103<br>SADD course:redis user:101<br>SMEMBERS course:redis</pre><p>Adding user:101 a second time does not create a duplicate member.</p><p>These commands illustrate how Redis structures can represent different kinds of application data.</p><h3>Redis as a Cache</h3><p>Caching is one of Redis’s most common uses. A <strong>cache</strong> stores a copy of data so it can be retrieved more quickly than if it were fetched from the original source every time. Consider a news application that repeatedly requests the latest articles.</p><p>Without caching:</p><pre>Request<br>   |<br>   v<br>Application<br>   |<br>   v<br>Database Query<br>   |<br>   v<br>Return Articles</pre><p>With caching:</p><pre>Request<br>   |<br>   v<br>Application<br>   |<br>   v<br>Check Redis<br>   |<br>   +---- Cache Hit ------&gt; Return Cached Articles<br>   |<br>   +---- Cache Miss -----&gt; Query Database<br>                              |<br>                              v<br>                        Store in Redis<br>                              |<br>                              v<br>                         Return Articles</pre><p>If the same data is requested frequently, caching can reduce database load and improve response times. However, the cache must be managed carefully so that users do not keep receiving outdated data.</p><h3>Cache Hit vs Cache Miss</h3><p>Two terms are especially important.</p><h4>Cache Hit</h4><p>The requested data exists in the cache.</p><pre>Application → Redis → Data Found</pre><p>The application can return the cached result.</p><h4>Cache Miss</h4><p>The requested data is not available in the cache.</p><pre>Application → Redis → Not Found<br>                         |<br>                         v<br>                      Database<br>                         |<br>                         v<br>                    Update Cache</pre><p>The application fetches the data from the original source and may store it in Redis.</p><p>A higher cache-hit rate can reduce the number of database queries, although the ideal hit rate depends on the workload.</p><h3>Cache-Aside Pattern</h3><p>One widely used caching strategy is <strong>cache-aside</strong>, also known as lazy loading.</p><p>The application manages the cache explicitly.</p><p>The general flow is:</p><ol><li>Check Redis for the requested data.</li><li>If it exists, return it.</li><li>Otherwise, fetch the data from the database.</li><li>Store the result in Redis.</li><li>Return the result.</li></ol><p>Pseudocode:</p><pre>def get_product(product_id):<br>    product = redis.get(f&quot;product:{product_id}&quot;)<br>       if product is not None:<br>        return product<br><br>       product = database.get_product(product_id)<br>       if product is not None:<br>        redis.set(<br>            f&quot;product:{product_id}&quot;,<br>            serialize(product),<br>            ex=300<br>        )<br>    return product</pre><p>Here, serialize() represents an application-defined conversion into a storable format. The cache entry expires after 300 seconds.</p><p>This example is conceptual: production code also needs to handle Redis failures, serialization, database errors, and cache invalidation.</p><h4>Why use expiration?</h4><p>Suppose a product’s price changes in the database. If Redis stores the old price indefinitely, the application may keep returning stale information. A time-to-live (TTL) limits how long the cached value remains available before expiration. TTL reduces the lifetime of stale data, but it does not guarantee immediate consistency.</p><h3>Cache Invalidation</h3><p>Caching introduces an important challenge: <strong>How do we keep cached data aligned with the source of truth?</strong></p><p>Suppose a product’s price changes from ₹999 to ₹899. The database is updated, but Redis still contains ₹999. The application may temporarily return the old price.</p><p>Common approaches include:</p><h4>TTL-based expiration</h4><p>Allow cached data to expire after a configured duration.</p><h4>Explicit invalidation</h4><p>Delete the cache entry when the underlying data changes.</p><pre>DEL product:501</pre><p>The next request can fetch the updated value from the database.</p><h4>Update the cache</h4><p>Update the database and cache through an application-managed process. This requires careful handling of failures and ordering. There is no single strategy that works best for every application. The correct choice depends on how stale the data is allowed to be.</p><h3>Redis and TTL</h3><p>TTL stands for <strong>Time To Live</strong>. It specifies how long a key should remain available before expiring.</p><p>For example:</p><pre>SET session:101 &quot;active&quot; EX 1800<br>TTL session:101</pre><p>Here, the session key is configured to expire after 1,800 seconds, or 30 minutes.</p><p>TTL is useful for:</p><ul><li>Sessions</li><li>Temporary verification codes</li><li>Cached database results</li><li>Temporary locks</li><li>Short-lived application state</li></ul><p>One important detail: expiration does not always mean the key disappears at the exact instant its TTL reaches zero. Redis handles expiration internally, and the key is no longer considered valid after it expires.</p><p>TTL is a powerful way to manage temporary data without requiring the application to delete every key manually.</p><h3>Redis as a Session Store</h3><p>Many applications need to remember information about a logged-in user.</p><p>For example:</p><pre>session:abc123<br>    |<br>    ├── user_id: 101<br>    ├── role: student<br>    └── status: active</pre><p>Redis can store session-related data so application servers can retrieve it quickly. This is especially useful when an application has multiple servers.</p><pre>              User<br>                |<br>                v<br>          Load Balancer<br>           /         \<br>          v           v<br>     App Server A  App Server B<br>           \         /<br>            \       /<br>              Redis</pre><p>Either application server can access the shared session store. The application does not have to rely exclusively on in-memory session data stored inside one particular server. Session expiration, access controls, secure cookie handling, and recovery requirements still need to be designed correctly.</p><h3>Redis for Rate Limiting</h3><p>A rate limiter controls how many requests a user or client can make during a period. For example, an API might allow a user to make 100 requests per minute. Redis can help implement rate limiting because operations such as incrementing a counter are atomic.</p><p>A simplified example:</p><pre>INCR rate:user:101<br>EXPIRE rate:user:101 60</pre><p>This increments a counter and sets an expiration.</p><p>However, these two commands alone are not a complete production-grade rate limiter. In a real implementation, counter creation, expiration, and limit checking must be coordinated carefully, often using a Lua script or another atomic approach. Redis is useful here because multiple application servers can share the same rate-limit state. That makes the rate limit consistent across instances rather than giving each server an independent counter.</p><h3>Redis for Leaderboards</h3><p>Sorted sets are especially useful for rankings.</p><p>Suppose a gaming application tracks player scores.</p><pre>ZADD leaderboard 950 player:101<br>ZADD leaderboard 1200 player:102<br>ZADD leaderboard 870 player:103</pre><p>Each player is a unique member, and the score determines their position in the ordering.</p><p>You can retrieve players with the highest scores:</p><pre>ZREVRANGE leaderboard 0 2 WITHSCORES</pre><p>This returns up to three members in descending score order.</p><p>Sorted sets make it convenient to implement:</p><ul><li>Gaming leaderboards</li><li>Popular-content rankings</li><li>Activity scores</li><li>Priority-based rankings</li></ul><p>This is an example of why Redis is more than a basic key-value store. Its built-in data structures can directly support application features.</p><h3>Redis for Queues and Streams</h3><p>Applications often need to process tasks asynchronously. For example, after a user places an order, the application may need to send a confirmation email. The order request should not necessarily wait for the entire email-delivery process to finish.</p><p>A queue or stream can separate the two operations.</p><pre>User Places Order<br>        |<br>        v<br>Order Service<br>        |<br>        v<br>   Redis Queue/Stream<br>        |<br>        v<br> Background Worker<br>        |<br>        v<br> Send Confirmation Email</pre><p>Redis lists can support simple queue patterns, while <strong>Redis Streams</strong> provide richer event-streaming capabilities, including entry IDs and consumer groups.</p><p>Redis can be a useful choice for certain asynchronous workflows, but it is not interchangeable with every dedicated message broker. Requirements such as retention, delivery guarantees, replay, throughput, and operational scale should influence the decision.</p><h3>Redis Persistence</h3><p>If Redis stores active data in memory, what happens when the server restarts? Redis provides persistence mechanisms that can save data to disk.</p><p>Two important options are <strong>RDB</strong> and <strong>AOF</strong>.</p><h4>RDB: Snapshotting</h4><p>RDB creates point-in-time snapshots of the dataset.</p><pre>Redis Dataset<br>      |<br>      v<br> Snapshot<br>      |<br>      v<br> RDB File</pre><p><strong>Advantages:</strong></p><ul><li>Compact snapshots</li><li>Useful for backups</li><li>Can support efficient recovery</li></ul><p><strong>Limitations:</strong></p><ul><li>Changes made after the most recent snapshot may be lost if a failure occurs.</li></ul><h4>AOF: Append Only File</h4><p>AOF records write operations so the dataset can be reconstructed by replaying them during recovery.</p><pre>Write Command<br>      |<br>      v<br> Append to AOF<br>      |<br>      v<br> Recovery by Replay</pre><p><strong>Advantages:</strong></p><ul><li>Can provide stronger recovery characteristics depending on the configured fsync policy.</li><li>Records write operations rather than relying only on periodic snapshots.</li></ul><p><strong>Limitations:</strong></p><ul><li>Files may grow over time.</li><li>Replay and maintenance require resources.</li></ul><p>Redis also supports combinations of persistence strategies.</p><p>The appropriate configuration depends on how much data loss is acceptable and how much overhead the application can tolerate.</p><h3>Redis Replication and High Availability</h3><p>Redis can replicate data between a primary and one or more replicas.</p><p>A simplified architecture looks like:</p><pre>              Primary<br>             /       \<br>            v         v<br>        Replica A  Replica B</pre><p>The primary processes writes, and replicas receive copies of its data.</p><p>Replication can support:</p><ul><li>Read scaling in suitable deployments</li><li>Redundancy</li><li>Failover strategies</li></ul><p>However, replication does not automatically guarantee that every replica has the latest write at every moment.</p><p>Redis replication is generally asynchronous, so a replica may temporarily lag behind the primary.</p><p>For high availability, Redis deployments may use <strong>Redis Sentinel</strong> or <strong>Redis Cluster</strong>, depending on the architecture and requirements.</p><p>Sentinel monitors primary-replica deployments and can coordinate failover. Redis Cluster distributes keys across multiple nodes and supports sharding with replication.</p><p>These mechanisms serve related but different purposes.</p><h3>Redis Cluster and Horizontal Scaling</h3><p>What happens when the dataset or workload becomes too large for one Redis server? One option is to distribute keys across multiple nodes. This is called <strong>sharding</strong>. Redis Cluster uses hash slots to distribute keys across the cluster.</p><p>A simplified representation:</p><pre>              Redis Cluster<br>                  |<br>        ┌─────────┼─────────┐<br>        v         v         v<br>      Node A    Node B    Node C<br>     Key Range  Key Range  Key Range</pre><p>Different keys are assigned to different hash slots, which are served by cluster nodes. This allows data and requests to be distributed across multiple machines. Redis Cluster can also use replicas to help with availability.</p><p>However, multi-key operations can have restrictions depending on which nodes hold the relevant keys. Applications may need to design key names and hash tags to keep related keys together when required.</p><p>So horizontal scaling introduces design considerations, just as it does in other distributed databases.</p><h3>Redis and the CAP Theorem</h3><p>Redis is sometimes discussed in the context of distributed-system trade-offs, but it is important to consider the actual deployment. A single Redis instance does not present the same distributed replication choices as a multi-node cluster.</p><p>In a replicated or clustered deployment, network failures, replication lag, failover, and consistency requirements become relevant.</p><p>For example, if a primary fails before a recent write has reached a replica, a failover may not preserve that latest write in every configuration.</p><p>Therefore, it would be misleading to label all Redis deployments simply as CP or AP.</p><p>The right analysis depends on the deployment architecture and the guarantees required by the application.</p><p>This connects Redis to our earlier discussions of <strong>CAP and PACELC</strong>: distributed data systems must account for failures, consistency, and latency, but the precise trade-offs vary by implementation.</p><h3>Redis vs Memcached</h3><p>Memcached is another technology commonly used for caching. Both Redis and Memcached can reduce the load on a main database, but they offer different capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Gj9JUysGq8MZyTDCsR4G6Q.png" /></figure><p>Redis is attractive when the application needs richer data structures or persistence options.</p><p>Memcached can be a good choice for straightforward caching workloads.</p><p>The best option depends on the workload rather than a universal performance ranking.</p><h3>Advantages of Redis</h3><h4>1. Very Fast Access</h4><p>In-memory data access supports low-latency operations.</p><h4>2. Rich Data Structures</h4><p>Applications can use hashes, lists, sets, sorted sets, streams, and more.</p><h4>3. Built-In Expiration</h4><p>TTL makes temporary data easier to manage.</p><h4>4. Useful Atomic Operations</h4><p>Commands such as INCR can safely perform certain concurrent updates.</p><h4>5. Flexible Deployment</h4><p>Redis supports persistence, replication, and clustering options.</p><h4>6. Broad Application Uses</h4><p>It can support caching, sessions, counters, rankings, and selected asynchronous workflows.</p><h3>Limitations of Redis</h3><p>Redis also has limitations.</p><h4>1. Memory Costs</h4><p>Keeping a large active dataset in RAM can be expensive.</p><h4>2. Data Expiration and Eviction</h4><p>Keys can expire, and configured eviction policies may remove keys when memory limits are reached.</p><p>Applications must be designed for these possibilities.</p><h4>3. Cache Invalidation</h4><p>Cached values can become stale when the underlying data changes.</p><h4>4. Persistence Trade-Offs</h4><p>Durability settings influence performance and recovery guarantees.</p><h4>5. Querying Limitations</h4><p>Redis is not a general-purpose replacement for SQL databases when complex relational joins and arbitrary relational queries are required.</p><h4>6. Distributed-System Complexity</h4><p>Replication, failover, sharding, and cluster-aware operations introduce operational and application-design challenges.</p><p>Redis is powerful when used for the workloads it was designed to support.</p><h3>When Should We Use Redis?</h3><p>Redis is a strong candidate when an application needs:</p><ul><li>Frequently accessed data to be returned quickly</li><li>Shared session storage across application servers</li><li>Atomic counters</li><li>Short-lived values</li><li>Leaderboards or rankings</li><li>Fast membership checks</li><li>Selected queue and stream patterns</li><li>Distributed rate limiting</li></ul><p>For example, a personalized news application could use Redis to cache popular articles, store short-lived user state, and maintain counters for trending content.</p><p>The primary database would still retain the durable article records and other information that needs to remain authoritative.</p><h3>When Should We NOT Use Redis?</h3><p>Redis may not be the right primary choice when:</p><ul><li>The application depends heavily on complex SQL joins.</li><li>The entire dataset cannot fit within an acceptable memory budget.</li><li>Arbitrary analytical queries are central to the workload.</li><li>A different database better satisfies durability, query, or transaction requirements.</li><li>A dedicated streaming or messaging platform is more appropriate for the required delivery guarantees and retention.</li></ul><p>The goal is not to store everything in Redis. The goal is to use Redis where its performance and data structures provide a meaningful benefit.</p><h3>How Redis Fits into the Big Data Ecosystem</h3><p>Redis connects several concepts from our series:</p><pre>              Distributed Systems<br>                      |<br>          ┌───────────┴───────────┐<br>          v                       v<br>      NoSQL Models           Replication<br>          |                       |<br>          └───────────┬───────────┘<br>                      v<br>                    Redis<br>                      |<br>          ┌───────────┼───────────┐<br>          v           v           v<br>       Caching     Counters    Real-Time State</pre><p>Redis is not primarily a replacement for HDFS or a batch-processing engine like MapReduce.</p><p>Instead, it often operates closer to the application layer, supporting fast access to data and application state.</p><p>This distinction is important:</p><ul><li><strong>HDFS</strong> focuses on distributed file storage.</li><li><strong>MapReduce</strong> focuses on distributed batch processing.</li><li><strong>HBase</strong> focuses on distributed wide-column data storage.</li><li><strong>Redis</strong> focuses on fast in-memory data operations and related workloads.</li></ul><p>Each technology solves a different problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSQrhSgCecGnHhLeb-d6Xw.png" /><figcaption>Key Takeaways</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f5953940c7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding VoltDB]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-voltdb-30e4ac800853?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/30e4ac800853</guid>
            <category><![CDATA[voltdb]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 12:54:40 GMT</pubDate>
            <atom:updated>2026-10-26T12:54:40.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine an application processing thousands of transactions every second.</p><p>A telecom company is tracking network events. A financial platform is processing transactions. An online service is updating user activity in real time.</p><p>These applications cannot always afford slow database operations. They need to process large volumes of data quickly while maintaining correctness.</p><p>Traditional databases can handle many such workloads, but certain high-throughput applications benefit from a different architecture: one designed around <strong>in-memory data, partitioning, and fast transaction execution</strong>.</p><p>This is where <strong>VoltDB</strong> comes in.</p><p>VoltDB is a distributed relational database designed for high-throughput, low-latency transactional workloads. It is associated with the NewSQL approach because it combines relational data and SQL with a distributed architecture.</p><p>Let’s understand how it works and what makes it different.</p><h3>What Is VoltDB?</h3><p>VoltDB is a relational database designed to process transactions at high speed.</p><p>It combines several important ideas:</p><ul><li>Relational tables and SQL</li><li>In-memory data processing</li><li>Distributed execution</li><li>Partitioned data</li><li>Transactional consistency</li><li>High-throughput workload processing</li></ul><p>Its design is especially suited to applications that perform many small, predictable transactions and need fast responses.</p><p>Unlike a traditional database architecture that may rely heavily on disk access and general-purpose query execution, VoltDB is designed to minimize overhead for supported transaction workloads.</p><h3>Why Was VoltDB Developed?</h3><p>Consider a telecom application processing events from millions of mobile devices.</p><p>Each event might require the system to:</p><ol><li>Identify the device.</li><li>Update its current state.</li><li>Check usage limits.</li><li>Record the event.</li><li>Return a response.</li></ol><p>When these operations happen at a very high rate, database overhead becomes important.</p><p>A database that repeatedly performs expensive disk operations, locks shared resources, or coordinates unnecessary work may struggle to meet strict latency requirements.</p><p>VoltDB approaches this problem through a design focused on fast, predictable transaction execution.</p><p>The key ideas are:</p><ul><li>Keep active data in memory where appropriate.</li><li>Partition data so work can execute in parallel.</li><li>Minimize contention between transactions.</li><li>Execute transactions in a controlled order.</li><li>Distribute processing across multiple partitions and nodes.</li></ul><p>These choices can deliver high performance for workloads that fit the architecture.</p><h3>What Makes VoltDB Different?</h3><p>Let’s compare the general approaches.</p><h4>Traditional disk-oriented database</h4><pre>Application<br>     ↓<br>SQL Query<br>     ↓<br>Database Engine<br>     ↓<br>Data Access + Query Execution<br>     ↓<br>   Result</pre><p>Traditional databases have sophisticated caching and optimization, so they do not necessarily read from disk for every query. However, their architectures often support a broad range of workloads and execution patterns.</p><h4>VoltDB’s approach</h4><pre>Application<br>     ↓<br>Transaction Request<br>     ↓<br>Partitioned Database<br>     ↓<br>In-Memory Execution<br>     ↓<br>Result</pre><p>VoltDB is designed to make transactions fast by keeping data in memory and reducing contention and execution overhead.</p><p>This does not mean it eliminates disk storage or durability concerns. Persistent storage, logging, replication, and recovery still matter.</p><p>The difference lies in how the system organizes and executes transactional work.</p><h3>In-Memory Database: What Does It Mean?</h3><p>An <strong>in-memory database</strong> keeps its active working data in RAM rather than relying primarily on disk for routine data access.</p><p>RAM is much faster to access than persistent storage such as SSDs or hard drives.</p><p>A simplified comparison:</p><pre>          Application<br>               |<br>               ↓<br>        Database Engine<br>               |<br>        ┌──────┴──────┐<br>        ↓             ↓<br>      RAM           Persistent<br>   Fast Access      Storage<br>                    Durability</pre><p>RAM provides fast access, while persistent storage helps preserve data across restarts and failures.</p><h4>Advantages</h4><ul><li>Fast data access</li><li>Low latency for suitable workloads</li><li>Reduced dependence on routine disk reads</li><li>Useful for high-frequency transactions</li></ul><h4>Limitations</h4><ul><li>RAM is more expensive per unit of capacity than many storage options.</li><li>Memory capacity is finite.</li><li>Durability and recovery still require careful design.</li><li>Workloads that exceed memory capacity may not fit the intended architecture well.</li></ul><p><strong>Important:</strong> In-memory does not mean data is never persisted to disk. Durability mechanisms remain essential.</p><h3>VoltDB and Partitioning</h3><p>One of VoltDB’s key design concepts is <strong>partitioning</strong>. Partitioning divides data into smaller sections so different parts of the system can process them independently.</p><h4>Why is this useful?</h4><p>Without partitioning, multiple transactions may compete for shared resources. With partitioning, transactions that operate independently on separate partitions can avoid much of that contention. The result can be better throughput and lower latency for suitable workloads.</p><h3>Single-Threaded Execution Per Partition</h3><p>A distinctive feature of VoltDB’s execution model is that transactions within a partition are executed serially by a single execution thread. This is an architectural choice designed to reduce concurrency-control overhead within that partition.</p><p>Let’s simplify the idea.</p><p>Imagine several transactions targeting the same partition:</p><pre>Transaction A ──┐<br>Transaction B ──┼──→ Partition 1<br>Transaction C ──┘</pre><p>The partition processes them in a defined sequence:</p><pre>Transaction A<br>      ↓<br>Transaction B<br>      ↓<br>Transaction C</pre><p>This reduces the need for multiple threads to compete over the same partition’s data using conventional locking. However, <strong>single-threaded per partition does not mean the entire database is single-threaded</strong>.</p><p>Different partitions can execute work in parallel:</p><pre>Partition 1 → Transaction A → Transaction B<br>Partition 2 → Transaction C → Transaction D<br>Partition 3 → Transaction E → Transaction F</pre><p>This is how VoltDB can combine controlled execution within partitions with parallelism across partitions.</p><h3>How Does VoltDB Execute a Transaction?</h3><p>Consider a transaction that updates a user’s account. A simplified execution flow looks like this:</p><pre>Client<br>  ↓<br>Submit Transaction<br>  ↓<br>Identify Target Partition<br>  ↓<br>Execute Transaction<br>  ↓<br>Apply Data Changes<br>  ↓<br>Record Required Durability Information<br>  ↓<br>Return Result</pre><p>The actual implementation includes additional mechanisms for transaction coordination, durability, replication, and recovery.</p><p>The important idea is that VoltDB aims to execute transactions efficiently by routing work to the relevant partition and reducing unnecessary contention.</p><h3>Single-Partition vs Multi-Partition Transactions</h3><p>This distinction is important for understanding VoltDB’s performance.</p><h3>Single-partition transaction</h3><p>A transaction accesses data belonging to one partition.</p><pre>Transaction<br>     |<br>     ↓<br>Partition A<br>     |<br>     ↓<br>Execute</pre><p>This is generally the simpler and faster case because the operation can be executed locally within the responsible partition.</p><h3>Multi-partition transaction</h3><p>A transaction accesses data across multiple partitions.</p><pre>             Transaction<br>                  |<br>           ┌──────┴──────┐<br>           ↓             ↓<br>      Partition A   Partition B<br>           \             /<br>            \           /<br>             Coordination</pre><p>The system may need to coordinate execution across partitions. That coordination introduces additional overhead and can increase latency. Therefore, a good VoltDB data model often tries to keep common transaction paths within a single partition when possible.</p><p>This is an important database-design consideration, not merely an implementation detail.</p><h3>Stored Procedures</h3><p>VoltDB supports transactions implemented through stored procedures. A stored procedure packages database operations into a defined unit of work.</p><p>For example, an application might need to:</p><ol><li>Check a customer’s balance.</li><li>Verify that sufficient funds are available.</li><li>Deduct the amount.</li><li>Record the transaction.</li></ol><p>Instead of sending multiple independent requests, the application can invoke a procedure that performs the required operations as a transaction.</p><p>Conceptually:</p><pre>Application<br>     ↓<br>Call Stored Procedure<br>     ↓<br>Validate Request<br>     ↓<br>Read and Update Data<br>     ↓<br>Commit Transaction<br>     ↓<br>Return Result</pre><p>This can reduce round trips between the application and database and helps VoltDB execute predictable transaction logic efficiently.</p><h3>SQL Support</h3><p>VoltDB is a relational database, so SQL is central to its data model.</p><p>For example, a table might be defined as:</p><pre>CREATE TABLE accounts (<br>    account_id BIGINT NOT NULL,<br>    balance DECIMAL NOT NULL,<br>    PRIMARY KEY (account_id)<br>);</pre><p>A query could retrieve an account:</p><pre>SELECT account_id, balance<br>FROM accounts<br>WHERE account_id = 101;</pre><p>And an update might look like:</p><pre>UPDATE accounts<br>SET balance = balance - 100<br>WHERE account_id = 101;</pre><p>These examples illustrate the familiar relational interface.</p><p>However, VoltDB is not a drop-in replacement for every traditional SQL database. Supported SQL features, query patterns, and operational behavior can differ. Applications need to be designed around the database’s supported workload and transaction model.</p><h3>VoltDB and ACID Transactions</h3><p>VoltDB is designed to support transactional correctness.</p><p>Let’s revisit ACID.</p><ul><li><strong>Atomicity:</strong> A transaction’s changes are treated as one logical unit.</li><li><strong>Consistency:</strong> Transactions preserve the database’s defined integrity rules.</li><li><strong>Isolation:</strong> Concurrent operations follow the database’s transaction and isolation guarantees.</li><li><strong>Durability:</strong> Committed changes are protected according to the configured durability mechanisms.</li></ul><p>These properties matter even when the database is designed for speed. For example, an account transfer should not simply subtract money from one account and fail to add it to the other. The database needs a reliable transaction mechanism to maintain the intended result. High performance is useful only when the system also preserves the required correctness.</p><h3>Durability and Recovery</h3><p>If active data resides in RAM, what happens when a machine loses power?</p><p>This is a critical question for any in-memory database. A database must use appropriate persistence and recovery mechanisms so committed data can be recovered after failures. Depending on the system’s configuration and deployment, durability mechanisms can involve:</p><ul><li>Transaction logging</li><li>Snapshots</li><li>Replication</li><li>Recovery procedures</li></ul><p>A simplified view:</p><pre>Transaction<br>     ↓<br>Execute in Memory<br>     ↓<br>Durability Mechanisms<br>     ↓<br>Acknowledge According to<br>Configured Guarantees</pre><p>The exact sequence depends on the implementation and configuration. It is important not to assume that every in-memory database acknowledges writes using the same persistence sequence.</p><h3>VoltDB and Distributed Systems</h3><p>VoltDB fits naturally into our distributed-systems discussion. A distributed database needs to manage:</p><ul><li>Partitioning</li><li>Parallel execution</li><li>Replication</li><li>Failure handling</li><li>Transaction coordination</li><li>Data consistency</li></ul><p>VoltDB combines partitioned execution with mechanisms designed to support transactional workloads across a distributed deployment.</p><p>However, adding more nodes does not automatically improve performance for every workload.</p><p>The result depends on factors such as:</p><ul><li>How well data is partitioned</li><li>How many transactions cross partitions</li><li>Whether the workload creates hotspots</li><li>How much coordination is required</li><li>The deployment’s durability and replication settings</li></ul><p>A workload with many independent, well-partitioned transactions may scale differently from one where nearly every transaction touches multiple partitions.</p><h3>Advantages of VoltDB</h3><h4>1. Low-Latency Transaction Processing</h4><p>Its architecture is designed to minimize overhead for supported transactional workloads.</p><h4>2. High Throughput</h4><p>Independent transactions can execute in parallel across partitions.</p><h4>3. Relational Data and SQL</h4><p>Applications can use a relational model rather than adopting a key-value or document model.</p><h4>4. Reduced Locking Overhead Within Partitions</h4><p>Serial execution within each partition avoids many forms of intra-partition lock contention.</p><h4>5. Transactional Processing</h4><p>It supports transactional workloads where correctness matters.</p><h4>6. Distributed Architecture</h4><p>Data and processing can be distributed across partitions and nodes.</p><h3>Limitations of VoltDB</h3><p>VoltDB is not the ideal choice for every database workload.</p><h4>1. Workload Design Matters</h4><p>Transactions should be designed to work efficiently with the partitioning model.</p><h4>2. Multi-Partition Coordination</h4><p>Transactions spanning partitions may require additional coordination.</p><h4>3. Memory Requirements</h4><p>An in-memory-oriented architecture can make RAM capacity and cost important considerations.</p><h4>4. SQL Compatibility Differences</h4><p>Applications may need changes when migrating from another relational database.</p><h4>5. Not a General-Purpose Replacement for Every Database</h4><p>Workloads involving complex analytical queries, broad compatibility requirements, or different access patterns may be better served by another database architecture.</p><h4>6. Operational Design Still Matters</h4><p>Durability, replication, backups, recovery, and failure handling must be configured and tested appropriately.</p><p>The right choice depends on the application’s performance requirements and data-access patterns.</p><h3>The Big Idea: Why Partitioning Matters So Much</h3><p>If there is one architectural lesson to remember from VoltDB, it is this: <strong>Performance depends not only on how much hardware we have, but also on how the workload is divided.</strong></p><p>Consider two scenarios.</p><h4>Scenario A: Independent transactions</h4><pre>Transaction A → Partition 1<br>Transaction B → Partition 2<br>Transaction C → Partition 3</pre><p>These transactions can potentially execute in parallel.</p><h4>Scenario B: Transactions crossing partitions</h4><pre>Transaction A<br>      |<br>      ├── Partition 1<br>      └── Partition 2<br>             |<br>       Coordination</pre><p>The second scenario introduces additional coordination. This is why partitioning keys, data locality, and transaction design are important when working with distributed databases. More machines help only when the architecture allows the work to use them effectively.</p><h3>How VoltDB Fits into the Big Data Ecosystem</h3><p>VoltDB connects several topics we’ve already covered:</p><pre>               Distributed Systems<br>                        ↓<br>                 Data Partitioning<br>                        ↓<br>                   Replication<br>                        ↓<br>                     NewSQL<br>                        ↓<br>                     VoltDB<br>                        ↓<br>           High-Throughput Transactions</pre><p>It also illustrates an important distinction within Big Data:</p><ul><li>Some systems focus on storing and processing enormous datasets in batches.</li><li>Some focus on distributed event streams.</li><li>Some focus on serving huge volumes of transactional requests with low latency.</li></ul><p>VoltDB belongs primarily to the last category. Big Data infrastructure is not just about storing more data. It is also about choosing the right architecture for how that data must be accessed and updated.</p><h3>Key Takeaways</h3><ul><li><strong>VoltDB</strong> is a relational database designed for high-throughput, low-latency transactional workloads.</li><li>It is associated with the <strong>NewSQL</strong> approach.</li><li>It combines SQL and relational data with a distributed architecture.</li><li>Its design emphasizes <strong>in-memory execution and partitioned transaction processing</strong>.</li><li>Transactions within a partition are executed serially, while independent partitions can execute work in parallel.</li><li>Single-partition transactions are generally simpler than multi-partition transactions.</li><li>Stored procedures can package transactional logic and reduce application-to-database round trips.</li><li>In-memory execution does not eliminate the need for durability, replication, or recovery.</li><li>VoltDB is most useful when the workload fits its execution and partitioning model.</li><li>It is not automatically a replacement for every relational, NoSQL, or analytical database.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30e4ac800853" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding NewSQL: Bringing SQL to Distributed Systems]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-newsql-bringing-sql-to-distributed-systems-27f2ef59ffa7?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/27f2ef59ffa7</guid>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 07:12:06 GMT</pubDate>
            <atom:updated>2026-09-16T07:12:06.487Z</atom:updated>
            <content:encoded><![CDATA[<p>We have now seen why traditional relational databases can struggle when data and traffic become extremely large.</p><p>We have also seen how <strong>NoSQL databases</strong> emerged to solve some of these problems by offering:</p><ul><li>Horizontal scalability</li><li>Flexible data models</li><li>Distributed architectures</li><li>High availability</li><li>Large-scale data handling</li></ul><p>But NoSQL comes with a trade-off.</p><p>Many applications still want the things that relational databases are really good at:</p><ul><li>SQL</li><li>Structured data</li><li>Transactions</li><li>Strong consistency</li><li>Relationships between data</li><li>ACID guarantees</li></ul><p>So an obvious question arises: <strong><em>Can we get the scalability of distributed systems without giving up the relational model and SQL?</em></strong></p><p>This is the idea behind <strong>NewSQL</strong>.</p><h3>What Is NewSQL?</h3><p><strong>NewSQL</strong> refers to a class of modern relational database systems designed to provide the scalability and distributed architecture of modern systems while retaining the SQL interface and transactional guarantees of traditional relational databases.</p><p><strong><em>NewSQL = SQL + Distributed Architecture + Scalability</em></strong></p><p>Traditional relational databases were primarily designed around centralized or scale-up architectures. NoSQL databases introduced new models and architectures for large-scale distributed workloads.</p><p>NewSQL tries to combine the strengths of both worlds.</p><pre>Traditional SQL<br>      +<br>Distributed Systems<br>      ↓<br>    NewSQL</pre><h3>Why Did NewSQL Emerge?</h3><p>Let’s look at the problem more clearly.</p><p>Traditional relational databases are extremely powerful.</p><p>They provide:</p><ul><li>SQL</li><li>ACID transactions</li><li>Strong consistency</li><li>Structured schemas</li><li>Joins</li><li>Constraints</li></ul><p>But when workloads become enormous, scaling them can become difficult. One traditional approach is <strong>vertical scaling</strong>:</p><pre>Small Database<br>      ↓<br>Bigger Database<br>      ↓<br>Even Bigger Database</pre><p>Eventually, there are physical and economic limits. Another approach is to distribute the database manually.</p><p>But now the application may have to deal with:</p><ul><li>Sharding</li><li>Replication</li><li>Distributed transactions</li><li>Data synchronization</li><li>Failure handling</li></ul><p>This increases complexity. NewSQL databases aim to provide these distributed capabilities <strong>inside the database system itself</strong>.</p><h3>Traditional SQL vs NoSQL vs NewSQL</h3><p>This is the easiest way to understand NewSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*cFSG913n1NcuAuKm7ZE26w.png" /></figure><p>The important point is that NewSQL isn’t simply “new SQL syntax.” It is primarily about <strong>how a relational database is designed and scaled</strong>.</p><h3>The Core Idea Behind NewSQL</h3><p>A NewSQL database tries to provide the familiar relational experience:</p><pre> Application<br>      ↓<br>     SQL<br>      ↓<br>Relational Database</pre><p>while internally using distributed infrastructure:</p><pre>                    SQL<br>                     ↓<br>              NewSQL Database<br>                     ↓<br>          Distributed Architecture<br>          /          |          \<br>         ↓           ↓           ↓<br>      Node A       Node B      Node C</pre><p>The application can continue using SQL without having to manually manage every distributed-system detail.</p><h3>What Makes NewSQL Different?</h3><p>The key difference is <strong>where the complexity lives</strong>.</p><p>With a traditional relational database:</p><pre>Application<br>     ↓<br>SQL Database</pre><p>Scaling the system horizontally can require additional architecture around the database.</p><p>With NewSQL:</p><pre>Application<br>     ↓<br>SQL Interface<br>     ↓<br>Distributed SQL Database<br>     ↓<br>Multiple Nodes</pre><p>The database itself is designed to handle:</p><ul><li>Distribution</li><li>Replication</li><li>Partitioning</li><li>Fault tolerance</li><li>Distributed transactions</li><li>Coordination</li></ul><p>This is one of the main ideas behind NewSQL.</p><h3>Distributed SQL</h3><p>You may also hear the term <strong>Distributed SQL</strong>.</p><p>Distributed SQL databases are relational databases that distribute data and computation across multiple machines while maintaining SQL semantics and transactional guarantees.</p><p>A simplified architecture looks like:</p><pre>                 Application<br>                      |<br>                      ↓<br>                     SQL<br>                      |<br>          ┌───────────┼───────────┐<br>          ↓           ↓           ↓<br>       Node A       Node B       Node C<br>          |           |           |<br>       Data A      Data B      Data C</pre><p>The database handles the complexity of distributing the data. The developer can still interact with it using SQL.</p><h3>Horizontal Scaling in NewSQL</h3><p>One of the biggest goals of NewSQL is <strong>horizontal scalability</strong>. Instead of continuously upgrading one machine:</p><pre>Database<br>   ↓<br>Bigger Database<br>   ↓<br>Even Bigger Database</pre><p>we can add more nodes:</p><pre>               Database<br>                  |<br>       ┌──────────┼──────────┐<br>       ↓          ↓          ↓<br>     Node A     Node B     Node C</pre><p>If the workload grows further:</p><pre>─────┬───────┬───────┬───────┬───────┐<br>     ↓       ↓       ↓       ↓       ↓<br>   Node A  Node B  Node C  Node D  Node E</pre><p>The system can distribute data and workload across these nodes.</p><p>This makes NewSQL particularly useful for applications that need to scale significantly.</p><h3>Data Partitioning</h3><p>A distributed database cannot simply put all the data on every machine. Instead, data is often <strong>partitioned</strong>.</p><p>For example, suppose we have:</p><pre>Customer IDs: 1 – 1,000,000</pre><p>The database might distribute the data across nodes:</p><pre>Node A → IDs 1 – 250,000<br>Node B → IDs 250,001 – 500,000<br>Node C → IDs 500,001 – 750,000<br>Node D → IDs 750,001 – 1,000,000</pre><p>These partitions allow the system to distribute storage and workload.</p><p>The important difference is that the database manages this distribution internally.</p><h3>Replication</h3><p>Partitioning helps distribute data. But what happens if a node fails? This is where <strong>replication</strong> becomes important.</p><p>A partition can have multiple replicas:</p><pre>              Partition A<br>              /    |    \<br>             ↓     ↓     ↓<br>        Node A   Node B  Node C<br>       Replica   Replica  Replica</pre><p>If one node fails:</p><pre>Node A ✗</pre><pre>Node B ✓<br>Node C ✓</pre><p>the system can potentially continue operating using another replica.</p><p>Replication improves:</p><ul><li>Fault tolerance</li><li>Availability</li><li>Data durability</li></ul><p>But it also introduces coordination between replicas. And that brings us back to our earlier discussions about: <strong>Consistency and latency.</strong></p><h3>NewSQL and ACID Transactions</h3><p>One of NewSQL’s biggest selling points is that it retains strong transactional support. Remember ACID?</p><h4>Atomicity</h4><p>A transaction happens completely or not at all.</p><h4>Consistency</h4><p>A transaction moves the database from one valid state to another valid state.</p><h4>Isolation</h4><p>Concurrent transactions should not interfere with each other incorrectly.</p><h4>Durability</h4><p>Once a transaction is committed, its changes should survive failures.</p><p>NewSQL systems aim to provide these guarantees even though the database itself is distributed across multiple machines.</p><h3>Why Distributed Transactions Are Difficult</h3><p>Imagine a transaction that needs to modify data stored on two different nodes:</p><pre>Transaction<br>     |<br>     ├────→ Node A<br>     |<br>     └────→ Node B</pre><p>Suppose Node A successfully commits:</p><pre>Node A ✓</pre><p>but Node B fails:</p><pre>Node B ✗</pre><p>Now we have a problem.</p><p>We don’t want half the transaction to succeed while the other half fails. A distributed database therefore needs mechanisms to coordinate such operations.</p><p>This can involve:</p><ul><li>Consensus</li><li>Distributed transaction protocols</li><li>Replication</li><li>Coordination between nodes</li></ul><p>NewSQL systems are designed to handle these challenges as part of the database architecture.</p><h3>SQL Still Matters</h3><p>One major advantage of NewSQL is that developers don’t have to abandon SQL. For example, a developer can still write:</p><pre>SELECT *<br>FROM Customers<br>WHERE country = &#39;India&#39;;</pre><p>or:</p><pre>UPDATE Accounts<br>SET balance = balance - 500<br>WHERE account_id = 101;</pre><p>The database handles the distributed execution internally.</p><p>This is important because SQL is already widely understood and supported by:</p><ul><li>Developers</li><li>Data analysts</li><li>Applications</li><li>BI tools</li><li>Database tools</li></ul><p>So NewSQL can provide a familiar interface while changing the architecture underneath.</p><h3>What Happens Behind a SQL Query?</h3><p>Consider:</p><pre>SELECT *<br>FROM Orders<br>WHERE customer_id = 101;</pre><p>In a traditional database, the query might execute mostly within one database server. In a distributed NewSQL database, the data may be distributed across multiple nodes.</p><p>A simplified flow could be:</p><pre>             Client<br>               ↓<br>           SQL Query<br>               ↓<br>           Query Layer<br>               ↓<br>      Find relevant partitions<br>               ↓<br>        Send work to nodes<br>               ↓<br>      Node A   Node B   Node C<br>        ↓        ↓        ↓<br>      Results from partitions<br>                 ↓<br>         Combine Results<br>                 ↓<br>         Return to Client</pre><p>The database hides much of this complexity from the application.</p><h3>NewSQL and Joins</h3><p>One advantage of the relational model is the ability to work with relationships between tables.</p><p>For example:</p><pre>SELECT Customers.name, Orders.amount<br>FROM Customers<br>JOIN Orders<br>ON Customers.id = Orders.customer_id;</pre><p>In a distributed environment, however, joins can become more expensive if the relevant data is stored on different machines. NewSQL systems therefore need sophisticated query execution and data-distribution strategies. This is one reason distributed SQL is technically challenging.</p><p>The goal is to preserve familiar relational operations while making them work efficiently across multiple nodes.</p><h3>NewSQL and the CAP Theorem</h3><p>NewSQL systems are still distributed systems. Therefore, CAP-related trade-offs still apply. If a network partition occurs, the system has to deal with the fundamental trade-off between: <strong>Consistency and Availability.</strong></p><p>For example, a system may choose to protect consistency even if some requests have to wait or fail temporarily. And during normal operation, PACELC reminds us that stronger consistency can involve additional coordination and therefore potentially higher latency.</p><p>So:</p><pre>Distributed NewSQL<br>       ↓<br>CAP Trade-offs<br>       ↓<br>PACELC Trade-offs</pre><p>NewSQL does not “escape” CAP.</p><p>It simply makes different design choices while preserving the relational/SQL experience.</p><h3>NewSQL vs NoSQL</h3><p>This is one of the most important comparisons.</p><h4>NoSQL</h4><p>NoSQL systems were designed around the idea that traditional relational databases were not always the best fit for massive distributed workloads.</p><p>They often prioritize:</p><ul><li>Horizontal scalability</li><li>Flexible data models</li><li>High availability</li><li>Distributed operation</li></ul><p>Different NoSQL databases use different models:</p><ul><li>Key-value</li><li>Document</li><li>Column-family</li><li>Graph</li></ul><h4>NewSQL</h4><p>NewSQL keeps:</p><ul><li>Relational data</li><li>SQL</li><li>Transactions</li><li>Structured schemas</li></ul><p>while introducing:</p><ul><li>Distributed architecture</li><li>Horizontal scalability</li><li>Automatic partitioning</li><li>Replication</li><li>Distributed execution</li></ul><p>So:</p><pre>NoSQL = Rethink the data model</pre><pre>NewSQL = Keep the relational model,<br>  rethink the architecture</pre><p>This is a useful way to remember the difference.</p><h3>NewSQL vs Traditional SQL</h3><p>NewSQL is not meant to replace every traditional relational database.</p><p>Traditional databases are still excellent for many workloads.</p><p>For example, a small or medium-sized application might work perfectly well with a conventional relational database running on one or a few servers.</p><p>NewSQL becomes more attractive when the system needs:</p><ul><li>Very large scale</li><li>Horizontal scaling</li><li>High availability</li><li>Distributed storage</li><li>Distributed transactions</li><li>SQL compatibility</li></ul><p>The architecture should always match the workload.</p><h3>Examples of NewSQL Databases</h3><p>Some well-known systems associated with the NewSQL/distributed-SQL space include:</p><h4>Google Spanner</h4><p>A globally distributed relational database designed for strong consistency and large-scale workloads.</p><h4>CockroachDB</h4><p>A distributed SQL database designed around horizontal scaling, resilience, and SQL compatibility.</p><h4>TiDB</h4><p>An open-source distributed SQL database designed to provide SQL compatibility with horizontal scalability.</p><h4>VoltDB</h4><p>A distributed in-memory relational database designed for high-throughput, low-latency transactional workloads.</p><p>VoltDB is particularly relevant to our Big Data sequence because we’ll look at it in more detail later.</p><p>These systems differ significantly in architecture and guarantees, so “NewSQL” should be understood as a broad category rather than a single database technology.</p><h3>NewSQL Architecture: High-Level View</h3><p>A simplified NewSQL architecture can be visualized as:</p><pre>                     Application<br>                         |<br>                         ↓<br>                     SQL Layer<br>                         |<br>                 Query Processing<br>                         |<br>             ┌───────────┼───────────┐<br>             ↓           ↓           ↓<br>          Node A       Node B       Node C<br>             |           |           |<br>          Partition    Partition    Partition<br>             |           |           |<br>          Replicas     Replicas     Replicas</pre><p>Different systems implement these components differently. But the general idea remains: <strong>SQL interface on top + distributed infrastructure underneath.</strong></p><h3>Advantages of NewSQL</h3><h4>1. SQL Support</h4><p>Developers can continue using a familiar query language.</p><h4>2. Horizontal Scalability</h4><p>The system can distribute workload across multiple machines.</p><h4>3. ACID Transactions</h4><p>NewSQL systems aim to preserve strong transactional guarantees in distributed environments.</p><h4>4. High Availability</h4><p>Replication allows the system to continue operating despite some failures.</p><h4>5. Automatic Distribution</h4><p>The database can handle partitioning and replication instead of forcing developers to build everything manually.</p><h4>6. Familiar Relational Model</h4><p>Tables, rows, columns, relationships, and joins remain available.</p><h3>Limitations of NewSQL</h3><p>NewSQL isn’t perfect either.</p><h4>1. Distributed Complexity</h4><p>The underlying architecture is still complex.</p><h4>2. Network Overhead</h4><p>Nodes have to communicate over a network.</p><h4>3. Coordination Costs</h4><p>Strong consistency and distributed transactions may require additional coordination.</p><h4>4. Operational Complexity</h4><p>Running a distributed database can require more infrastructure knowledge.</p><h4>5. Not Always Necessary</h4><p>A small application may not need a distributed database at all.</p><h4>6. Distributed Joins Can Be Expensive</h4><p>When related data is spread across different nodes, queries may require network communication.</p><p>So NewSQL solves many problems, but it also introduces new engineering challenges.</p><h3>When Should We NOT Use NewSQL?</h3><p>NewSQL is not automatically the best database choice.</p><p>You may not need it if:</p><ul><li>The dataset is relatively small.</li><li>Traffic is low.</li><li>One relational database handles the workload comfortably.</li><li>Distributed transactions aren’t required.</li><li>The application does not need horizontal database scaling.</li></ul><p>Adding a distributed database too early can introduce unnecessary complexity. A simple relational database is often the better engineering decision when it is sufficient.</p><h3>SQL + NoSQL + NewSQL: The Bigger Picture</h3><p>We can now see the evolution more clearly.</p><h4>Traditional SQL</h4><p>Focused on: <strong>Structured data + relationships + transactions</strong></p><h4>NoSQL</h4><p>Focused on: <strong>Large-scale distributed workloads + flexibility + scalability</strong></p><h4>NewSQL</h4><p>Attempts to combine: <strong>Relational model + SQL + transactions + distributed scalability</strong></p><p>A simplified evolution looks like:</p><pre>Traditional SQL<br>       |<br>       | Need more distributed scalability<br>       ↓<br>     NoSQL<br>       |<br>       | But relational workloads still need<br>       | SQL + transactions<br>       ↓<br>    NewSQL</pre><p>This doesn’t mean NewSQL came after NoSQL in a strict chronological sense or that it replaces NoSQL. These are different approaches designed for different requirements.</p><h3>NewSQL and Big Data</h3><p>Why does NewSQL matter in a Big Data course? Because Big Data isn’t only about storing huge files.</p><p>Modern data systems also need to support:</p><ul><li>Massive transaction volumes</li><li>Distributed applications</li><li>Real-time workloads</li><li>Large numbers of users</li><li>High availability</li><li>Global data access</li></ul><p>NewSQL demonstrates how traditional database ideas can evolve for distributed environments. It connects several concepts we’ve already studied:</p><pre>Relational Databases<br>        +<br>       SQL<br>        +<br>      ACID<br>        +<br>Distributed Systems<br>        +<br>   Replication<br>        +<br>  Partitioning<br>        ↓<br>      NewSQL</pre><h3>NewSQL vs NoSQL: A Practical Example</h3><p>Imagine an online store.</p><p>It has:</p><ul><li>Customers</li><li>Products</li><li>Orders</li><li>Payments</li><li>Inventory</li></ul><p>The relationships between these entities are important.</p><p>For example:</p><pre> Customer<br>    ↓<br>  Order<br>    ↓<br> Product<br>    ↓<br> Inventory</pre><p>A relational model and transactions can be extremely useful here.</p><p>If the system also needs to scale across many machines, NewSQL becomes an interesting option.</p><p>On the other hand, if the workload mainly involves huge volumes of flexible event data or simple key-value lookups, a NoSQL system may be more appropriate.</p><p>The database should therefore be selected based on the workload rather than simply choosing the “newest” technology.</p><h3>The Big Idea</h3><p>NewSQL can be summarized in one sentence:</p><blockquote><strong><em>NewSQL tries to give applications the familiar relational and transactional capabilities of SQL databases while providing the horizontal scalability and fault tolerance expected from distributed systems.</em></strong></blockquote><p>It is essentially an attempt to answer: <strong>“Can we keep SQL while scaling like a distributed system?”</strong></p><p>The answer is: <strong>Yes, but the underlying architecture becomes significantly more complex.</strong></p><h3>Key Takeaways</h3><ul><li><strong>NewSQL</strong> is a class of modern relational databases designed for distributed environments.</li><li>It combines <strong>SQL and relational data models</strong> with <strong>horizontal scalability</strong>.</li><li>NewSQL systems aim to retain <strong>ACID transactions</strong> while distributing data across multiple machines.</li><li>Data can be <strong>partitioned and replicated</strong> across nodes.</li><li>The database manages much of the distributed complexity internally.</li><li>NewSQL differs from NoSQL because it keeps the <strong>relational model and SQL interface</strong>.</li><li>Distributed transactions, joins, and strong consistency can introduce additional coordination and latency.</li><li>Examples include <strong>Google Spanner, CockroachDB, TiDB, and VoltDB</strong>.</li><li>NewSQL is useful when applications need <strong>SQL + transactions + large-scale distributed operation</strong>.</li><li>It is not necessary for every application; traditional relational databases remain excellent for many workloads.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27f2ef59ffa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Distributed Systems: How Multiple Machines Work as One]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-distributed-systems-how-multiple-machines-work-as-one-a187a6188cfa?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/a187a6188cfa</guid>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 08:19:31 GMT</pubDate>
            <atom:updated>2026-09-12T08:19:31.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a system that needs to handle millions of users, enormous amounts of data, and thousands of requests every second.</p><p>Can one computer handle everything? Sometimes. But as systems grow, a single machine eventually becomes a bottleneck.</p><p>It may not have enough:</p><ul><li>CPU</li><li>Memory</li><li>Storage</li><li>Network capacity</li><li>Processing power</li></ul><p>And even more importantly, if that one machine fails, the entire system may go down.</p><p>So instead of relying on one powerful machine, we can use <strong>multiple machines that work together as a single system</strong>. This is the fundamental idea behind <strong>Distributed Systems</strong>.</p><h3>What Is a Distributed System?</h3><p>A <strong>distributed system</strong> is a collection of independent computers that communicate and coordinate with each other to appear to users as one system.</p><p>In simple terms:</p><blockquote><strong><em>Multiple machines + communication + coordination = Distributed System</em></strong></blockquote><p>For example:</p><pre>             User<br>               |<br>               ↓<br>        Distributed System<br>        /        |        \<br>       ↓         ↓         ↓<br>   Server A   Server B   Server C</pre><p>The user doesn’t necessarily need to know which server is processing their request.</p><p>The machines collectively provide the service.</p><p>Distributed systems are everywhere today:</p><ul><li>Search engines</li><li>Social media</li><li>Cloud platforms</li><li>Banking systems</li><li>E-commerce platforms</li><li>Streaming services</li><li>Big Data platforms</li><li>Distributed databases</li></ul><h3>Why Do We Need Distributed Systems?</h3><p>The main reason is simple:</p><p><strong>A single machine has limits.</strong></p><p>Suppose an application receives:</p><pre>100 requests/second</pre><p>One server may handle it easily.</p><p>But eventually the system may receive:</p><pre>10,000 requests/second</pre><p>or:</p><pre>1,000,000 requests/second</pre><p>At some point, simply making the machine more powerful becomes expensive or impossible. This leads to two fundamental approaches:</p><h4>Vertical Scaling</h4><p>Make one machine more powerful.</p><pre>Small Server<br>     ↓<br>Bigger Server<br>     ↓<br>Even Bigger Server</pre><h4>Horizontal Scaling</h4><p>Add more machines.</p><pre>       Load<br>         ↓<br>   ┌─────┼─────┐<br>   ↓     ↓     ↓<br>Server Server Server<br>  A      B      C</pre><p>Distributed systems are primarily built around <strong>horizontal scaling</strong>.</p><h3>The Basic Architecture</h3><p>A distributed application may look like this:</p><pre>                  Users<br>                    |<br>                    ↓<br>               Load Balancer<br>              /      |      \<br>             ↓       ↓       ↓<br>         Server A Server B Server C<br>             \       |       /<br>              \      |      /<br>                 Database</pre><p>Different machines may perform different responsibilities.</p><p>For example:</p><ul><li>Load balancer distributes requests</li><li>Application servers process business logic</li><li>Database servers store information</li><li>Cache servers provide fast access</li><li>Message brokers handle asynchronous communication</li></ul><p>Together, these components form a distributed system.</p><h3>Nodes</h3><p>A machine participating in a distributed system is commonly called a <strong>node</strong>.</p><p>A node could be:</p><ul><li>a physical server</li><li>a virtual machine</li><li>a cloud instance</li><li>a container</li><li>another computing device</li></ul><p>For example:</p><pre>Distributed System</pre><pre>Node A<br>Node B<br>Node C<br>Node D<br>Node E</pre><p>Each node can perform computation, store data, communicate with other nodes, or do some combination of these.</p><h3>Communication Between Nodes</h3><p>Distributed systems depend heavily on communication. Unlike processes running inside the same machine, distributed nodes communicate through a network.</p><p>For example:</p><pre>Node A<br>   |<br>   | Network Request<br>   ↓<br>Node B</pre><p>This communication introduces problems that don’t exist, or are much easier to handle, on a single machine.</p><p>For example:</p><ul><li>Network delays</li><li>Lost messages</li><li>Duplicate messages</li><li>Connection failures</li><li>Server failures</li><li>Network partitions</li></ul><p>This is one of the main reasons distributed systems are difficult.</p><h3>The Network Is Not Perfect</h3><p>One of the most important assumptions in distributed systems is:</p><blockquote><strong><em>You cannot assume that network communication will always work perfectly.</em></strong></blockquote><p>Suppose:</p><pre>Server A  ←────→  Server B</pre><p>Normally they communicate.</p><p>But suddenly:</p><pre>Server A   X   Server B</pre><p>The servers may both still be running. They simply cannot communicate with each other. This is called a <strong>network partition</strong>. And this is exactly where our earlier discussion of <strong>CAP Theorem</strong> becomes relevant.</p><h3>Distributed Systems and CAP Theorem</h3><p>We previously learned that CAP deals with three properties:</p><ul><li>Consistency</li><li>Availability</li><li>Partition Tolerance</li></ul><p>Distributed systems need to think about these because multiple machines communicate over a network. If communication fails, the system has to decide what to do.</p><p>For example:</p><pre>             Network Partition<br>                    |<br>             ┌──────┴──────┐<br>             ↓             ↓<br>       Keep serving?   Stop/Delay?<br>             |             |<br>       Availability   Consistency</pre><p>PACELC then extends this discussion by asking what happens <strong>even when there is no partition</strong>. So our concepts connect naturally:</p><pre>Distributed Systems<br>        ↓<br>       CAP<br>        ↓<br>      PACELC</pre><h3>Fault Tolerance</h3><p>Another major goal of distributed systems is <strong>fault tolerance</strong>. A fault is a problem affecting part of the system.</p><p>For example:</p><pre>Server A  ✓<br>Server B  ✗<br>Server C  ✓</pre><p>If the entire application depends on Server B, the system may fail. But if the workload can be handled by other nodes:</p><pre>Server A  ✓<br>Server B  ✗<br>Server C  ✓</pre><pre>      ↓</pre><pre>System continues</pre><p>the system is more fault tolerant.This is one of the biggest advantages of distributing work across multiple machines.</p><h3>Replication</h3><p>One common way to improve fault tolerance is <strong>replication</strong>. Replication means maintaining multiple copies of data or services.</p><p>For example:</p><pre>            Data<br>              |<br>       ┌──────┼──────┐<br>       ↓      ↓      ↓<br>   Replica A Replica B Replica C</pre><p>If one replica fails, another may still be available.</p><p>Replication can improve:</p><ul><li>Availability</li><li>Fault tolerance</li><li>Read performance</li></ul><p>But it also introduces a major challenge: <strong>How do we keep the replicas synchronized? </strong>And once again, we return to: <strong>Consistency vs Latency</strong></p><p>This is why replication was so important when we discussed PACELC.</p><h3>Data Partitioning</h3><p>Replication creates multiple copies. But sometimes we don’t want every machine to store all the data. Instead, we can divide the data among machines. This is called <strong>partitioning</strong> or <strong>sharding</strong>.</p><p>For example:</p><pre>All Data<br>   |<br>   ├── Data A → Server 1<br>   ├── Data B → Server 2<br>   └── Data C → Server 3</pre><p>Each server stores only a portion of the total dataset. This allows the system to handle datasets that are too large for one machine.</p><h3>Replication vs Partitioning</h3><p>These concepts are often confused.</p><h4>Replication</h4><p><strong>Copy the same data across multiple machines.</strong></p><pre>Data A<br> ↓<br>Server 1<br>Server 2<br>Server 3</pre><p>Purpose:</p><ul><li>Fault tolerance</li><li>Availability</li><li>Read scaling</li></ul><h4>Partitioning</h4><p><strong>Divide different data across different machines.</strong></p><pre>Data A → Server 1<br>Data B → Server 2<br>Data C → Server 3</pre><p>Purpose:</p><ul><li>Scale storage</li><li>Scale processing</li><li>Distribute workload</li></ul><p>Large distributed systems often use <strong>both</strong>.</p><p>For example:</p><pre>          Entire Dataset<br>                |<br>        Partition into shards<br>          /      |      \<br>       Shard A Shard B Shard C<br>          |       |       |<br>       replicas replicas replicas</pre><h3>Load Balancing</h3><p>If we have multiple servers, we need to decide: <strong>Which server should handle each request? </strong>This is the job of a <strong>load balancer</strong>.</p><pre>                 Users<br>                   |<br>                   ↓<br>             Load Balancer<br>             /     |     \<br>            ↓      ↓      ↓<br>        Server A Server B Server C</pre><p>The load balancer distributes incoming requests across available servers.</p><p>A simple strategy is <strong>Round Robin</strong>:</p><pre>Request 1 → Server A<br>Request 2 → Server B<br>Request 3 → Server C<br>Request 4 → Server A<br>Request 5 → Server B</pre><p>Other strategies can consider:</p><ul><li>Current server load</li><li>Number of active connections</li><li>Server response time</li><li>Server health</li><li>Geographic location</li></ul><p>Load balancing prevents one server from becoming overloaded while others remain underutilized.</p><h3>Distributed Coordination</h3><p>Once multiple machines exist, they need to coordinate. For example, imagine two servers both trying to modify the same piece of information.</p><pre>Server A ──→ Data<br>Server B ──→ Data</pre><p>What if both make conflicting changes?</p><p>The system needs rules for:</p><ul><li>Who can perform an operation</li><li>Which update wins</li><li>How nodes discover each other</li><li>How failures are detected</li><li>How leadership is selected</li><li>How replicas synchronize</li></ul><p>This is called <strong>distributed coordination</strong>. Coordination is one of the hardest parts of distributed systems.</p><h3>Leader and Follower</h3><p>A common distributed architecture uses a <strong>leader</strong> and one or more <strong>followers</strong>.</p><pre>             Leader<br>            /      \<br>           ↓        ↓<br>       Follower  Follower</pre><p>The leader may handle writes. Followers replicate the data.</p><p>For example:</p><pre>Client<br>  |<br>  ↓<br>Leader<br>  |<br>  ├────→ Follower A<br>  |<br>  └────→ Follower B</pre><p>This simplifies some coordination problems because there is a designated node responsible for certain operations. However, the system now has to handle: <strong>What happens if the leader fails? </strong>This leads to <strong>leader election</strong>.</p><h3>Leader Election</h3><p>Suppose:</p><pre>Leader A  ✓<br>Follower B<br>Follower C</pre><p>Now Leader A crashes. The system needs another node to become the leader.</p><pre>Leader A  ✗</pre><pre>Follower B → New Leader<br>Follower C → Follower</pre><p>The process of selecting a new leader is called <strong>leader election</strong>. This is an important distributed-systems problem because multiple nodes must agree on who the leader is. Systems use different consensus and coordination mechanisms to solve such problems.</p><h3>Consensus</h3><p>One of the most important concepts in distributed systems is <strong>consensus</strong>. Consensus means that distributed nodes agree on some value or decision despite failures.</p><p>For example:</p><pre>Node A ──┐<br>Node B ──┼──→ Agreement<br>Node C ──┘</pre><p>The nodes might need to agree on:</p><ul><li>Who is the leader</li><li>Whether an operation should be committed</li><li>What the next state of the system should be</li></ul><p>Algorithms such as <strong>Raft</strong> and <strong>Paxos</strong> are designed to solve consensus problems. You don’t need to dive deeply into these algorithms to understand distributed systems at a foundational level.</p><p>The key idea is:</p><blockquote><strong><em>Multiple machines need a reliable way to agree even when some machines or network connections fail.</em></strong></blockquote><h3>Distributed Transactions</h3><p>Now imagine a transaction involving multiple machines.</p><p>For example:</p><pre>Bank Account A → Server 1<br>Bank Account B → Server 2</pre><p>A money transfer might need to update both.</p><p>What happens if:</p><pre>Server 1 → transaction succeeds<br>Server 2 → transaction fails</pre><p>Now the system is left in an inconsistent state. Distributed transactions try to solve such problems. One well-known approach is <strong>Two-Phase Commit (2PC)</strong>.</p><p>At a very high level:</p><h4>Phase 1: Prepare</h4><p>The coordinator asks participating nodes:</p><blockquote><em>“Can you commit this transaction?”</em></blockquote><h4>Phase 2: Commit</h4><p>If everyone agrees:</p><blockquote><em>“Commit.”</em></blockquote><p>Otherwise:</p><blockquote><em>“Abort.”</em></blockquote><p>Conceptually:</p><pre>             Coordinator<br>              /       \<br>             ↓         ↓<br>        Server A    Server B<br>          Prepare     Prepare<br>             ↓         ↓<br>          Ready?      Ready?<br>              \       /<br>               ↓     ↓<br>               Commit</pre><p>Distributed transactions provide stronger guarantees but can introduce additional coordination and latency. Again, distributed systems involve trade-offs.</p><h3>Distributed Systems and Big Data</h3><p>Distributed systems are the foundation of modern Big Data technologies.</p><p>Why? Because Big Data often means: <strong>Too much data + too much processing + too many requests for one machine. </strong>So data and computation are distributed across many machines.</p><p>For example:</p><pre>              Big Data<br>                 |<br>       ┌─────────┴─────────┐<br>       ↓                   ↓<br> Distributed Storage   Distributed Processing<br>       ↓                   ↓<br>      HDFS              MapReduce<br>       ↓<br>      HBase</pre><p>This is why concepts such as:</p><ul><li>HDFS</li><li>MapReduce</li><li>HBase</li><li>NoSQL databases</li><li>Kafka</li><li>distributed databases</li></ul><p>are all connected to distributed-system concepts.</p><h3>Distributed Storage</h3><p>A distributed storage system stores data across multiple machines.</p><p>Instead of:</p><pre>One Machine<br>     |<br>   Data</pre><p>we have:</p><pre>              Dataset<br>                 |<br>       ┌─────────┼─────────┐<br>       ↓         ↓         ↓<br>    Node A     Node B    Node C</pre><p>The system may divide and replicate the data automatically. <strong>HDFS</strong> is a classic example from the Hadoop ecosystem. HDFS divides large files into blocks and distributes those blocks across machines while maintaining replicas for fault tolerance.</p><h3>Distributed Processing</h3><p>Storage alone isn’t enough. We also need to process the data.</p><p>Instead of processing everything on one machine:</p><pre>Huge Dataset<br>     ↓<br>One Computer<br>     ↓<br>Processing</pre><p>a distributed processing framework can divide the work:</p><pre>             Huge Dataset<br>                  |<br>        ┌─────────┼─────────┐<br>        ↓         ↓         ↓<br>      Node A    Node B    Node C<br>      Process   Process   Process<br>        \         |         /<br>         \        |        /<br>             Final Result</pre><p>This is the basic idea behind <strong>MapReduce</strong> and other distributed processing frameworks.</p><h3>Distributed Systems Are Not Just “Many Servers”</h3><p>Having multiple servers does not automatically make a good distributed system.</p><p>The machines need to:</p><ul><li>Communicate</li><li>Coordinate</li><li>Handle failures</li><li>Distribute workload</li><li>Manage data</li><li>Recover from errors</li><li>Maintain the required consistency</li></ul><p>For example:</p><pre>Multiple Servers<br>       ≠<br>Good Distributed System</pre><p>The real challenge is making those independent machines behave like a reliable system.</p><h3>The Fallacies of Distributed Computing</h3><p>One of the famous lessons in distributed systems is that developers often make incorrect assumptions about networks.</p><p>Some common assumptions are:</p><ul><li>The network is reliable.</li><li>Latency is zero.</li><li>Bandwidth is infinite.</li><li>The network is secure.</li><li>The topology never changes.</li><li>There is only one administrator.</li><li>Transport cost is zero.</li></ul><p>In reality: <strong>Networks fail. </strong>Messages can be delayed. Connections can disappear. Servers can crash. Data can arrive late.</p><p>This is why distributed systems require careful failure handling.</p><h3>Common Challenges in Distributed Systems</h3><p>Distributed systems provide enormous scalability, but they also introduce significant complexity.</p><h4>1. Network Failures</h4><p>Nodes may not be able to communicate.</p><h4>2. Partial Failures</h4><p>One component can fail while the rest of the system continues working.</p><h4>3. Data Consistency</h4><p>Multiple replicas may temporarily contain different values.</p><h4>4. Coordination</h4><p>Nodes need to agree on important decisions.</p><h4>5. Synchronization</h4><p>Different nodes may operate at slightly different times.</p><h4>6. Debugging</h4><p>A problem may involve multiple machines and services.</p><h4>7. Latency</h4><p>Network communication takes time.</p><h4>8. Security</h4><p>More machines and communication channels mean more things to protect.</p><p>This is why distributed systems are significantly more complicated than simply running an application on one machine.</p><h3>Advantages of Distributed Systems</h3><p>Despite their complexity, distributed systems offer major benefits.</p><h4>Scalability</h4><p>More machines can be added as workload increases.</p><h4>Fault Tolerance</h4><p>The failure of one node does not necessarily bring down the entire system.</p><h4>High Availability</h4><p>Services can continue operating even when some components fail.</p><h4>Performance</h4><p>Work can be processed in parallel across multiple machines.</p><h4>Large-Scale Storage</h4><p>Massive datasets can be distributed across many machines.</p><h4>Geographic Distribution</h4><p>Systems can place services or data closer to users in different regions.</p><h3>Limitations of Distributed Systems</h3><p>Distributed systems are not a free solution.</p><p>They introduce:</p><ul><li>More infrastructure</li><li>More network communication</li><li>More operational complexity</li><li>Coordination problems</li><li>Consistency challenges</li><li>Difficult debugging</li><li>Higher development and maintenance costs</li></ul><p>Therefore:</p><blockquote><strong><em>You should not distribute a system simply because you can.</em></strong></blockquote><p>Distribution is useful when the scale, availability, fault tolerance, or performance requirements justify the additional complexity.</p><h3>Key Takeaways</h3><ul><li>A <strong>distributed system</strong> consists of multiple independent machines working together.</li><li>Distributed systems are mainly used to achieve <strong>scalability, availability, fault tolerance, and large-scale processing</strong>.</li><li><strong>Horizontal scaling</strong> adds more machines instead of making one machine increasingly powerful.</li><li>A <strong>node</strong> is a participating machine or computing instance.</li><li><strong>Replication</strong> creates multiple copies of data.</li><li><strong>Partitioning/sharding</strong> divides data across machines.</li><li><strong>Load balancing</strong> distributes requests across servers.</li><li>Distributed systems need <strong>coordination</strong> between nodes.</li><li><strong>Leader election</strong> allows nodes to select a leader when required.</li><li><strong>Consensus</strong> allows distributed nodes to agree on decisions despite failures.</li><li>Network failures and partial failures are fundamental challenges.</li><li>Distributed systems are the foundation of many <strong>Big Data technologies</strong>.</li><li>CAP and PACELC help us understand the trade-offs that arise when building these systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rb1CkDOoSsMS1rZPx94TAA.png" /><figcaption>Summary</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a187a6188cfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PACELC Theorem: The Trade-Off Between Consistency and Latency]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-pacelc-theorem-the-trade-off-between-consistency-and-latency-919da6d158ca?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/919da6d158ca</guid>
            <category><![CDATA[pacelc-theorem]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 07:58:04 GMT</pubDate>
            <atom:updated>2026-09-12T07:58:04.832Z</atom:updated>
            <content:encoded><![CDATA[<p>When we talk about distributed systems, one question appears again and again:</p><p><strong>Should a system prioritize consistency, or should it prioritize speed and availability?</strong></p><p>We have already seen this problem through the <strong>CAP Theorem</strong>. CAP tells us that when a network partition occurs, a distributed system cannot guarantee both <strong>Consistency</strong> and <strong>Availability</strong> at the same time.</p><p>But there is one important limitation: <strong>What happens when there is no network partition?</strong></p><p>Even when everything is working normally, distributed systems still have to make trade-offs.</p><p>For example, should a system wait for multiple replicas to confirm a write before responding, or should it respond immediately and synchronize the replicas afterward?</p><p>Waiting can improve consistency, but it can increase latency. Responding immediately can reduce latency, but some replicas may temporarily contain older data.</p><p>This is where <strong>PACELC Theorem</strong> comes in.</p><h3>Why Do We Need PACELC?</h3><p>CAP focuses mainly on what happens <strong>during a network partition</strong>. But real distributed systems do not spend all their time dealing with network partitions.</p><p>Most of the time, the system is operating normally.</p><p>Even then, there is a trade-off between:</p><ul><li><strong>Consistency</strong></li><li><strong>Latency</strong></li></ul><p>Consider a database replicated across multiple servers. Suppose a user updates their profile. The system could:</p><p><strong>Option 1:</strong><br>Wait until the update is synchronized with other replicas before confirming the operation.</p><p>→ Better consistency<br>→ Potentially higher latency</p><p><strong>Option 2:</strong><br>Confirm the operation immediately and synchronize other replicas asynchronously.</p><p>→ Lower latency<br>→ Some replicas may temporarily return stale data</p><p>CAP does not explicitly describe this normal-operation trade-off. PACELC extends CAP to include it.</p><h3>What is PACELC Theorem?</h3><p>PACELC is an extension of the CAP Theorem.</p><p>Where:</p><ul><li><strong>P = Partition</strong></li><li><strong>A = Availability</strong></li><li><strong>C = Consistency</strong></li><li><strong>E = Else</strong></li><li><strong>L = Latency</strong></li><li><strong>C = Consistency</strong></li></ul><p>The theorem can be expressed as:</p><blockquote><strong><em>If there is a Partition, choose between Availability and Consistency; Else, when there is no partition, choose between Latency and Consistency.</em></strong></blockquote><p>In short:</p><p><strong>During a partition: P → A or C</strong></p><p><strong>During normal operation: E → L or C</strong></p><h3>Breaking Down PACELC</h3><p>Let’s understand each part separately.</p><h4>P → Partition</h4><p>The first question is: <strong>What happens if a network partition occurs? </strong>A network partition means that some nodes in a distributed system cannot communicate with other nodes.</p><p>For example:</p><pre>Server A  ←→  Server B</pre><pre>Server C  ←X→  Server D</pre><p>The servers are still running, but communication between the two groups has failed. This is the <strong>P</strong> in PACELC.</p><h4>A → Availability</h4><p>During a partition, one possible choice is to prioritize <strong>Availability</strong>. The system continues responding to requests even if it cannot communicate with every replica. This means users can continue using the system, but some responses may contain stale or temporarily inconsistent data.</p><h4>C → Consistency</h4><p>The other choice during a partition is <strong>Consistency</strong>. The system may refuse or delay some operations until it can guarantee that the data remains consistent. This protects correctness but can make some requests unavailable. This is the same fundamental trade-off described by CAP.</p><h4>The “E” in PACELC: Else</h4><p>Now comes the part that CAP does not explicitly address. <strong>E means Else.</strong></p><p>In other words:</p><blockquote><strong><em>What happens when there is NO network partition?</em></strong></blockquote><p>The system is operating normally. All replicas can communicate. There is still a trade-off. This time, the trade-off is: <strong>Latency vs Consistency</strong></p><p>That’s why we move from: <strong>P → A/C</strong></p><p>to: <strong>E → L/C</strong></p><h4>L → Latency</h4><p>Latency is the amount of time it takes for a system to respond to a request. In a distributed database, achieving stronger consistency can require communication between multiple machines.</p><p>For example:</p><pre>Client<br>   ↓<br>Server A<br>   ↓<br>Replica B<br>   ↓<br>Replica C<br>   ↓<br>Confirmation<br>   ↓<br>Response to Client</pre><p>The system may need to wait for other nodes before confirming an operation. This can increase latency. On the other hand, the system could respond using the local replica immediately:</p><pre>Client<br>   ↓<br>Server A<br>   ↓<br>Immediate Response</pre><p>This reduces latency, but the local replica might not yet have the latest data.</p><h4>C → Consistency</h4><p>Consistency means that the system tries to ensure that users see the correct and up-to-date state of the data according to the system’s consistency model.</p><p>For example, suppose a user changes their username from:</p><pre>old_name → shreya</pre><p>If the system prioritizes strong consistency, it may make sure the update is properly coordinated before returning success. If the system prioritizes low latency, another replica might temporarily return:</p><pre>old_name</pre><p>while replication catches up. This is sometimes called <strong>stale data</strong> or a <strong>stale read</strong>.</p><h3>The Complete PACELC Decision</h3><p>The easiest way to remember PACELC is through this flow:</p><pre>             Distributed System<br>                     |<br>                     ↓<br>            Is there a partition?<br>                /          \<br>              YES           NO<br>               |             |<br>               ↓             ↓<br>        Consistency or    Consistency or<br>         Availability       Latency</pre><h3>PACELC vs CAP Theorem</h3><p>The two theorems are closely related, but PACELC gives us a more complete picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*NlB3qPc79M11uRbG3CU7EA.png" /></figure><p>CAP essentially tells us:</p><blockquote><strong><em>When a partition happens, you cannot have both strong consistency and availability.</em></strong></blockquote><p>PACELC adds:</p><blockquote><strong><em>Even when there is no partition, choosing stronger consistency can come at the cost of latency.</em></strong></blockquote><h3>Why Does Consistency Increase Latency?</h3><p>This is one of the most important ideas behind PACELC. Imagine a system with three replicas:</p><pre>             Database<br>          /      |      \<br>         /       |       \<br>    Replica A Replica B Replica C</pre><p>A client sends a write to Replica A. If the system wants stronger consistency, it may need to coordinate with the other replicas before confirming the operation.</p><p>More coordination means:</p><ul><li>more network communication</li><li>more waiting</li><li>more dependency on other nodes</li><li>potentially higher response time</li></ul><p>Therefore: <strong>Stronger consistency → more coordination → potentially higher latency</strong></p><p>On the other hand: <strong>Less coordination → lower latency → potentially weaker consistency</strong></p><h3>Synchronous vs Asynchronous Replication</h3><p>Replication is one of the places where this trade-off becomes very visible.</p><h4>Synchronous Replication</h4><p>The system waits for replicas to acknowledge an operation.</p><pre>Client<br>  ↓<br>Primary<br>  ↓<br>Replica 1<br>  ↓<br>Replica 2<br>  ↓<br>Acknowledgement<br>  ↓<br>Client</pre><h4>Advantages</h4><ul><li>Better consistency</li><li>Less chance of stale data</li></ul><h4>Disadvantages</h4><ul><li>Higher latency</li><li>More dependent on replica availability</li></ul><h4>Asynchronous Replication</h4><p>The system does not wait for every replica.</p><h4>Advantages</h4><ul><li>Lower latency</li><li>Faster responses</li></ul><h4>Disadvantages</h4><ul><li>Replicas may temporarily contain stale data</li><li>There can be a delay before all replicas agree</li></ul><p>PACELC helps us understand why systems make these choices.</p><h3>A Simple Example: Online Shopping</h3><p>Imagine an e-commerce application with multiple database replicas.</p><p>A product’s price is:</p><pre>₹999</pre><p>The price is updated to:</p><pre>₹899</pre><p>Now imagine that the update reaches one replica immediately but another replica is still showing ₹999. If the system prioritizes <strong>low latency</strong>, it may allow users to read from a nearby replica without waiting for every replica to synchronize.</p><p>The result: <strong>Fast response, but potentially stale data.</strong></p><p>If the system prioritizes <strong>consistency</strong>, it may coordinate the replicas before serving the response.</p><p>The result: <strong>More consistent data, but potentially higher latency.</strong></p><p>Neither choice is universally better. It depends on the application.</p><h3>Where Does This Trade-Off Matter?</h3><p>Different applications have different requirements.</p><h4>Banking</h4><p>Consistency is extremely important. If a transaction updates an account balance, the system cannot casually return an outdated balance. Therefore, stronger consistency may be preferred even if it adds some latency.</p><h4>Social Media</h4><p>A user’s feed does not necessarily need every replica to be perfectly synchronized immediately. A slightly stale feed is usually acceptable if it loads quickly. Therefore, lower latency may be more important.</p><h3>PACELC and Distributed Databases</h3><p>PACELC is particularly useful when comparing distributed databases.</p><p>A distributed database may have:</p><ul><li>multiple replicas</li><li>multiple servers</li><li>geographic distribution</li><li>network communication between nodes</li><li>replication</li><li>different consistency models</li></ul><p>Every one of these decisions can affect: <strong>Consistency, availability, and latency. </strong>For example, placing replicas closer to users can reduce latency.</p><p>But maintaining strong consistency across geographically distant replicas may require additional coordination. That coordination can increase response time. Therefore, system designers have to decide what matters more for their workload.</p><h3>PACELC Classification</h3><p>PACELC can also be used to describe distributed systems using four-letter combinations. The first part describes what the system prefers during a partition. The second part describes what it prefers during normal operation.</p><p>For example:</p><pre>PA/EL</pre><p>means:</p><ul><li><strong>P → A:</strong> During partition, prioritize Availability</li><li><strong>E → L:</strong> During normal operation, prioritize Latency</li></ul><p>Similarly:</p><pre>PC/EC</pre><p>means:</p><ul><li><strong>P → C:</strong> During partition, prioritize Consistency</li><li><strong>E → C:</strong> During normal operation, prioritize Consistency</li></ul><p>These classifications help us communicate a system’s design priorities more precisely. However, real databases can have configurable consistency models and behavior can vary by operation, configuration, and implementation. So PACELC classifications should be treated as useful design descriptions rather than rigid labels.</p><h3>PACELC and Replication</h3><p>Replication is at the heart of many PACELC trade-offs. Why? Because once data exists on multiple machines, the system needs to keep those copies coordinated.</p><p>Consider:</p><pre>             Write<br>               ↓<br>            Primary<br>           /       \<br>          ↓         ↓<br>     Replica A   Replica B</pre><p>If the system waits for replicas: <strong>Consistency ↑</strong></p><p>but potentially: <strong>Latency ↑</strong></p><p>If the system allows replicas to synchronize later: <strong>Latency ↓</strong></p><p>but potentially: <strong>Staleness ↑</strong></p><p>PACELC gives us a way to reason about this trade-off.</p><h3>PACELC Does Not Mean “Consistency Is Bad”</h3><p>A common misunderstanding is:</p><blockquote><em>“If consistency increases latency, then distributed systems should always choose latency.”</em></blockquote><p>That’s not correct. The goal is not to maximize one property. The goal is to choose the right balance for the application.</p><p>For a payment system: <strong>Consistency &gt; a few milliseconds of latency</strong></p><p>For a social feed: <strong>Low latency &gt; perfectly synchronized replicas</strong></p><p>For another application, the priorities may be completely different.</p><p>Distributed-system design is about understanding these trade-offs and making deliberate decisions.</p><h3>PACELC in the Big Data World</h3><p>Big Data systems are often distributed by nature.</p><p>A system may contain:</p><ul><li>thousands of machines</li><li>replicated data</li><li>distributed storage</li><li>geographically separated nodes</li><li>high request volumes</li></ul><p>At this scale, communication between machines is not free. Every additional coordination step can affect performance.</p><p>Therefore, Big Data systems constantly make decisions around:</p><ul><li>consistency</li><li>availability</li><li>latency</li><li>replication</li><li>fault tolerance</li><li>scalability</li></ul><p>PACELC helps us understand the reasoning behind these design decisions.</p><h3>Key Takeaways</h3><ul><li><strong>PACELC is an extension of the CAP Theorem.</strong></li><li><strong>P = Partition</strong></li><li><strong>A = Availability</strong></li><li><strong>C = Consistency</strong></li><li><strong>E = Else</strong></li><li><strong>L = Latency</strong></li><li><strong>C = Consistency</strong></li></ul><p>The core idea is:</p><blockquote><strong><em>If there is a Partition, choose between Availability and Consistency; Else, choose between Latency and Consistency.</em></strong></blockquote><p>During a partition: <strong>P → A or C</strong></p><p>During normal operation: <strong>E → L or C</strong></p><p>Strong consistency often requires more coordination between replicas, which can increase latency. Lower latency can be achieved by reducing coordination or serving from local/nearby replicas, but this can allow stale data.</p><p>Most importantly: <strong>There is no universally “best” choice. </strong>The right trade-off depends on what the application values most.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGjbnOrZ-fS1vhEZxnK_Ug.png" /><figcaption>PACELC Theorem Summary</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=919da6d158ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding HBase: The Distributed NoSQL Database Built for Big Data]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-hbase-the-distributed-nosql-database-built-for-big-data-935fd7b6fdb3?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/935fd7b6fdb3</guid>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[hbase]]></category>
            <category><![CDATA[hbase-architecture]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 14:16:23 GMT</pubDate>
            <atom:updated>2026-09-10T14:16:23.105Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, we stepped outside the traditional relational database world and explored <strong>NoSQL databases</strong>.</p><p>We learned that NoSQL databases come in different forms:</p><ul><li>Key-Value</li><li>Document</li><li>Column-Family</li><li>Graph</li></ul><p>We also saw that <strong>Apache HBase</strong> belongs to the <strong>Column-Family</strong> category.</p><p>But that raises an obvious question:</p><blockquote><strong><em>What exactly is HBase, and why would we need another database when Hadoop already gives us HDFS?</em></strong></blockquote><p>To answer that, we need to understand the problem HBase was designed to solve.</p><h3>HDFS Stores Data… But Can It Act Like a Database?</h3><p>Let’s say we have billions of records stored in HDFS.</p><p>HDFS is excellent for:</p><ul><li>Storing huge files</li><li>Distributed storage</li><li>High-throughput batch processing</li><li>Fault tolerance</li></ul><p>But suppose an application asks:</p><blockquote><em>“Give me the record for user </em><em>U12345 right now.&quot;</em></blockquote><p>HDFS isn’t designed to behave like a traditional database where we can efficiently perform random, low-latency reads and writes to individual records.</p><p>HDFS is primarily a <strong>distributed file system</strong>.</p><p>We need something on top of distributed storage that can provide:</p><ul><li>Random reads</li><li>Random writes</li><li>Fast access to individual records</li><li>Horizontal scalability</li><li>Distributed storage</li><li>Integration with Hadoop</li></ul><p>This is where: <strong>Apache HBase </strong>comes in.</p><h3>What is HBase?</h3><p><strong>Apache HBase</strong> is a distributed, open-source, NoSQL database designed to store and access very large datasets across a cluster.</p><p>It is a <strong>column-family database</strong> inspired by Google’s Bigtable design.</p><p>HBase is designed to work closely with the Hadoop ecosystem and typically uses <strong>HDFS for persistent storage</strong>.</p><p>In simple terms:</p><blockquote><strong><em>HDFS is primarily responsible for storing distributed files, while HBase provides database-style random read/write access to large distributed datasets.</em></strong></blockquote><p>Think of the relationship as:</p><pre>               Hadoop Ecosystem<br>                     │<br>          ┌──────────┴──────────┐<br>          ↓                     ↓<br>        HDFS                  HBase<br>   Distributed Storage    NoSQL Database<br>          │                     │<br>          ↓                     ↓<br>      Store files         Read / Write data</pre><p>HBase is therefore not a replacement for HDFS. It uses the Hadoop ecosystem to provide a different level of access to data.</p><h3>Why Was HBase Needed?</h3><p>Imagine a company has: <strong>Billions of customer records. </strong>A relational database might store them in tables. But as the data becomes enormous, distributed storage and horizontal scaling become increasingly important.</p><p>HBase is designed for workloads where we need:</p><ul><li>Very large tables</li><li>Millions or billions of rows</li><li>Distributed storage</li><li>High write throughput</li><li>Random reads and writes</li><li>Horizontal scalability</li></ul><p>For example:</p><pre>User ID → User Information<br>U10001  → ...<br>U10002  → ...<br>U10003  → ...<br>...<br>U999999999 → ...</pre><p>Instead of treating the entire dataset as one massive file, HBase provides a database abstraction over distributed storage.</p><h3>Understanding the HBase Data Model</h3><p>This is probably the most important part of HBase. At first glance, HBase looks somewhat like a relational table. But internally, its data model is quite different.</p><p>The basic structure is:</p><pre>Table<br>  ↓<br>Rows<br>  ↓<br>Row Key<br>  ↓<br>Column Families<br>  ↓<br>Columns<br>  ↓<br>Values</pre><p>Let’s understand each part.</p><h4>1. Row Key</h4><p>Every row in HBase has a unique identifier called the: Row Key</p><p>For example:</p><pre>user_101<br>user_102<br>user_103</pre><p>The row key is extremely important because HBase stores and retrieves rows based on it.</p><p>For example:</p><pre>Row Key: user_101</pre><p>could identify one particular user’s data.</p><p>A good row-key design is therefore very important for HBase performance.</p><h4>2. Column Family</h4><p>This is one of the biggest differences from a traditional relational table. HBase groups related columns into Column Families.</p><p>Suppose we have:</p><pre>user</pre><p>as one column family.</p><p>Inside it we could have:</p><pre>user:name<br>user:age<br>user:city</pre><p>Another family could be:</p><pre>activity</pre><p>containing:</p><pre>activity:last_login<br>activity:posts<br>activity:likes</pre><p>Conceptually:</p><pre>Row Key: user_101</pre><pre>user<br> ├── name<br> ├── age<br> └── city</pre><pre>activity<br> ├── last_login<br> ├── posts<br> └── likes</pre><p>Column families are defined at the table level.</p><h4>3. Columns</h4><p>Inside a column family, we can have individual columns.</p><p>For example:</p><pre>user:name<br>user:age<br>user:city</pre><p>Here:</p><pre>user → Column Family<br>name → Column Qualifier</pre><p>The complete identifier is:</p><pre>Column Family : Column Qualifier</pre><p>For example:</p><pre>user:name</pre><h4>4. Cell</h4><p>A specific value stored at the intersection of a:</p><ul><li>Row</li><li>Column family</li><li>Column qualifier</li><li>Timestamp</li></ul><p>is called a <strong>cell</strong>.</p><p>For example:</p><pre>user_101<br>   ↓<br>user:name<br>   ↓<br>&quot;Shireen&quot;</pre><p>HBase cells can maintain multiple versions of a value using timestamps.</p><h4>5. Versions and Timestamps</h4><p>HBase can maintain multiple versions of a cell.</p><p>For example:</p><pre>user:name</pre><pre>Timestamp 1 → &quot;Ritu&quot;<br>Timestamp 2 → &quot;Ritu Raj&quot;</pre><p>The timestamp helps identify versions. This can be useful when data changes over time. The number of versions retained is configurable.</p><h3>Putting the HBase Data Model Together</h3><p>Suppose we have this HBase table:</p><pre>users</pre><p>with two column families:</p><pre>info<br>activity</pre><p>Our data might look conceptually like:</p><pre>Row Key: 101</pre><pre>info:name        → Shreya<br>info:city        → Noida<br>info:age         → 21</pre><pre>activity:posts   → 45<br>activity:likes   → 120</pre><p>Another row could have:</p><pre>Row Key: 102</pre><pre>info:name        → Rahul<br>info:city        → Delhi</pre><pre>activity:posts   → 20</pre><p>Notice something interesting. The second row doesn’t necessarily need exactly the same set of columns. This is one of the flexible aspects of HBase’s data model.</p><h3>HBase vs Relational Tables</h3><p>At first glance, you might think:</p><blockquote><em>“This looks like a normal table.”</em></blockquote><p>But there are important differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*xDUDVTaBpaNasbw8YMD-ww.png" /></figure><p>The biggest difference is the <strong>data model and architecture</strong>.</p><h3>HBase Architecture</h3><p>Now let’s look at the architecture. A simplified HBase cluster looks like:</p><pre>                  HBase Cluster<br>                       │<br>                    HMaster<br>                       │<br>          ┌────────────┼────────────┐<br>          ↓            ↓            ↓<br>     RegionServer  RegionServer  RegionServer<br>          │            │            │<br>       Regions       Regions       Regions<br>          │            │            │<br>          └────────────┼────────────┘<br>                       ↓<br>                      HDFS</pre><p>There are several important components here:</p><ul><li>HMaster</li><li>RegionServer</li><li>Regions</li><li>HDFS</li><li>ZooKeeper</li></ul><p>Let’s understand them one by one.</p><h4>HMaster</h4><p>The <strong>HMaster</strong> is responsible for cluster-level administrative tasks.</p><p>It handles things such as:</p><ul><li>Managing regions</li><li>Assigning regions to RegionServers</li><li>Load balancing</li><li>Schema operations</li><li>Monitoring RegionServers</li><li>Coordinating administrative tasks</li></ul><p>A simplified view:</p><pre>             HMaster<br>             /     \<br>            ↓       ↓<br>      RegionServer RegionServer</pre><p>The HMaster is important for <strong>management and coordination</strong>. It does not handle every client read/write request. That’s an important point.</p><h4>RegionServer</h4><p>The <strong>RegionServer</strong> is where much of the actual data-serving work happens.</p><p>It handles:</p><ul><li>Reads</li><li>Writes</li><li>Regions</li><li>Client requests</li></ul><p>For example:</p><pre>Client<br>   ↓<br>RegionServer<br>   ↓<br>Region<br>   ↓<br>Data</pre><p>A cluster can have multiple RegionServers. This allows the workload to be distributed.</p><h4>What is a Region?</h4><p>This is one of the most important HBase concepts. A large HBase table is divided horizontally into: Regions</p><p>Suppose our row keys are:</p><pre>001<br>002<br>003<br>...<br>1000000</pre><p>Instead of storing everything on one server:</p><pre>Entire Table<br>     ↓<br>One Server</pre><p>HBase divides the table into regions:</p><pre>Table<br> │<br> ├── Region 1 → Rows 001–250000<br> ├── Region 2 → Rows 250001–500000<br> ├── Region 3 → Rows 500001–750000<br> └── Region 4 → Rows 750001–1000000</pre><p>These regions can be distributed across different RegionServers.</p><p>This allows HBase to scale horizontally.</p><h4>Region Splitting</h4><p>What happens when a region becomes too large? HBase can split it.</p><p>For example:</p><pre>Before:</pre><pre>Region 1<br>Rows A → Z</pre><p>becomes:</p><pre>After:</pre><pre>Region 1A<br>Rows A → M</pre><pre>Region 1B<br>Rows N → Z</pre><p>The resulting regions can then be served independently. This allows the database to continue scaling as the amount of data increases.</p><h3>How Does HBase Find the Correct Region?</h3><p>Suppose a client wants:</p><pre>Row Key = user_5000</pre><p>HBase needs to determine:</p><blockquote><strong><em>Which region contains this row?</em></strong></blockquote><p>It uses metadata about the region layout to locate the appropriate RegionServer and region.</p><p>Conceptually:</p><pre>Client<br>  ↓<br>Find Region<br>  ↓<br>Find RegionServer<br>  ↓<br>Send Request<br>  ↓<br>Read / Write</pre><p>Once the client knows where the relevant region is, it can communicate with the appropriate RegionServer.</p><h4>ZooKeeper</h4><p>Another important component in the HBase ecosystem is: Apache ZooKeeper. ZooKeeper provides distributed coordination services.</p><p>In HBase deployments, ZooKeeper helps with things such as:</p><ul><li>Cluster coordination</li><li>RegionServer tracking</li><li>Master election/coordination</li><li>Maintaining important cluster state</li></ul><p>A simplified picture:</p><pre>             ZooKeeper<br>             /   |   \<br>            ↓    ↓    ↓<br>          HMaster RegionServer RegionServer</pre><p>You don’t need to memorise every internal ZooKeeper detail at this stage.</p><p>The important idea is:</p><blockquote><strong><em>ZooKeeper helps HBase components coordinate in a distributed environment.</em></strong></blockquote><h3>Where Does HBase Store the Data?</h3><p>This is another important question. HBase generally uses: HDFS for persistent storage.</p><p>So the architecture becomes:</p><pre>                 HBase<br>                   │<br>             RegionServers<br>                   │<br>                Regions<br>                   │<br>                   ↓<br>                  HDFS<br>                   │<br>              Distributed<br>                Storage</pre><p>HBase provides the database interface. HDFS provides distributed persistent storage underneath. This is why HBase fits naturally into the Hadoop ecosystem.</p><h3>HBase Write Flow</h3><p>Let’s understand what happens when a client writes data.</p><p>Suppose we execute:</p><pre>PUT user_101, info:name, Shanaya</pre><p>A simplified flow is:</p><pre>Client<br>   ↓<br>Locate Region<br>   ↓<br>RegionServer<br>   ↓<br>Write to WAL<br>   ↓<br>MemStore<br>   ↓<br>Later flushed to disk<br>   ↓<br>HFiles on HDFS</pre><p>Let’s understand these pieces.</p><h4>Write-Ahead Log (WAL)</h4><p>Before data is permanently written to the underlying storage files, HBase uses a: Write-Ahead Log</p><p>The basic principle is:</p><blockquote><strong><em>Record the change in the log before relying on the in-memory update as durable.</em></strong></blockquote><p>This helps with recovery if a RegionServer fails.</p><p>Conceptually:</p><pre>Write Request<br>      ↓<br>     WAL<br>      ↓<br>   MemStore<br>      ↓<br>   HFile/HDFS</pre><p>If a failure occurs before the data reaches its final storage location, the WAL can help recover the changes.</p><h3>MemStore</h3><p>After being written to the WAL, data is kept in memory in a structure called MemStore. Each Region has MemStores associated with its column families.</p><p>For example:</p><pre>Region<br>  │<br>  ├── Column Family A → MemStore<br>  └── Column Family B → MemStore</pre><p>MemStore allows HBase to accumulate writes in memory before flushing them to disk.</p><h4>HFiles</h4><p>Eventually, MemStore data is flushed to disk as HFiles. These files are stored in HDFS.</p><p>So the simplified lifecycle is:</p><pre>Client Write<br>     ↓<br>    WAL<br>     ↓<br> MemStore<br>     ↓<br>   Flush<br>     ↓<br>   HFile<br>     ↓<br>   HDFS</pre><p>This is an important flow to understand.</p><h3>HBase Read Flow</h3><p>Now suppose the client wants:</p><pre>user_101</pre><p>The request follows a simplified path:</p><pre>Client<br>   ↓<br>Locate Region<br>   ↓<br>RegionServer<br>   ↓<br>Check MemStore<br>   ↓<br>Check BlockCache<br>   ↓<br>Read HFiles if necessary<br>   ↓<br>Return Result</pre><p>HBase can therefore retrieve data from in-memory structures or persistent storage.</p><h3>BlockCache</h3><p>HBase also uses a <strong>BlockCache</strong> to keep frequently accessed data blocks in memory.</p><p>The basic idea is:</p><pre>Frequently accessed data<br>          ↓<br>      Keep in memory<br>          ↓<br>      Faster reads</pre><p>So repeated reads don’t always require accessing the underlying storage.</p><h3>Complete HBase Read/Write Picture</h3><p>Putting everything together:</p><pre>                    Client<br>                       │<br>                       ↓<br>                Region Location<br>                       │<br>                       ↓<br>                 RegionServer<br>                  /         \<br>                 ↓           ↓<br>              READ         WRITE<br>               ↓              ↓<br>          BlockCache          WAL<br>               ↓              ↓<br>           MemStore?       MemStore<br>               ↓              ↓<br>            HFiles          Flush<br>               ↓              ↓<br>              HDFS          HFiles</pre><p>This is a simplified view, but it captures the important architecture.</p><h3>Basic HBase Commands</h3><p>HBase provides a shell for interacting with tables. Let’s look at some basic operations.</p><h4>1. Create a Table</h4><p>Suppose we want a table called:</p><pre>users</pre><p>with a column family:</p><pre>info</pre><p>We can conceptually write:</p><pre>create &#39;users&#39;, &#39;info&#39;</pre><h4>2. Insert Data</h4><p>To insert a user’s name:</p><pre>put &#39;users&#39;, &#39;101&#39;, &#39;info:name&#39;, &#39;Shanaya&#39;</pre><p>Here:</p><pre>users       → Table<br>101         → Row Key<br>info        → Column Family<br>name        → Column<br>Shireen     → Value</pre><h4>3. Read a Row</h4><pre>get &#39;users&#39;, &#39;101&#39;</pre><p>This retrieves the data associated with row key 101.</p><h4>4. Scan a Table</h4><pre>scan &#39;users&#39;</pre><p>This can retrieve rows from the table. A scan is useful when we need to process a range or many rows rather than one specific row.</p><h4>5. Delete Data</h4><p>For example:</p><pre>delete &#39;users&#39;, &#39;101&#39;, &#39;info:name&#39;</pre><p>This deletes the specified cell.</p><h4>6. Delete a Table</h4><p>A table generally needs to be disabled before being dropped:</p><pre>disable &#39;users&#39;<br>drop &#39;users&#39;</pre><p>These commands illustrate the basic CRUD-style operations available through the HBase shell.</p><h3>HBase vs Relational Database</h3><p>Let’s compare HBase with a traditional relational database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*o_bvAozwB4ruGbJG-4Xe3w.png" /></figure><p>Again, this does <strong>not</strong> mean HBase is universally better. The workload determines the appropriate database.</p><h3>Why HBase Works Well for Sparse Data</h3><p>Consider a dataset with many possible attributes.</p><p>Suppose we have:</p><pre>User<br> ├── Name<br> ├── Age<br> ├── City<br> ├── Phone<br> ├── Website<br> ├── College<br> ├── Job<br> ├── ...</pre><p>But not every user has every attribute.</p><p>One user may have:</p><pre>Name<br>City<br>College</pre><p>Another may have:</p><pre>Name<br>City<br>Job<br>Website</pre><p>HBase can naturally represent such sparse data without requiring every row to contain every possible column. This is one of the useful characteristics of the column-family model.</p><h3>HBase and Horizontal Scalability</h3><p>Suppose our dataset grows from:</p><pre>1 TB</pre><p>to:</p><pre>100 TB</pre><p>We don’t necessarily want one enormous server. HBase can distribute regions across multiple RegionServers.</p><p>For example:</p><pre>              HBase Table<br>                   │<br>        ┌──────────┼──────────┐<br>        ↓          ↓          ↓<br>      Region     Region     Region<br>        ↓          ↓          ↓<br>      Server A   Server B   Server C</pre><p>As the workload grows, more machines can be added to the cluster. This is one of the major reasons HBase is useful for Big Data workloads.</p><h3>HBase Limitations</h3><p>HBase is powerful, but it comes with trade-offs.</p><h4>1. No traditional SQL interface</h4><p>HBase isn’t designed around relational SQL querying.</p><h4>2. No traditional joins</h4><p>If your application heavily depends on complex joins, HBase may not be the best choice.</p><h4>3. Row-key design is critical</h4><p>A poorly designed row key can create uneven data distribution and performance problems.</p><h4>4. Operational complexity</h4><p>Running a distributed HBase cluster requires understanding:</p><ul><li>HDFS</li><li>RegionServers</li><li>HMaster</li><li>ZooKeeper</li><li>Regions</li><li>Replication</li><li>Failure handling</li></ul><h4>5. Not ideal for every workload</h4><p>For small datasets or complex relational queries, a traditional relational database may be much simpler.</p><h3>The Importance of Row-Key Design</h3><p>One of the most important practical HBase concepts is “<strong>Choose your row key carefully”</strong>.</p><p>Suppose we use sequential row keys:</p><pre>1<br>2<br>3<br>4<br>5<br>...</pre><p>Depending on the region layout and write pattern, new writes can become concentrated around one part of the key space. This can create a <strong>hotspot</strong>. Instead, applications sometimes design row keys to distribute writes more evenly.</p><p>Possible techniques include:</p><ul><li>Salting</li><li>Hashing</li><li>Reversing identifiers</li><li>Composite keys</li></ul><p>The exact strategy depends on the application’s access pattern.</p><p>The important lesson is:</p><blockquote><strong><em>HBase performance depends heavily on how you design and access your row keys.</em></strong></blockquote><h3>HBase and CAP Theorem</h3><p>Remember our previous article?</p><p>We learned about:</p><p><strong>Consistency</strong></p><p><strong>Availability</strong></p><p><strong>Partition Tolerance</strong></p><p>HBase operates in a distributed environment, so distributed-system trade-offs matter. HBase is generally designed around <strong>strong consistency for row-level operations</strong>, while also providing distributed fault tolerance and scalability.</p><p>Different NoSQL databases make different consistency and availability choices. This is why we should understand the actual architecture of each database.</p><h3>Where is HBase Useful?</h3><p>HBase is suitable for applications that need:</p><h4>Massive datasets</h4><p>Millions or billions of rows.</p><h4>Fast random access</h4><p>Retrieve or update data using a row key.</p><h4>High write throughput</h4><p>Applications continuously generating large volumes of data.</p><h4>Sparse data</h4><p>Rows may contain different sets of columns.</p><h4>Distributed storage</h4><p>Data needs to be spread across multiple machines. Potential use cases include:</p><ul><li>User profiles</li><li>Time-series-like datasets</li><li>Large-scale logs</li><li>Sensor data</li><li>Messaging data</li><li>Financial records</li><li>Large distributed lookup systems</li></ul><p>The exact suitability depends on the workload and architecture.</p><h3>HBase in the Hadoop Ecosystem</h3><p>Now let’s connect everything.</p><p>We’ve already learned:</p><h4>HDFS</h4><p>Stores distributed data.</p><h4>MapReduce</h4><p>Processes large datasets in parallel.</p><h4>YARN</h4><p>Manages cluster resources.</p><p>And now:</p><h4>HBase</h4><p>Provides distributed NoSQL database access.</p><p>Conceptually:</p><pre>                  HADOOP ECOSYSTEM<br>                        │<br>       ┌────────────────┼────────────────┐<br>       ↓                ↓                ↓<br>      HDFS           MapReduce          HBase<br>       │                │                │<br> Distributed       Distributed      NoSQL Database<br>  Storage           Processing        Access<br>       │                │                │<br>       └────────────────┼────────────────┘<br>                        ↓<br>                  Big Data Platform</pre><h3>Key Takeaways</h3><p>If you remember only a few things from this article, remember these:</p><p><strong>1. HBase is a distributed NoSQL database designed for very large datasets.</strong></p><p><strong>2. HBase belongs to the column-family NoSQL category.</strong></p><p><strong>3. HBase is closely integrated with the Hadoop ecosystem and commonly uses HDFS for persistent storage.</strong></p><p><strong>4. HDFS is primarily a distributed file system, while HBase provides database-style random read/write access.</strong></p><p><strong>5. HBase organizes data using tables, row keys, column families, column qualifiers, cells, and timestamps.</strong></p><p><strong>6. A row key uniquely identifies a row and is extremely important for HBase performance.</strong></p><p><strong>7. Large HBase tables are divided into regions, which can be distributed across RegionServers.</strong></p><p><strong>8. HMaster manages cluster-level administrative operations, while RegionServers handle data-serving operations.</strong></p><p><strong>9. ZooKeeper provides distributed coordination within the HBase ecosystem.</strong></p><p><strong>10. Writes involve mechanisms such as the WAL and MemStore before data is flushed into HFiles stored on HDFS.</strong></p><p><strong>11. HBase supports horizontal scaling by distributing regions across multiple servers.</strong></p><p><strong>12. HBase is not a replacement for relational databases; it is designed for different workloads.</strong></p><p><strong>13. HBase is especially useful when we need huge distributed datasets with fast key-based reads and writes.</strong></p><p><strong>14. Good row-key design is critical because poor key design can lead to hotspots and uneven workloads.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfVmX0JYIcVGPh30yrxTOw.png" /><figcaption>HBase SUMMARY</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=935fd7b6fdb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding NoSQL Databases: Why Big Data Needed a Different Approach]]></title>
            <link>https://medium.com/@kachrooshireen3/understanding-nosql-databases-why-big-data-needed-a-different-approach-11516addf8ee?source=rss-3bdf82716559------2</link>
            <guid isPermaLink="false">https://medium.com/p/11516addf8ee</guid>
            <category><![CDATA[cap]]></category>
            <category><![CDATA[sql-vs-nosql]]></category>
            <category><![CDATA[types-of-nosql-databases]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[nosql-database]]></category>
            <dc:creator><![CDATA[Shireen Kachroo]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 13:43:09 GMT</pubDate>
            <atom:updated>2026-09-10T13:43:09.422Z</atom:updated>
            <content:encoded><![CDATA[<p>So far in our, we’ve seen how data can be:</p><ul><li>Ingested from different sources</li><li>Stored in Data Lakes</li><li>Represented using different file formats</li><li>Distributed across machines using Hadoop</li><li>Processed using MapReduce</li></ul><p>We also learned about <strong>CAP Theorem</strong>, which showed us that distributed systems have to deal with an important trade-off between <strong>Consistency, Availability, and Partition Tolerance</strong>.</p><p>Now let’s look at another major question:</p><blockquote><strong><em>If our data is becoming massive and distributed, are traditional relational databases always the best choice?</em></strong></blockquote><p>For many applications, relational databases are still an excellent choice. But when systems started dealing with:</p><ul><li>Huge volumes of data</li><li>Rapidly changing data</li><li>Unstructured and semi-structured information</li><li>Millions of users</li><li>Globally distributed applications</li><li>Very high read/write traffic</li></ul><p>developers began looking for different database architectures.</p><p>This led to the rise of: <strong>NoSQL Databases</strong></p><h3>What is NoSQL?</h3><p>NoSQL generally refers to database systems that do not rely on the traditional relational, table-based model as their primary way of representing data.</p><p>The name is commonly interpreted as: <strong><em>“Not Only SQL”</em></strong></p><p>This is important. NoSQL does <strong>not</strong> necessarily mean: <em>“No SQL at all.”</em></p><p>Instead, it represents a broader family of databases that use different data models and access patterns depending on the problem.</p><p>Instead of forcing every dataset into:</p><pre>Table<br> ├── Rows<br> └── Columns</pre><p>NoSQL databases can represent data using models such as:</p><pre>Key → Value<br>Document<br>Column Family<br>Graph</pre><p>The goal is often to make it easier to build systems that require <strong>horizontal scalability, flexible schemas, high throughput, or distributed operation</strong>.</p><h3>First, Let’s Understand Traditional Relational Databases</h3><p>Before understanding why NoSQL exists, let’s quickly revisit the relational model. A relational database stores data in tables.</p><p>For example, an e-commerce application might have:</p><pre>CUSTOMERS</pre><pre>ID | Name   | City<br>---|--------|------<br>1  | Aisha  | Delhi<br>2  | Rahul  | Noida<br>3  | Neha   | Jaipur</pre><p>And another table:</p><pre>ORDERS</pre><pre>Order_ID | Customer_ID | Amount<br>---------|-------------|-------<br>101      | 1           | 500<br>102      | 2           | 900<br>103      | 1           | 300</pre><p>The relationship between the tables is maintained using keys.</p><p>This model is powerful because it provides:</p><ul><li>Structured data</li><li>Relationships</li><li>SQL querying</li><li>Transactions</li><li>Strong consistency options</li><li>Mature tooling</li></ul><p>For many applications, this is exactly what we need. But at very large scale, some challenges can appear.</p><h3>Why Did NoSQL Become Popular?</h3><p>The growth of the internet changed the amount and type of data applications had to handle.</p><p>Consider applications such as:</p><ul><li>Social media</li><li>Search engines</li><li>Online shopping</li><li>Streaming platforms</li><li>Gaming</li><li>IoT</li><li>Real-time analytics</li></ul><p>These systems may have: <strong>Millions or billions of records </strong>and potentially: <strong>Thousands or millions of requests per second.</strong></p><p>Traditional relational databases can scale significantly, but scaling a single relational system vertically can eventually become <strong>expensive or insufficient </strong>for certain workloads.</p><p>This encouraged architectures based heavily on: <strong>Horizontal Scaling</strong></p><h3>Vertical vs Horizontal Scaling</h3><p>Let’s understand this difference.</p><h4>Vertical Scaling</h4><p>We make one machine more powerful.</p><p>For example:</p><pre>Server<br>  ↓<br>More CPU<br>More RAM<br>More Storage</pre><p>This is called <strong>scale up</strong>. It can work well, but the machine has physical and economic limits.</p><h3>Horizontal Scaling</h3><p>Instead of making one machine more powerful, we add more machines.</p><pre>       Server<br>          ↓<br>   ┌──────┼──────┐<br>   ↓      ↓      ↓<br>Server  Server  Server</pre><p>This is called <strong>scale out</strong>. Distributed NoSQL databases are often designed with horizontal scaling as a core requirement.</p><h3>The Main Idea Behind NoSQL</h3><p>The central idea isn’t simply: <em>“NoSQL is better than SQL.”</em></p><p>Instead: <strong>Different applications have different data and scalability requirements, so different database models make sense for different problems.</strong></p><p>For example: A banking application may strongly depend on transactions and consistency. A social media application may need massive scalability and flexible data structures. An IoT application may continuously generate huge amounts of time-series-like data. A recommendation system may need to represent relationships between users and products.</p><p>One database model doesn’t have to solve all of these problems equally well.</p><h3>The Four Major Types of NoSQL Databases</h3><p>NoSQL databases are commonly divided into four major categories:</p><h4>1. Key-Value Databases</h4><p>This is the simplest NoSQL model.</p><p>Data is stored as:</p><pre>Key → Value</pre><p>For example:</p><pre>&quot;user_101&quot; → &quot;Shreya&quot;<br>&quot;user_102&quot; → &quot;Rahul&quot;<br>&quot;user_103&quot; → &quot;Aisha&quot;</pre><p>The key uniquely identifies the value.</p><p>Another example could be:</p><pre>&quot;session_123&quot; → User Session Data</pre><p>The database can quickly find the value using the key.</p><h3>Why Use Key-Value Databases?</h3><p>They are useful when we already know the key and primarily need fast access to the associated value.</p><p>Common applications include:</p><ul><li>Caching</li><li>Session management</li><li>Shopping carts</li><li>User preferences</li><li>Real-time counters</li></ul><p>A well-known example is: <strong>Redis</strong></p><h4>2. Document Databases</h4><p>Document databases store data as documents, commonly represented using JSON-like structures.</p><p>For example:</p><pre>{<br>    &quot;id&quot;: 101,<br>    &quot;name&quot;: &quot;Shreya&quot;,<br>    &quot;city&quot;: &quot;Noida&quot;,<br>    &quot;skills&quot;: [<br>        &quot;C++&quot;,<br>        &quot;Python&quot;,<br>        &quot;SQL&quot;<br>    ]<br>}</pre><p>Instead of splitting this information across multiple relational tables, a document database can store the related information together in a single document.</p><h4>Why Are Document Databases Useful?</h4><p>One major advantage is <strong>schema flexibility</strong>.</p><p>Suppose one user has:</p><pre>name<br>city<br>skills</pre><p>while another user also has:</p><pre>name<br>city<br>skills<br>experience<br>projects</pre><p>A document-oriented database can often accommodate these differences more naturally than a rigid relational schema.</p><p>This makes document databases useful for:</p><ul><li>Content management</li><li>Product catalogues</li><li>User profiles</li><li>Web applications</li><li>Applications where data structures evolve frequently</li></ul><p>A popular example is: <strong>MongoDB</strong></p><h4>3. Column-Family Databases</h4><p>Column-family databases organize data around <strong>column families</strong> rather than traditional relational tables.</p><p>This model is particularly useful for:</p><ul><li>Massive datasets</li><li>Distributed storage</li><li>High write throughput</li><li>Large-scale analytical or operational workloads</li></ul><p>A well-known example is: <strong>Apache HBase</strong></p><p>HBase is especially important in the Hadoop ecosystem because it can provide distributed, random, real-time read/write access over very large datasets.</p><h4>4. Graph Databases</h4><p>Some applications aren’t primarily about rows and columns.</p><p>They’re about: <strong><em>Relationships.</em></strong></p><p>For example:</p><pre>Shreya<br>   ↓ follows<br>Rahul<br>   ↓ follows<br>Aisha</pre><p>A graph database represents entities as <strong>nodes</strong> and their relationships as <strong>edges</strong>.</p><p>For example:</p><pre>       Rahul<br>      /     \<br> follows   works_with<br>    ↓          ↓<br> Shreya     Aisha</pre><p>Graph databases are useful for:</p><ul><li>Social networks</li><li>Recommendation systems</li><li>Fraud detection</li><li>Network analysis</li><li>Knowledge graphs</li><li>Relationship-heavy applications</li></ul><p>When relationships are the central part of the problem, graph databases can be a natural choice.</p><h3>SQL vs NoSQL</h3><p>Let’s compare the traditional relational model with the broader NoSQL approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*icL8Z8w1feBvpujxO18j3Q.png" /></figure><p>But there is an important point:</p><blockquote><strong><em>SQL databases can also scale horizontally and run in distributed architectures.</em></strong></blockquote><p>And:</p><blockquote><strong><em>NoSQL databases can also provide strong consistency and transactions.</em></strong></blockquote><p>So we should avoid treating SQL and NoSQL as two completely rigid categories. The real difference is primarily about <strong>data models, system architecture, scalability patterns, and workload requirements</strong>.</p><h4>Schema: Fixed vs Flexible</h4><p>One of the biggest differences you’ll hear about is schema.</p><h4>Relational Database</h4><p>A relational database typically defines the structure beforehand.</p><p>For example:</p><pre>STUDENT</pre><pre>ID<br>Name<br>Age<br>Department</pre><p>Every row follows this structure.</p><h4>Document Database</h4><p>A document database can allow documents with different fields.</p><p>For example:</p><pre>Document 1</pre><pre>{<br>    &quot;name&quot;: &quot;Shireen&quot;,<br>    &quot;age&quot;: 21<br>}</pre><p>Another document could be:</p><pre>{<br>    &quot;name&quot;: &quot;Rahul&quot;,<br>    &quot;age&quot;: 22,<br>    &quot;skills&quot;: [&quot;C++&quot;, &quot;SQL&quot;]<br>}</pre><p>This flexibility can be useful when application requirements change frequently.</p><p>However, flexibility does <strong>not</strong> mean:</p><blockquote><em>“No structure is required.”</em></blockquote><p>Poorly designed document schemas can still create data-quality and maintenance problems.</p><h3>NoSQL and Horizontal Scaling</h3><p>One of the major reasons NoSQL became popular was its compatibility with distributed architectures.</p><p>Suppose we have:</p><pre>              NoSQL Database<br>                   │<br>        ┌──────────┼──────────┐<br>        ↓          ↓          ↓<br>      Node 1     Node 2     Node 3</pre><p>As the dataset grows, we can add more nodes:</p><pre>Node 1<br>Node 2<br>Node 3<br>   ↓<br>Node 4<br>Node 5<br>...</pre><p>The data can be distributed across the cluster.</p><p>This approach is called:</p><h4>Scale Out</h4><p>It is particularly useful for applications that need to handle massive amounts of data and traffic.</p><h3>Sharding</h3><p>Another important concept in distributed NoSQL databases is: <strong>Sharding</strong></p><p>Sharding means dividing data across multiple machines.</p><p>For example, suppose we have:</p><pre>Users 1–1,000,000</pre><p>We could distribute the data:</p><pre>Shard 1 → Users 1–250,000<br>Shard 2 → Users 250,001–500,000<br>Shard 3 → Users 500,001–750,000<br>Shard 4 → Users 750,001–1,000,000</pre><p>Now different machines handle different portions of the dataset. This allows the system to scale horizontally.</p><h3>Replication in NoSQL</h3><p>Sharding distributes data. But what happens if a machine fails?</p><p>We can use: <strong>Replication</strong></p><p>For example:</p><pre>             Shard 1<br>            /       \<br>       Primary     Replica</pre><p>If the primary node fails, another replica may be able to take over, depending on the database’s architecture.</p><p><strong>So Sharding → Helps with</strong> <strong>scalability</strong></p><p><strong>Replication → Helps with availability and fault tolerance</strong></p><p><strong>Many distributed databases use both.</strong></p><h3>NoSQL and CAP Theorem</h3><p>Remember our previous article?</p><p>We discussed: <strong>Consistency, Availability, Partition Tolerance</strong></p><p>NoSQL databases often operate in distributed environments where network partitions are possible. Therefore, CAP-related trade-offs become important.</p><p>Depending on the database and configuration, a system may prioritise:</p><h4>Stronger consistency</h4><p>or</p><h4>Higher availability with eventual consistency</h4><p>The important thing is:</p><blockquote><strong><em>There is no single CAP behaviour shared by every NoSQL database.</em></strong></blockquote><p>Different systems make different design choices. This is why understanding the actual database architecture is more important than simply memorising: <em>“NoSQL = AP.” </em>That’s an oversimplification.</p><h3>Eventual Consistency</h3><p>Some distributed NoSQL systems use <strong>eventual consistency</strong>. This means replicas may temporarily contain different values but eventually converge.</p><p>For example:</p><pre>Initially:</pre><pre>Node A → Value X<br>Node B → Value X</pre><p>An update occurs:</p><pre>Node A → Value Y<br>Node B → Value X</pre><p>After replication:</p><pre>Node A → Value Y<br>Node B → Value Y</pre><p>This can allow the system to remain highly available while updates propagate through the cluster. Whether eventual consistency is appropriate depends entirely on the application’s requirements.</p><h3>Polyglot Persistence</h3><p>Using different databases for different requirements is called: Polyglot Persistence</p><p>For example:</p><pre>                  Application<br>                       │<br>        ┌──────────────┼──────────────┐<br>        ↓              ↓              ↓<br>     SQL DB         Redis          MongoDB<br>  Transactions       Cache         Documents</pre><p>Another application might use:</p><pre>SQL + Redis + HBase + Graph Database</pre><p>Each database is selected based on the workload it handles best.</p><p>This is a common architectural idea in modern distributed systems.</p><h3>NoSQL Does NOT Mean “SQL Is Dead”</h3><p>This is one of the biggest misconceptions. NoSQL did not replace relational databases.</p><p>Instead:</p><blockquote><strong><em>SQL and NoSQL solve different problems, and modern systems often use both.</em></strong></blockquote><p>For example:</p><p>=&gt; A payment system may use a relational database because transactions and consistency are critical.</p><p>=&gt; A caching layer may use Redis.</p><p>=&gt; A product catalogue may use MongoDB.</p><p>=&gt; A large distributed dataset may use HBase.</p><p>So the better question is not: <em>“SQL or NoSQL?”</em></p><p>It is: <strong><em>“Which database model best fits this particular workload?”</em></strong></p><h3>Advantages of NoSQL Databases</h3><h4>1. Horizontal scalability</h4><p>Many NoSQL systems are designed to scale by adding machines.</p><h4>2. Flexible data models</h4><p>Document and other NoSQL models can handle changing or semi-structured data naturally.</p><h4>3. High throughput</h4><p>Some NoSQL systems are designed to handle very high read/write workloads.</p><h4>4. Distributed architecture</h4><p>Many NoSQL databases are designed to operate across clusters.</p><h4>5. Fault tolerance</h4><p>Replication and distributed architectures can provide resilience against node failures.</p><h4>6. Specialised data models</h4><p>Instead of forcing every problem into tables, NoSQL provides models suited to specific workloads.</p><h3>Limitations of NoSQL</h3><p>NoSQL isn’t automatically better. It also introduces trade-offs.</p><h4>1. Weaker relational capabilities</h4><p>Many NoSQL databases don’t provide the same relational features as traditional SQL databases.</p><h4>2. Transactions vary</h4><p>Transaction support differs significantly between NoSQL systems.</p><h4>3. Querying can be less standardised</h4><p>There is no universal NoSQL query language equivalent to SQL across all NoSQL databases.</p><h4>4. Data duplication</h4><p>Some NoSQL designs intentionally duplicate data to make reads faster. This can make updates more complicated.</p><h4>5. Application complexity</h4><p>Distributed systems can introduce challenges involving:</p><ul><li>Replication</li><li>Consistency</li><li>Sharding</li><li>Failure recovery</li><li>Conflict resolution</li></ul><h4>6. Not ideal for every workload</h4><p>For highly relational transactional applications, a relational database may still be the better choice.</p><h3>Key Takeaways</h3><p>If you remember only a few things from this article, remember these:</p><p><strong>1. NoSQL generally means “Not Only SQL” and represents a family of non-relational database approaches.</strong></p><p><strong>2. NoSQL became popular as applications began handling massive, distributed, high-throughput, and flexible data workloads.</strong></p><p><strong>3. The four commonly discussed NoSQL categories are Key-Value, Document, Column-Family, and Graph databases.</strong></p><p><strong>4. Key-Value databases are useful for fast key-based access.</strong></p><p><strong>5. Document databases store flexible JSON-like documents.</strong></p><p><strong>6. Column-family databases are designed for large-scale distributed datasets and include systems such as HBase.</strong></p><p><strong>7. Graph databases focus on relationships between entities.</strong></p><p><strong>8. NoSQL systems often emphasise horizontal scalability, but not every NoSQL database works in exactly the same way.</strong></p><p><strong>9. Sharding distributes data across machines, while replication maintains additional copies for availability and fault tolerance.</strong></p><p><strong>10. NoSQL does not mean relational databases are obsolete.</strong></p><p><strong>11. Different workloads may require different database models.</strong></p><p><strong>12. Using multiple database technologies for different requirements is called polyglot persistence.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6xifaYXfLahRmAEgHY3KQ.png" /><figcaption>No SQL Summary</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11516addf8ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>