<?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 TechWithAdil on Medium]]></title>
        <description><![CDATA[Stories by TechWithAdil on Medium]]></description>
        <link>https://medium.com/@techwithadil?source=rss-91710ce06fb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QZiPsBFKrqvmqGQtXBLsMQ.jpeg</url>
            <title>Stories by TechWithAdil on Medium</title>
            <link>https://medium.com/@techwithadil?source=rss-91710ce06fb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:37:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@techwithadil/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[Circuit breakers in microservices]]></title>
            <link>https://medium.com/@techwithadil/circuit-breakers-in-microservices-17ef0b4d8d98?source=rss-91710ce06fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/17ef0b4d8d98</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[circuit-breaker-pattern]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[TechWithAdil]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 06:41:24 GMT</pubDate>
            <atom:updated>2023-03-06T06:41:24.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*_5GO9-s3m-PKShbky1ZF0w.png" /><figcaption>Circuit breaker</figcaption></figure><h3>Introduction:</h3><p>Most organizations today prefer to adopt microservices architectural pattern for their software development. This pattern comprises of a set of small, independent and well defined services that talk to each other over well defined set of APIs.</p><p>When multiple services collaborate to serve requests on a distributed network, failure is inevitable. Failures can occur when we have to connect to databases, APIs or remote services. No matter how well a cloud native microservices architecture is defined, it is bound to fail at some point making resiliency a critical feature to keep in mind.</p><h3>Transient and Non-Transient Errors</h3><p>Transient errors are temporary in nature. Since they are typically fixed automatically after the connection is retried, they don’t tend to require any application-level changes. These self-correcting faults include database connectivity, network issues, and temporary unavailability of services. Link issues, dead services, network routes not accessible for a few seconds or milliseconds, the website experiencing a heavy load and sending sporadic 503 HTTP service inaccessible messages, or the database you’re trying to reach being transferred to a different server and therefore unavailable for a few seconds are all examples of this form of error</p><p>Non-Transient errors continue to occur until their root causes are addressed. If they do not get fixed after multiple attempts, application code changes are necessary.</p><p>Transient errors can cause performance degradation in the entire application during synchronous execution because of the cascading of timeouts or failures causing poor user experience. When complex applications use microservices, an outage in one microservice can lead to application failure. This post shows how to use the circuit breaker design pattern to help with a graceful service degradation</p><h3>Circuit breakers to the rescue</h3><p>This pattern was popularized by <strong>Michael Nygard</strong> in his book “<strong><em>Release it</em></strong>”. This design pattern restricts the caller service to call the destination service based on previously caused repeated timeouts or failures. It also detects when the destination service is functional and ready to accept requests again.</p><p>The circuit breaker pattern can improve the stability and resiliency of the system. For transient errors we can use a circuit breaker to safeguard underlying services which might be experiencing performance issues or failures. The idea here is to fail fast and not consume system resources waiting for the degraded service to respond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*-vz58BGxJ0-VTSCLvQcpLQ.png" /><figcaption>Circuit breaker at work</figcaption></figure><h3>Circuit Breaker Implementation:</h3><p>Circuit breakers are implemented with three states:</p><ol><li><strong>CLOSED</strong>: This is the state the circuit breaker has to be in and it implies that the circuit is working perfectly fine. It allows the different services to communicate as expected and also monitors the failures occurring within the defined time period. If this failure count goes beyond the specified threshold, the circuit will break and the state transfers to <strong>OPEN</strong>.</li><li><strong>OPEN</strong>: Once this state is reached, the circuit breaker stops all communications to the callee service and the caller service gets a default message from the circuit breaker. This allows us to stop the callee service from getting bombarded with requests and thereby allowing it time to gracefully startup again saving lot of CPU resources. The circuit breaker remains in the OPEN state until the timeout period ends and moves to a <strong>HALF_OPEN</strong> state once this timeout is reached.</li><li><strong>HALF_OPEN</strong>: In the half open state, the circuit breaker will allow a limited number of requests to pass through. If those requests are successful, it switches back to CLOSED state and resumes normal operation. If those requests also fail, it moves back to OPEN state again and starts the timeout again.</li></ol><p><strong><em>You can check for the basic count-based and time based implementation of the circuit breaker on my github </em></strong><a href="https://github.com/aedelkhanday/circuit-breaker"><strong><em>here</em></strong></a></p><h4><strong>Advantages:</strong></h4><ul><li>Helps reduce resources tied up in operations which are likely to fail.</li><li>Avoids waiting on timeouts for the client and an OPEN state avoids putting unnecessary load on server .</li><li>Can be used for monitoring and any change in state can be logged with details. These details can be super helpful to get a more insightful monitoring.</li></ul><h4><strong>Disadvantages:</strong></h4><ul><li>Difficult to test. A lot is required than a simple close down access to a service. It needs to handle a variety of failure responses and these responses need to be thoroughly tested.</li><li>Circuit breakers are a difficult to do as a one-off. They require an infrastructure management technology such as a service mesh that can manage the switching.</li></ul><h4><strong>Conclusion:</strong></h4><p>The circuit breaker pattern is an important aspect of microservices architecture these days. Its advantages far outweigh the few cons that is has. It allows the developers to prevent cascading failures due to network issues and improves the overall resiliency of the system as well as availability. Using the Circuit Breaker pattern in conjunction with a system management technology such as a service mesh allows software architects to take a global approach to creating fail-safe systems.</p><p><strong>For my previous articles click </strong><a href="https://medium.com/@techwithadil"><strong>here</strong></a></p><h4>References:</h4><ol><li><a href="https://medium.com/nerd-for-tech/design-patterns-for-microservices-circuit-breaker-pattern-ba402a45aac2">https://medium.com/nerd-for-tech/design-patterns-for-microservices-circuit-breaker-pattern-ba402a45aac2</a></li><li><a href="https://www.youtube.com/watch?v=5_Bt_OEg0no">https://www.youtube.com/watch?v=5_Bt_OEg0no</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17ef0b4d8d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Address Translation(NAT)]]></title>
            <link>https://medium.com/@techwithadil/network-address-translation-nat-93d4f42a8984?source=rss-91710ce06fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/93d4f42a8984</guid>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[TechWithAdil]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 13:10:37 GMT</pubDate>
            <atom:updated>2023-02-03T13:10:37.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*IgV0IbwpsDZsfxDYu4mSFQ.png" /></figure><h3>Introduction</h3><p>We all know that IPv4 has a finite number of IP addresses. It uses a 32 bit address space and provides <strong>4,294,967,296</strong>(²³²) unique addresses. With the widespread usage of the internet and the large number of connected devices in most homes(<em>mobiles, laptops, TVs, refrigerators, smartwatches etc</em>.), this number doesn’t look that big at all. Also a major chunk of the IP addresses are exempted and used for testing, broadcasting and certain military purposes. Out of the 4.2 billion, roughly only 3 billion IP addresses are available for public use. So in order to provide a unique IP address to each device, this number would be exhausted quickly. To overcome this, NAT was introduced as a mechanism to provide a single IP address to a set of devices in a private network.</p><h3>What is Network Address Translation (NAT)?</h3><p>Network Address Translation(NAT) allows a group of computers in a private network to share a single IP address to connect to the internet. For example, In a home setting with multiple computers, a NAT device acts as an interface between the computers and the internet and maps a single public IP to all the computers so that they can connect to the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*_rr5VUhPK84UEfqlABadeg.png" /><figcaption>Fig 1: Network Address Translation(NAT)</figcaption></figure><p>In most of the home networks, if you are connected to the same network on multiple devices and you do a simple google search (<em>whats my ip)</em> on all devices, it will return the same IP address on all connected devices. In some cases it may provide a different IP address to each device even though they are connected to same network. This is something for you to figure out 💁.</p><h4><strong>NAT in action</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*4UMYeR8IR3zpS88t-0fucg.png" /><figcaption>Fig 2: NAT in action</figcaption></figure><p>TThe NAT enabled router does not look like a router to the outside world. It is a device with a single IP address that has the capability to access the internet. All traffic leaving the home network has the IP address as <strong><em>145.12.121.11</em></strong> and all the incoming traffic to the network must have a destination address as <strong><em>145.12.121.11</em></strong>.</p><p>In essence, the NAT-enabled router is hiding the details of the home network from the outside world. (<em>As a sidenote, you might wonder where the home network computers get their addresses and where the router gets its single IP address. Often, the answer is the same — </em><strong><em>DHCP</em></strong><em>! The router gets its address from the ISP’s DHCP server, and the router runs a DHCP server to provide addresses to computers within the NAT-DHCP-router- controlled home network’s address space.</em>)</p><p>In the figure (<em>Fig 2</em>) above, one of the computers in a home network is trying to connect to <a href="http://example.com/"><em>example.com</em></a> over the internet. In the first step the private IP and port of the machine is encoded in the packet header along with the destination ip address and port number(<strong><em>of </em></strong><a href="http://example.com/"><strong><em>example.com</em></strong></a>). It is shown as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*qwGb2jMhK0RsZ2xYZ-JXjQ.png" /></figure><p>Once this information reaches to the NAT device it generates a new port number(<em>lets say</em> <strong><em>6766</em></strong>) for this data packet and replaces the private ip address with its own public ip address(<strong><em>145.12.121.11</em></strong>) and the port number with the newly generated port number. When generating a new source port number, the NAT router can select any source port number that is not currently in the NAT translation table. (Note that because a port number field is 16 bits long, the NAT protocol can support over 60,000 simultaneous connections with a single WAN-side IP address for the router!) NAT in the router also adds an entry to its NAT translation table(<strong><em>Step 2 in fig 2</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*qaMj50jXhogYXcBJI744oA.png" /></figure><p>The Web server, blissfully unaware that the arriving datagram containing the HTTP request has been manipulated by the NAT router, responds with a datagram whose destination address is the IP address of the NAT router, and whose destination port number is the port number of the router(<strong><em>6766</em></strong>). The source IP is the IP address of the server(<strong><em>example.com</em></strong>) and the server port(443).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*6HLoGoL1pEkQ4MN8ddZyzw.png" /></figure><p>When this datagram arrives at the NAT router, the router indexes the NAT translation table using the destination IP address and destination port number to obtain the appropriate IP address (192.168.0.1) and destination port number (3390) for the browser in the home network. The router then rewrites the datagram’s destination address and destination port number, and forwards the datagram into the home network to the correct device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*PlOufK-d7V8byb0XGPyXog.png" /></figure><h3>Disadvantages of NAT</h3><ul><li>Network address translation is a technology that consumes memory resources and processor space, because it must translate IPv4 addresses for all outgoing and incoming IPv4 datagrams and retain the details from translation in memory.</li><li>Some applications and technologies will not function as expected with NAT enabled.</li><li>Network address translation complicates protocols for tunneling. IPsec is the secure protocol recommended for network address translation.</li><li>A router is a device for the network layer, yet as a NAT device, it is required to tamper with the transport layer in the form of port numbers.</li></ul><h3>Conclusion</h3><p>NAT is a very important aspect of firewall security. It conserves the number of public addresses used within an organization, and it allows for stricter control of access to resources on both sides of the firewall.</p><p>There are many types of NAT and given the scope of this article, I am restricting it to just understanding the concept. I will discuss the types in detail in future articles.</p><p><strong>Check my other articles </strong><a href="https://medium.com/@techwithadil"><strong>here</strong></a>!</p><h4>References</h4><ol><li>Article on NAT by AviNetworks <a href="https://avinetworks.com/glossary/network-address-translation/#:~:text=In%20this%20way%2C%20network%20address,both%20security%20and%20economic%20goals.">here</a>!</li><li><a href="https://whatismyipaddress.com/nat">https://whatismyipaddress.com/nat</a></li><li><a href="https://www.youtube.com/watch?v=RG97rvw1eUo">https://www.youtube.com/watch?v=RG97rvw1eUo</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d4f42a8984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consistent hashing explained]]></title>
            <link>https://medium.com/@techwithadil/consistent-hashing-explained-5fe0676b7ff6?source=rss-91710ce06fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe0676b7ff6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[hashing-algorithm]]></category>
            <dc:creator><![CDATA[TechWithAdil]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 06:34:28 GMT</pubDate>
            <atom:updated>2023-01-24T06:34:28.366Z</atom:updated>
            <content:encoded><![CDATA[<p>I developed a deep interest in this topic while reading about distributed caching strategies on the web. It’s fascinating to know how data gets assigned in this distributed cache setup and most importantly what happens when the cache servers are added or removed. The need for consistent caching arose from limitations experienced while running collections of these caching machines.</p><p>Before we get into the details about consistent hashing, it’s important to give a brief idea about hashing and what it means in a distributed setup.</p><h4><strong>What is Hashing?</strong></h4><p>Hashing in simple terms is a process of converting a given key into another value. A hash function is used to generate the new value according to a mathematical algorithm also known as a <strong><em>hash function</em></strong>.</p><pre>A -&gt; f(A) -&gt; B</pre><p>Hashing simply takes our input <strong>(A)</strong> and applies a function <strong>f(A)</strong> and outputs a <em>hash key</em> or simply a <strong>hash</strong> <strong>B.</strong></p><h4><strong>Hash Tables:</strong></h4><p>To understand hash tables let’s take an example. Let’s assume we have a set of user information and the structure of data is similar to the one given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnEeWmoazpox2MGa1A3W3g.png" /><figcaption><em>Fig 1: Data objects inside an array</em></figcaption></figure><p>In order to search in this data structure(<em>array of objects</em>), we need to iterate through it until we find a desired element. It gives the best performance when the element to be searched is at index 0 O(1) and the worst case is when the element is present at the last position O(n) and we have to traverse the entire list. This logic works well for smaller data sizes but as soon as the data grows, the performance takes a hit and it becomes a very bad choice for searching.</p><p>How do we fix this? Let’s suppose all the members had an id which happened to be a sequential number reflecting the order in which they were added to the list. If we start searching using the ids and if each id corresponds to an equivalent array index, searching becomes extremely efficient as for any given id, we can always directly access it(for example a member with ID = 3 will be at index 3 in this list.). Now we are able to access the items in the list in O(1) or <em>constant time.</em></p><p>Obviously the above example is somewhat contrived and in the real world we need to search by more meaningful keywords like names or emails or maybe an entirely different field. In such cases it is certainly a better approach to have a mechanism in place where the access is almost direct while at the same time being able to handle large datasets. This is where <em>hash functions</em> come to our rescue. A good hash function will be used to map an arbitrary piece of data to an integer. Let’s assume that we have to search by name in our above example. To create a simple hash function we can take the ASCII code of the individual characters of the name and sum them up and perform a modulo operation on the sum with the size of the array.</p><p>We can get the index for the names as below:</p><pre>ada = a(97) + d(100) + a(97) = 294  % 6 = 0 <br>kin = j(107) + i(108) + m(110) = 325 % 6 = 1<br>max= m(109) + a(97) + x(120) = 326 % 6 = 2<br>polmy = p(112) + o(111) + l(108)+ m(109) + y(121) = 560 % 6 = 3<br>tam = s(116) + a(97) + m(109) = 322 % 6 = 4<br>sum = s(115) + u(117) + m(109) = 341 % 6 = 5</pre><p>The data now looks like below after the hash function is applied on each element during insertion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyRH9qT_cH_G5swK-Uw-aA.png" /><figcaption>Fig 2: Data objects after applying the hash modulo operation</figcaption></figure><p>During insertion we don’t have to linearly add the elements. Instead each entry will need to go via the <strong><em>hash modulo N</em></strong> operation where N is the size of the array. To search for the element we do the same. We first perform the <strong><em>hash modulo N</em></strong> operation and then directly go to the index to find the element at the index. This structure is called the hash table. Although this strategy also works well, it has some limitations. Sometimes multiple keys can get mapped to the same index, a phenomenon known as <strong>collision</strong>. There are multiple ways of handling collisions like <strong><em>open addressing</em></strong> or <strong><em>chaining</em></strong> (<em>closed addressing</em>). Read more about the collision resolution techniques <a href="https://runestone.academy/ns/books/published/pythonds/SortSearch/Hashing.html#collision-resolution">here</a></p><h4><strong>Distributed Hashing:</strong></h4><p>Companies rely a lot on caching strategies to optimise on performance and provide near real time responses on the web. Most of the times multiple caching servers are required to handle such traffic as the load gets distributed among different servers thereby reducing the load on an individual machine. In this scenario the data gets distributed among these different servers. Hence the name “<strong><em>distributed</em></strong>”.</p><p>One such implementation of this is that of in-memory caches such as <strong><em>memcached</em></strong> or a highly performant <em>NoSql database</em> from <strong><em>Amazon</em></strong> popularly known as <strong><em>Dynamo DB</em></strong>.</p><p>Let’s take an example again. Suppose we have three cache servers A, B and C that can store our objects. Such a setup is necessary as mentioned earlier to improve performance as the data is first designed to be fetched from these cache servers and if its not present on the cache(<em>cache miss</em>), a call to the DB is made to fetch the data and store it on the cache server with an appropriate key so that it can be found the next time it is needed. The simplest way to do this is to use the technique as mentioned above. Take the hash modulo of the number of servers.</p><pre>server = hash modulo N</pre><p>Here N is the number of cache servers in the pool. To store or retrieve a key, the client first computes the hash, applies a modulo Noperation, and uses the resulting index to contact the appropriate server (probably by using a lookup table of IP addresses). Note that the hash function used for key distribution must be the same one across all clients, but it need not be the same one used internally by the caching servers.</p><p>Let us try to map the above data to the three servers A, B and C. We can represent the relationship using the below table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3xZ-w6UUY-3xzxuITQjwQ.png" /></figure><p>This distribution works fine as long as the server size is fixed and no new addition/deletion of servers happen. The problem arises when one of the servers become unavailable or a new server is added to the pool. In both the cases it gives rise to the problem of <strong><em>Rehashing</em></strong>. In such scenarios we need to redistribute the keys in order to account for the new change in the size of the servers. From the previous example if we removed the server C, we have to rehash all the keys using hash modulo 2 instead of hash modulo 3 and the table will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mhwtrBhlFoB5j2SUV8Yug.png" /></figure><p>We need to understand here that we had to rehash all the keys and not just the keys from server C. This would mean that all of a sudden most of the keys won’t be found because they won’t be present at their new location and majority of the queries will result in cache miss and the original data will likely need to be re-fetched again putting a lot of load on the caching servers and at the same time may result in duplication on multiple servers.This will eventually degrade the performance of the servers and may possibly cause the origin servers to crash.</p><h3><strong>Consistent hashing to the rescue</strong>:</h3><p>How do we solve the problem of rehashing when the number of servers get added or removed from the caching cluster? We need a distribution scheme that is independent of the number of servers so that any time there is a change in the servers, the rehashing is minimized. One such clever and surprisingly powerful scheme was first described by <a href="https://www.cs.princeton.edu/courses/archive/fall09/cos518/papers/chash.pdf">Karger et al</a> at MIT.</p><p>Consistent Hashing is a distributed hashing scheme that operates independently of the number of servers or objects in a distributed hash table by assigning them a position on an abstract circle, or hash ring. This allows servers and objects to scale without affecting the overall system.</p><p>In other words we can map the objects(data) as well as the servers on an imaginary abstract circle also known as <strong><em>hash ring.</em></strong> This also means that every data point or a server is just an angle on this circle. If we try to map our hash output range on this circle the minimum hash value will correspond to angle of 0 on this circle and the maximum possible value would be 360 and all the other values will linearly fit somewhere in between. In order to get a position for any key on this circle, we need to calculate the hash and find out where it lies on the circle. Let us try to see our data on this imaginary circle. (<strong><em>The angles are calculated as hash modulo 360</em></strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*5aeW-n5YTk4Dmyac9YnJUQ.png" /></figure><p>Now, let us also place the servers on the edge of this circle by randomly assigning them angles too. We can use the server ids to generate the hash. Let’s assume the servers generate the hash and angles as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sdJKbWHP_uEgKKYOiFD2qw.png" /></figure><p>This will look like this on our circle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*Xr-Z7XzOkpqk3fTtKkIauA.png" /></figure><p>Since we have established a convention to define a position for the servers and the data objects on the circle, how do we assign the object to the server. The simple rule here is to assign the object to the closest server in the clockwise or counter clockwise direction(<em>Depending on the algorithm convention</em>). So to locate a server for a given key, we need to move in either ascending or descending direction to find the closest server. It can be represented as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*oZU2Oa60ul5b3I5s5DfwXg.png" /></figure><p>This approach solves the problem of rehashing for us. Let’s say server B is removed. To account for this only the keys that belonged to B need to be rehashed to a new server(<em>in this case server C since that’s the closest</em>). The keys that were hashed to A and C remain the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*w_9TuqaQ8XYSdF58K6K_Zg.png" /></figure><p>Similarly we can add new servers to this setup without rehashing the entire keys as shown below. That’s the beauty of this technique. So adding or removing the servers results in assigning the keys to the servers in an elegant way leaving all the other keys untouched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*K7gh-on90PeIn7J5t9U-tQ.png" /></figure><p>Theoretically this technique works well but it has a few drawbacks.</p><ol><li>The keys assignment in this setup may get skewed and it may happen that one server gets assigned a lot of keys and puts significant load on it.</li><li>If a server goes down, again it may put a lot of pressure on a server since this server now needs to accommodate its own keys and also the keys from the crashed server.</li></ol><p>To account for this drawback we can use a simple trick. The trick is to assign not one, but many labels(angles) to each server. So instead of A, B and C we could have A0...A9, B0...B9 and</p><p>C0...C9,all interspersed along the circle. The factor by which the number of labels are to be increased for each server(also known as weight) depends upon the situation. For example if server B is twice as powerful as A and C, we can assign twice the labels and as such it will end up holding twice the data than the rest on an average.</p><p>In our case for our understanding, let’s assume all three servers have an equal weight of 10, our ring will look something like given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*LI-gSk4EMMb8iOVHBJySaQ.png" /></figure><p>Using this trick we have tried to uniformly distribute all the servers on the ring which will lead to better distribution of load among the servers.</p><p>This is how consistent hashing solves the rehashing problem. In general only k/N keys need to be remapped. k is the number of keys and N is the number of servers.</p><h4><strong>Conclusion</strong>:</h4><p>We observed that when using distributed caching to optimize performance, it may happen that the number of caching servers changes (<em>reasons for this may be a server crashing, or the need to add or remove a server to increase or decrease overall capacity</em>).</p><p>By using consistent hashing to distribute keys between the servers, the number of keys to be rehashed is reduced substantially and therefore, the impact on origin servers is minimized preventing potential downtime or performance issues.</p><p>There are clients for several systems, such as <strong><em>Memcached, DynamoDB</em></strong> and <strong><em>Redis</em></strong>, that include support for consistent hashing out of the box.</p><p><strong>Check my other articles </strong><a href="https://medium.com/@techwithadil"><strong>here</strong></a>!</p><h4>References:</h4><ol><li><a href="https://en.wikipedia.org/wiki/Consistent_hashing">https://en.wikipedia.org/wiki/Consistent_hashing</a></li><li><a href="https://www.youtube.com/watch?v=UF9Iqmg94tk">https://www.youtube.com/watch?v=UF9Iqmg94tk</a></li><li>Research paper on consistent hashing by Karger Et al. <a href="https://www.cs.princeton.edu/courses/archive/fall09/cos518/papers/chash.pdf">here</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe0676b7ff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySql Replication masterclass — Part 3]]></title>
            <link>https://medium.com/@techwithadil/mysql-replication-masterclass-part-3-ee75a59ac372?source=rss-91710ce06fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee75a59ac372</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database-replication]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[TechWithAdil]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 07:00:33 GMT</pubDate>
            <atom:updated>2023-01-08T07:00:33.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>MySql Replication masterclass — Part 3</h3><h3><strong>Introduction</strong></h3><p>In the previous articles we understood a lot about database replication basics, its <em>synchronisation types</em> and different <em>replication formats</em>. We also learnt about the <strong><em>binlogs</em></strong> in detail. We also introduced the different replication types <strong><em>Binlog position based replication</em></strong> and <strong><em>GTID replication</em></strong>. In this article we will try to understand these types in detail. We have already set the base of all pre requisites in our previous articles (<a href="https://medium.com/@techwithadil/mysql-replication-masterclass-part-1-c5610c8997df"><strong>part1</strong></a><strong> and </strong><a href="https://medium.com/@techwithadil/mysql-replication-masterclass-part-2-6bf339ddaea1"><strong>part2</strong></a>).</p><h3><strong>Binlog position based replication:</strong></h3><p>Let us try to understand the binlog position based replication where the MySql server instance acting as the <strong>source</strong> or <strong>primary</strong> DB(<em>this is where the database changes take place</em>) writes the updates or changes as “events” to the binary log. All the replicas connected to this source receive these events and make appropriate changes on the replica DB based on these events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*uLy0RR1ZE8gTt78CaAGFZQ.png" /><figcaption><strong>Fig</strong>: Binlog position based Replication</figcaption></figure><p>Each replica has the information about the binary log coordinates; i.e, the <em>binlog filename</em> and the <em>position</em> within that file it has processed from the source. Its important to point here that the entire responsibility of maintaining the binlog coordinates is with the replicas and as such individual replicas can be connected and disconnected from the server without affecting the source’s operation.</p><h4><strong>Setting up Binlog Position Based Replication:</strong></h4><p>Let’s try to understand how to setup a MySql server to use binlog position based replication. There are different methods of setting up replication and the exact method to use depends on whether you already have data in the database on the source. We will setup replication for a database that already contains data and try to understand the steps involved.</p><p>The tasks to be followed are:</p><ul><li>Setting the Replication Source Configuration</li><li>Setting the Replica configuration</li><li>Creating a user for Replication</li><li>Obtaining the Source Binlog coordinates</li><li>Creating the data snapshot for the source</li><li>Setting the source configuration on the replica</li></ul><h4><strong>Setting the Replication Source Configuration</strong></h4><p>The first step towards this type of replication is to enable binary logging on the source. This can be done by either providing a value to <strong><em>log-bin</em></strong> variable during startup or by directly updating the MySql config file(<strong><em>my.cnf or my.ini</em></strong>).</p><p>Also each server with the replication topology must be configured with a unique non-zero <strong><em>server_id</em></strong>. This <strong><em>server_id</em></strong> is used to identify individual servers within the replication topology and must be a positive integer between 1 and (2³²)-1.</p><p>The default server_id is 1. It can be changed by issuing a statement like this:</p><pre>SET GLOBAL server_id = 5</pre><p>We also need to ensure that the <strong><em>skip_networking</em></strong> system variable is not enabled on the source as this controls the networking on the source. If this is enabled the replicas cannot communicate with the source and replication fails.</p><h4><strong>Setting the Replica Configuration</strong></h4><p>Each replica should be configured with a unique <strong><em>server_id</em></strong> that differs from that of the source and any other replicas. Note that a <strong><em>server_id</em></strong> value of 0(<em>default in earlier versions of MySql</em>) prevents a replica to connect to the source and must be updated with a new non-zero number for replication to work. Binary logging is not required to be enabled on the replicas. However it can prove to be beneficial for data backups and crash recovery. It can also be enabled for a more sophisticated replication topology where the replica can act as a source for another replica and thereby reduce connections on the source DB.</p><h4><strong>Creating a user for Replication</strong></h4><p>Each replica needs to connect to the source using credentials like username and password, so there must be some user account on the source that the replicas can use to connect. Any user account can be used provided it has been granted the <strong>REPLICATION_SLAVE</strong> privilege. We can create different accounts for each replica or use a common account for all the replicas.</p><p>Although it’s not mandatory to create a new account for replication specifically but its worth mentioning here that the replication username and password are stored in plain text in the replica’s connection metadata repository <strong><em>mysql.slave_master_info</em></strong>. Therefore it’s a better practice to always have a separate account that has privileges only for replication to minimize the possibility of compromise to other accounts.</p><p>We can create a new user as follows:</p><pre>mysql &gt; CREATE USER &#39;repl_user&#39;@&#39;host&#39; IDENTIFIED by &#39;password&#39;;<br>mysql &gt; GRANT REPLICATION SLAVE ON *.* TO &#39;repl_user&#39;@&#39;host&#39;;</pre><h4><strong>Obtaining the Source Binlog coordinates</strong></h4><p>For the replicas to start the replication, we need to get the correct coordinates(<em>for a fresh master DB its the start of the log file and for a DB with existing data its the position of the last update</em>) within the binlog. To obtain these coordinates below steps can be followed:</p><ul><li>Create a session on the source from the command line and execute the below command: This command first acquires the exclusive metadata locks for the tables and so it ensures that all transactions are complete. It then flushes the tables from the table cache and reopens them and acquires table locks. It also downgrades the metadata lock from exclusive to shared. After doing these changes other sessions can still read data but wont be able to modify the data.</li></ul><pre>mysql &gt; FLUSH TABLES WITH READ LOCK;</pre><ul><li>Leave the above session open and in a different session on the source use the below command to get the details about binlog coordinates</li></ul><pre>mysql &gt; SHOW MASTER STATUS;<br>+------------------+----------+--------------+------------------+<br>| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |<br>+------------------+----------+--------------+------------------+<br>| mysql-bin.000003 | 73       | test         | manual,mysql     |<br>+------------------+----------+--------------+------------------+</pre><p>Here the <strong><em>File</em></strong> column shows the name of the binlog file and the <strong><em>Position</em></strong> column shows the position within the file. We need to record these values as these will allow us to set up the replicas later. These values represent the replication coordinates at which the replica should begin processing new updates from the source.</p><h4><strong>Creating the data snapshot for the source</strong></h4><p>For our example we need to create replication for the source that already contains data. We need to synchronise this data with the replicas before we can start the replicas to start reading events from the source. There are multiple ways to dump the data from the source database. The possible options are:</p><ul><li>Using the <strong><em>mysqldump</em></strong> tool to create a dump of all the databases that are going to be a part of the replication process. This is the recommended method when using <strong><em>innodb</em></strong></li><li>If the database is stored in binary portable files, we can copy the raw data files to the replica. This method skips the overhead of updating indexes as INSERT statements are replayed. This is not recommended for <strong><em>innodb</em></strong> engines.</li><li>Using MySql server’s Clone plugin to transfer the data from an existing replica to a clone.</li></ul><p>Lets use the <strong><em>mysqldump</em></strong> utility to create a snapshot of the data below:</p><pre>$&gt; mysqldump --all-databases --master-data &gt; dbdump.sql</pre><p>The above statement dumps all databases to a file named <strong><em>dbdump.sql</em></strong>. The <strong><em>— master-data</em></strong> option automatically appends the REPLICATION SOURCE TO statement required on the replica to start the replication process.</p><h4><strong>Setting the source configuration on the replica</strong></h4><p>Since we are setting up replication with existing data, we need to transfer the snapshot created above from the source to replica before starting replication. Once the snapshot is copied we can import the dump file as below:</p><pre>$&gt; mysql &lt; dbdump.sql</pre><p>Let’s now configure the replica with the replication coordinates from the source. To do this we need to run the below command on the replica with the appropriate information as relevant to our source</p><pre>mysql&gt; CHANGE REPLICATION SOURCE TO<br>    -&gt;     SOURCE_HOST=&#39;source_host_name&#39;,<br>    -&gt;     SOURCE_USER=&#39;replication_user_name&#39;,<br>    -&gt;     SOURCE_PASSWORD=&#39;replication_password&#39;,<br>    -&gt;     SOURCE_LOG_FILE=&#39;recorded_log_file_name&#39;,<br>    -&gt;     SOURCE_LOG_POS=recorded_log_position;</pre><p>The CHANGE REPLICATION statement has other options as well. <a href="https://dev.mysql.com/doc/refman/8.0/en/change-replication-source-to.html">Details</a></p><p>This statement tells the replica DB which source to connect to and what user credentials to use. We also have to mention the log file name from where it needs to read events. The most important parameter is the SOURCE_LOG_POS which basically tells the replica to start reading from this position onwards. We got these details above when we ran <strong><em>SHOW MASTER STATUS</em></strong> command.</p><h4><strong>Start Replication and Check Status</strong></h4><p>Now that everything is configured, its time to start the replication on the replica via the below command</p><pre>mysql&gt; start replica;</pre><p>To determine whether the replication is running successfully we can run the below command:</p><pre>mysql&gt; show replica status;</pre><p>The output of the above command is as below:</p><pre>mysql&gt; show replica status\\G<br>*************************** 1. row ***************************<br>             Replica_IO_State: Waiting for master to send event<br>                  Source_Host: &lt;primary IP&gt;<br>                  Source_User: repl_user<br>                  Source_Port: &lt;primary port&gt;<br>                Connect_Retry: 60<br>              Source_Log_File: mysql-bin.000001<br>          Read_Source_Log_Pos: 852<br>               Relay_Log_File: mysql-relay-bin.000002<br>                Relay_Log_Pos: 1067<br>        Relay_Source_Log_File: mysql-bin.000001<br>           Replica_IO_Running: Yes<br>          Replica_SQL_Running: Yes<br>                 Skip_Counter: 0<br>          Exec_Source_Log_Pos: 852<br>              Relay_Log_Space: 1283<br>              Until_Condition: None<br>               Until_Log_File:<br>                Until_Log_Pos: 0<br>           Source_SSL_Allowed: No<br>        Seconds_Behind_Source: 0<br>Source_SSL_Verify_Server_Cert: No<br>  Replicate_Ignore_Server_Ids:<br>             Source_Server_Id: 1<br>                  Source_UUID: e17d0920-d00e-11eb-a3e6-000d3aa00f87<br>             Source_Info_File: mysql.slave_master_info<br>                    SQL_Delay: 0<br>          SQL_Remaining_Delay: NULL<br>    Replica_SQL_Running_State: Slave has read all relay log; waiting for more updates<br>           Source_Retry_Count: 86400<br>           Retrieved_Gtid_Set: e17d0920-d00e-11eb-a3e6-000d3aa00f87:1-3<br>            Executed_Gtid_Set: e17d0920-d00e-11eb-a3e6-000d3aa00f87:1-3<br>                Auto_Position: 1<br>        Get_Source_public_key: 0<br>            Network_Namespace:<br>1 row in set (0.00 sec)</pre><h3><strong>GTID Based Replication</strong></h3><p>This type of replication is a straight forward approach to replication and does not need us to track the binlog positions at all times. In this case the master database maintains the transactions in its log and these transactions are copied and replayed on the replicas and on successful commit, it guarantees consistency among the master and all the replica servers. Here also we can use <em>statement</em> or <em>row</em> based format; however for best results its better to use <em>row based format (</em><a href="https://medium.com/@techwithadil/mysql-replication-masterclass-part-2-6bf339ddaea1"><em>explained here</em></a><em>)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*aVgbOUwngPTsMvxnK5cA3Q.png" /><figcaption><strong>Fig</strong>: GTID based Replication</figcaption></figure><p>GTIDs are always preserved between the source and the replica and once a transaction with a given GTID is committed on a given server, any subsequent transaction with the same GTID is ignored by that server. This ensures that a transaction committed on a server cannot be applied multiple times which helps to guarantee consistency.</p><h4>What are GTIDs?</h4><p>A <strong><em>Global Transaction Identifier(GTID)</em></strong> is a unique identifier created and associated with each transaction committed on the server of origin(source DB). This id is unique not only on the source server on which it originated , but is unique across all servers in a given replication topology.</p><p>A GTID is represented as a pair of coordinates seperated by a colon(:) character as shown below:</p><pre>GTID = source_id: transaction_id</pre><p>The <strong><em>source_id</em></strong> identifies the originating server. The source’s <strong><em>server_uuid</em></strong> is used for this value. The <strong><em>transaction_id</em></strong> is a sequence number determined in order in which the transaction was committed on the source. For example, the first transaction to be committed on the server has 1 as its <strong><em>transaction_id</em></strong> and the tenth transaction to be committed on the same server is assigned a <strong><em>transaction_id</em></strong> of 10.</p><pre>3E11FA47-71CA-11E1-9E33-C80AA9429562:23</pre><p>The above example shows a <em>transaction_id</em> of 23 originating on the server with uuid <strong><em>3E11FA47–71CA-11E1–9E33-C80AA9429562</em></strong></p><p>The upper limit for sequence numbers for GTIDs on a server instance is the number of non-negative values for a signed 64-bit integer (2 to the power of 63 minus 1, or 9,223,372,036,854,775,807). In newer versions of MySql, a warning is issued when the server instance is approaching this limit.</p><h3><strong>Setting up GTID based Replication:</strong></h3><p>To setup replication using GTIDs some of the steps are similar to the binlog based replication as specified above. We will try to go through each step one by one:</p><ul><li>Primary Host Configurations</li><li>Replica host configurations</li><li>Creating a replication user</li><li>Configure the replica to use GTID based auto positioning</li><li>Starting Replication and check status</li></ul><h4><strong>Primary Host configurations:</strong></h4><p>The following config parameters should be present in the primary my.cnf file for setting up GTID based replication.</p><pre>server-id - a unique ID for the mysql server<br>log-bin - the binlog location<br>binlog-format - ROW | STATEMENT (we will use ROW)<br>gtid-mode - ON<br>enforce-gtid-consistency - ON</pre><p>Here the first three options are similar to what we enabled during binlog based replication as well.</p><p><strong><em>gtid-mode</em></strong>: Enables GTID based logging on the server.</p><p><strong><em>enforce-gtid-consistency</em></strong>: Depending on the value of this variable, the server enforces the GTID consistency by allowing execution of only statements that can be safely logged using a GTID. Setting this to ON means that no transaction is allowed to violate GTID consistency.</p><h4><strong>Replica Host Configurations</strong></h4><p>The following config parameters should be present in the replica my.cnf file for setting up replication.</p><pre>server-id - different than the primary host<br>log-bin - (optional, if you want replica to log its own changes as well)<br>binlog-format - depends on the above<br>gtid-mode - ON<br>enforce-gtid-consistency - ON<br>log-slave-updates - ON</pre><p>Here we have added an extra param <strong><em>log-slave-updates</em></strong>. Its an optional param that can be enabled only if we enable <strong><em>log_bin</em></strong> on the replica server. It allows the replica server to log the changes coming from the primary along with its own changes. It also allows us in setting up <strong><em>chain replication.</em></strong></p><h4><strong>Creating a replication user</strong></h4><p>Since the replicas need a user to connect to the primary DB this step is exactly similar to what we did above. We need to create a replica user with only the <em>replication slave</em> privileges.</p><h4><strong>Configure the replica to use GTID based auto positioning</strong></h4><p>The replication setup must know about the primary host, the user and password to connect, the GTID auto-position parameter. The following command is used for setting up</p><pre>CHANGE REPLICATION SOURCE TO<br>  SOURCE_HOST = host,<br>  SOURCE_PORT = port,<br>  SOURCE_USER = user,<br>  SOURCE_PASSWORD = password,<br>  SOURCE_AUTO_POSITION = 1;</pre><p>The <strong>SOURCE_AUTO_POSITION</strong> tells the replica that the source’s transactions are identified by GTIDs. In the binlog based replication above we used <strong>SOURCE_LOG_FILE</strong> and <strong>SOURCE_LOG_POS</strong> as its dependent on the log file name and the position within that file.</p><h4><strong>Starting Replication and check status</strong></h4><p>Now that everything is configured, we just need to start the replication on the replica via the following command:</p><pre>start replica;</pre><p>Again, if we want to test if the replication is running successfully, we can determine that by issuing the below command:</p><pre>show replica status;</pre><h3>Conclusion</h3><p>There are a lot of intricate optimizations that MySql takes care of internally and it handles a lot of concurrent operations by running specialized threads on both the source and replica DBs. We may cover these also in future.</p><p>This completes our three part series of MySql database replication masterclass. I would highly appreciate your feedback.</p><h4>References:</h4><ol><li><a href="https://dev.mysql.com/doc/refman/5.7/en/replication-configuration.html">https://dev.mysql.com/doc/refman/5.7/en/replication-configuration.html</a></li><li><a href="https://www.redhat.com/sysadmin/gtid-replication-mysql-servers">https://www.redhat.com/sysadmin/gtid-replication-mysql-servers</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee75a59ac372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySql Replication masterclass — Part 2]]></title>
            <link>https://medium.com/@techwithadil/mysql-replication-masterclass-part-2-6bf339ddaea1?source=rss-91710ce06fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf339ddaea1</guid>
            <category><![CDATA[dbms-and-rdbms]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-replication]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[TechWithAdil]]></dc:creator>
            <pubDate>Sat, 31 Dec 2022 05:48:49 GMT</pubDate>
            <atom:updated>2023-01-08T07:07:42.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>MySql Replication masterclass — Part 2</h3><h3><strong>Introduction</strong></h3><p>In the previous article we spoke about the concept of replication and introduced its <em>types</em>, <em>synchronization variations</em> and also talked about its <em>advantages</em> and <em>drawbacks</em>. In this article we will try to learn more about the specifics of <strong><em>Binlogs</em></strong><em> in MySQL</em> and how logs are structured and stored. In the upcoming articles we will try to get into the details of how exactly the replication is done both in <strong>Binlog</strong> format as well as <strong>GTIDs</strong>.</p><p>Before we move ahead, we need to understand more about the <strong><em>binlogs</em></strong> and very importantly introduce the concept of <strong><em>replication formats.</em></strong></p><p><strong><em>Binlogs</em></strong> as described in the previous article as well are basically log files that contain database events that describe database changes such as table creations or any changes or updates to the data. Binlogs also contain events for the statements that could have potentially made changes(<em>eg, a DELETE that matched no rows</em>). The Binary logs are not used to log all the statements like SELECT or SHOW. To do so we can use the <strong><em>General Query Log</em></strong>. Performance takes a slight hit when Binary logging is enabled but the benefits in <em>replication</em> and <em>data recovery</em> outweighs this slight performance decrement. Binary logging is enabled by default (<em>log_bin system variable is set to ON</em>). If for some reason it’s disabled you can enable it in the configuration file and restart the server. You can check this variable as below:</p><pre>show global variables like &quot;log_bin&quot;;</pre><h3><strong>Replication Formats</strong></h3><p>The Replication works because the events written in the source DB’s binary log are read from the source by the replicas and processed on the replica. These events are recorded in different formats according to the type of the event. With respect to MySql replication, the binary log format can be of three types that decides the main type of replication:</p><ul><li>Statement Based Replication (SBR)</li><li>Row Based Replication (RBR)</li><li>Mixed Replication</li></ul><p>You can check the replication format on MySql as below:</p><pre>show global variables like &quot;binlog_format&quot;;<br>+---------------+-------+<br>| Variable_name | Value |<br>+---------------+-------+<br>| binlog_format | ROW   |<br>+---------------+-------+</pre><p>You can also set the binlog format at runtime, although setting the logging format does not set the binary logging on the server. The setting only takes effect when the binary logging is enabled on the server(<strong><em>log_bin is set to ON</em></strong>).</p><pre>SET GLOBAL binlog_format = ‘STATEMENT’; // For all clients that connect subsequent to the change*<br>SET SESSION binlog_format = ‘STATEMENT’; // *For an individual client*</pre><h4><strong>Statement Based Replication(SBR)</strong></h4><p>This was the default logging format in older versions of MySql(<em>≤5.1.4</em>). When using SBR logging, the source writes the exact SQL statements to the binary log as executed by the source. Replication of the source to the replica works by sending the same statements to the replicas and executing these SQL statements on the replica. For example consider the below two DML statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kW97D7WMFVC_zVgvtAdJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4bxpoenNWp9q8f1D4A_WA.png" /></figure><p>For these queries, the SBR logs the statements as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mr0mkHlFrhoSo9M4d5QKOg.png" /></figure><h4><strong>Row Based Replication</strong></h4><p>This is now the default method in newer versions of MySql. When using Row Based Replication logging(RBR), the source writes events to the binlog that indicate how individual table rows are changed. The replication works by copying these events representing the changes to the table rows to the replica. Lets see an example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*09EM6ZJDmde_4SPyQDT0_g.png" /></figure><p>The binlog records these changes as given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vINDXFuCz8EOrCEdCbKdTA.png" /></figure><p>We can see here the RBR has created three individual statements for one update statement along with the values for the rows. This always ensures that data remains consistent between source and the replicas.</p><p>Let’s take a look at the operational differences between SBR and RBR:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdfGYhdC1K2AYbmMix23Rw.png" /></figure><h4><strong>Mixed Replication Format</strong></h4><p>We can configure MySQL to use a mix of SBR and RBR. This is called Mixed-format logging. When using Mixed format logging, SBR is used by default. Depending on certain circumstances and also the storage engine being used the log is automatically switched to Row based logging in particular cases. When running MIXED logging format, the server automatically switches from Statement-based to Row-based logging under the following few conditions:</p><ul><li>When a function contains UUID()</li><li>When a call to a loadable function is involved</li><li>When the LOAD_FILE() function is used</li><li>When a statement refers to one or more system variables.</li></ul><h3><strong>Conclusion</strong></h3><p>As we have already gathered, all three types of logging have their unique characteristics, advantages and disadvantages. Many users still prefer statement based replication for their use cases. However, the Mixed replication format should be sufficient when it comes to performance and data integrity.</p><p><strong>Check out the part 1 by clicking </strong><a href="https://medium.com/@techwithadil/mysql-replication-masterclass-part-1-c5610c8997df"><strong>Here</strong></a><strong>!</strong></p><p><strong>Next Part </strong><a href="https://medium.com/@techwithadil/mysql-replication-masterclass-part-3-ee75a59ac372"><strong>here</strong></a>!</p><h4>References:</h4><ol><li><a href="https://dev.mysql.com/doc/refman/8.0/en/binary-log-formats.html">https://dev.mysql.com/doc/refman/8.0/en/binary-log-formats.html</a></li><li><a href="https://linkedin.github.io/school-of-sre/level101/databases_sql/replication/">https://linkedin.github.io/school-of-sre/level101/databases_sql/replication/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf339ddaea1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySql Replication masterclass — Part 1]]></title>
            <link>https://medium.com/@techwithadil/mysql-replication-masterclass-part-1-c5610c8997df?source=rss-91710ce06fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5610c8997df</guid>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-replication]]></category>
            <dc:creator><![CDATA[TechWithAdil]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 06:51:21 GMT</pubDate>
            <atom:updated>2022-12-31T06:06:12.421Z</atom:updated>
            <content:encoded><![CDATA[<h3>MySql Replication masterclass — Part 1</h3><h3>Introduction</h3><p>In today’s world as they say “<em>Data is the new oil</em>” and websites around the world generate humongous amounts of data every minute and this data needs to be stored and retrieved efficiently. Presently the databases are doing a great job in allowing us to manage our data efficiently but anytime anything can go wrong because of network outages, server crashes and what not. This is in accordance with Murphy’s<strong> law</strong> where he states “<em>Anything that can go wrong will go wrong</em>”. We as engineers need to ensure that our data is always safe and available to our users.</p><p>At some point every company starts realizing the amount of data they have accumulated over time and the amount of pressure the database has to undergo when it comes to query performance and scalability. Taking regular database dumps is a way to safeguard data but not the optimal one since it’s very time consuming. This is where database replication comes into play.</p><p>Replication is a vast and one of the very important topics when it comes to Database Engineering. It allows us to have multiple copies of the same data in different servers in different geographies. It sounds very simple but a lot goes behind the scenes to make it possible. Let’s take a deep dive into it using Mysql as the database management technology and try to understand what replication is and what are its different flavors and formats provided by MySql.</p><h3>So what exactly is Replication?</h3><p>In simple terms, Replication enables data from one MySql database(<strong>also called Master/source/Primary DB</strong>) to be copied to one or more MySql databases(<strong>also known as replicas/slave DBs</strong>). Replication is asynchronous by default and the replica servers do not need a permanent connection to the primary DB. We can replicate all databases, selected databases or selected tables within the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/0*BFWNpuuIKp6t_O-n" /></figure><p><strong><em>Fig: Database replication</em></strong></p><h3>What makes Replication so important?</h3><ol><li><strong>Adding read replicas to scale reads</strong> — We can add any number of read replicas to the primary DB and scale read requests. In this type of setup the write and read requests are segregated. The write requests are sent only to the primary DB and the read requests are distributed between the replicas. This also increases write performance as the primary DB is only handling writes and doesn’t care about any read connections.</li><li><strong>Analytics</strong> — We can configure a read replica to perform analytics without affecting the performance on the primary DB. This setup allows us to have a dedicated database server to perform just analytical queries.</li><li><strong>Disaster Recovery</strong> — A replica in some other geographical region paves a proper path to configure disaster recovery.</li></ol><h3>Replication Synchronization Types:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*d1bGCiItQI_7D7BF" /></figure><p><strong><em>Fig: Replication Synchronization types</em></strong></p><p><strong>Synchronous Replication: </strong>In synchronous replication, a commit performed on the source should be committed to all the replicas before the control passes back to the session that performed the transaction. The advantage here is that in case of a failover all the replicas will have the updated copies of the data. The biggest drawback is slow processing and delay to complete the transaction.</p><p><strong>Asynchronous Replication — </strong>This is the default synchronization method used by MySql. Here the primary or the master database accepts the transactions and sends back the acknowledgement to the session. The master DB does not care whether the transactions have been written on any replica or not. With asynchronous replication, if the server crashes the transaction that it might have committed may not have reached the replica and a failover in such a scenario may result in some missing data on the replica w.r.t the primary DB.</p><p><strong>SemiSynchronous Replication: </strong>It falls between synchronous and asynchronous replication. In this case only one replica should acknowledge the event changes from the source DB. This setup guarantees that all the transactions that have been committed to the primary DB are available in at least one of the replicas. Compared to asynchronous replication, semi-synchronous replication provides improved data integrity, because when a commit returns successfully, it is known that the data exists in at least two places. Until a semisynchronous source receives acknowledgment from the required number of replicas, the transaction is on hold and not committed</p><p><strong>Delayed Replication</strong>: We can deliberately lag the replica in a typical MySQL replication by the number of seconds desired by the use case. This type of replication safeguards from severe human errors of dropping or corrupting the data on the primary, for example, in the above diagram for Delayed Replication, if a <strong><em>DROP DATABASE</em></strong> is executed by mistake on the primary, we still have <strong>x</strong> seconds to recover the data from Replica2 as that command has not been replicated on Replica2 yet.</p><h3>Replication Types</h3><p>This is a very fundamental aspect when it comes to replication as this is what defines how the actual replication takes place. For the sake of simplicity I will try to list the different types and explain about them in a nutshell and in the next part we will go over these topics in detail. There are two methods of replication:</p><ul><li><strong><em>Binary log file position based replication</em></strong></li><li><strong><em>Global transaction Identifiers (GTIDs)</em></strong></li></ul><p><strong>Binary log file position based Replication</strong>: Before we dive into this type of replication we need to understand the binary log files(a.k.a <strong><em>binlogs</em></strong>). <em>Binlogs are log files present in the data directory that record all the events about database changes like schema changes or database updates and records them in a specific format. The binlogs do not log any SELECT statements</em>.</p><p>In this type of replication all replicas keep the record of the binlog coordinates of the Primary DB — current binlog and the positions in them till the replica has read and processed. It is quite possible that at any given time two replicas are reading two different events in the same binlog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*awhND1XDNbE2Nvls" /></figure><p><strong><em>Fig: Binlog based replication</em></strong></p><p><strong>Global Transaction Identifiers(GTIDs): </strong>This method is transactional and does not require working with binlogs or positions in them. In this case all transactions performed on the source DB get a unique identifier or GTID(<em>a typical GTID looks like </em><strong><em>server-uuid: positive integer</em></strong>). When using GTIDs, each transaction can be identified and tracked as it is committed on the originating server and applied by any replicas.Because GTID-based replication is completely transaction-based, it is simple to determine whether sources and replicas are consistent; as long as all transactions committed on a source are also committed on a replica, consistency between the two is guaranteed.</p><h3>Conclusion</h3><p>In modern tech solutions replication plays a very crucial role in system design as it not only reduces the risk of data loss but it also improves the performance of the overall solution to a great extent.</p><p>We will cover the actual database replication using Binlogs as well as GTIDs in detail in our coming parts. Stay tuned.</p><p>Part 2 <a href="https://medium.com/@techwithadil/mysql-replication-masterclass-part-2-6bf339ddaea1">here</a>!</p><p>References:</p><ol><li><a href="https://dev.mysql.com/doc/refman/8.0/en/replication.html">https://dev.mysql.com/doc/refman/8.0/en/replication.html</a></li><li><a href="https://www.youtube.com/watch?v=aE2UPg3Ckck">https://www.youtube.com/watch?v=aE2UPg3Ckck</a></li><li><a href="https://linkedin.github.io/school-of-sre/level101/databases_sql/replication/">https://linkedin.github.io/school-of-sre/level101/databases_sql/replication/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5610c8997df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>