<?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 William Johnson on Medium]]></title>
        <description><![CDATA[Stories by William Johnson on Medium]]></description>
        <link>https://medium.com/@relieved_gold_mole_613?source=rss-db132d2bd3fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qDKKwefzwEVHZP7NJxOMGg.jpeg</url>
            <title>Stories by William Johnson on Medium</title>
            <link>https://medium.com/@relieved_gold_mole_613?source=rss-db132d2bd3fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:55:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@relieved_gold_mole_613/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[Why Does MySQL Use B+ Trees?]]></title>
            <link>https://medium.com/@relieved_gold_mole_613/why-does-mysql-use-b-trees-7807ed3090bc?source=rss-db132d2bd3fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7807ed3090bc</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[whys-the-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[William Johnson]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 13:41:50 GMT</pubDate>
            <atom:updated>2024-03-02T13:41:50.138Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, we will analyze in depth the reasons behind MySQL’s choice of B+ trees.</h4><p><strong>Overview</strong><br>First of all, it is important to clarify that MySQL is not directly related to B+ trees. The storage engine in MySQL that is related to B+ trees is the default storage engine, InnoDB. In addition to InnoDB, MySQL also supports MyISAM as another underlying storage engine for tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-l_AO5kMy-AoPxn5JNU4Wg.png" /></figure><p>When creating a table using SQL statements, you can specify the storage engine for the current table. You can find all the supported storage engines in MySQL’s documentation, such as MyISAM, CSV, MEMORY, etc. However, by default, the following SQL statement will create a table supported by the InnoDB storage engine:</p><pre>CREATE TABLE t1 (<br> a INT,<br> b CHAR(20),<br> PRIMARY KEY (a)<br>) ENGINE=InnoDB;</pre><p>The question we will analyze today is ultimately why the default storage engine InnoDB in MySQL uses B+ trees to store data. As many people who are familiar with MySQL know, whether it is data in the table (primary key index) or secondary indexes, B+ trees are used to store the data. In the former case, the data is stored in the table in the form of &lt;id, row&gt;, and in the latter case, it is stored in the form of &lt;index, id&gt;. This is relatively easy to understand:</p><ul><li>In the primary key index, the id is the primary key, and we can find all the columns of the row by using the id.</li><li>In the secondary index, the columns in the index form the key, and we can find the id by using the columns in the index. If necessary, we can then use the id to find all the content of the current data row.</li></ul><p>For InnoDB, all data is stored in the form of key-value pairs. The primary key index and secondary indexes store data by using id and index as keys, and all columns and id as the corresponding values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bac_AL4x7QxWI7xTb1vWIw.png" /></figure><p>Before we analyze the reasons behind InnoDB’s use of B+ trees, we need to consider a few “hypothetical enemies” for B+ trees. Because if we only have one choice, discussing the merits of B+ trees becomes pointless. The two hypothetical enemies we will consider are B trees and hash tables. I believe these are questions that many people will encounter in interviews. We will use these two data structures as examples to analyze the advantages of B+ trees.</p><h4><strong>Design</strong></h4><p>By now, we have clarified the question we will discuss today, which is why MySQL’s InnoDB storage engine chooses B+ trees as the underlying data structure instead of B trees or hash tables. In this section, we will explain the reasons behind InnoDB’s choice from the following two aspects.</p><ul><li>InnoDB needs to have strong performance on specific queries to support the scenarios and functions it needs to handle.</li><li>Loading data from disk to memory takes a lot of time, so B+ trees are an excellent choice.</li></ul><p>Data persistence and querying of persistent data are common requirements. This requires us to deal with disk, memory, and CPU. As an OLTP database, MySQL not only needs to handle transactions but also needs to ensure data persistence and have a certain real-time data query capability. These requirements determine the choice of B+ trees. We will analyze the logic behind these two reasons in detail.</p><h4><strong>Read and Write Performance</strong></h4><p>Many people may not be familiar with the term OLTP. Let us quickly explain it. OLTP stands for Online Transaction Processing, which is the traditional relational database used for basic daily transaction processing. In contrast, OLAP (Online Analytical Processing) is mainly used in data warehouses to support complex analysis and decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAhlRkYIsNIFhKljdXxAkQ.png" /></figure><p>As a storage engine that supports OLTP databases, we often use InnoDB to perform the following tasks:</p><ul><li>Adding, modifying, and deleting data in a table using INSERT, UPDATE, and DELETE statements.</li><li>Batch deletion of data that meets certain conditions using UPDATE and DELETE statements.</li><li>Querying all columns of a specific record by using SELECT statements and the primary key.</li><li>Querying records in a table that meet certain conditions and sorting them based on certain fields using SELECT statements.</li><li>Querying the number of rows in a table using SELECT statements.<br>Ensuring the uniqueness of a field or several fields in a table using a unique index.</li></ul><p>If we use B+ trees as the underlying data structure, the time complexity of SQL statements that only access or modify one data row is O(log n), which is the height of the tree. However, if we use hash tables, the time complexity can reach O(1), which seems very favorable. However, when we use SQL statements like the following, hash tables may not perform well:</p><pre>SELECT * FROM posts WHERE author = &#39;william&#39; ORDER BY created_at DESC<br>SELECT * FROM posts WHERE comments_count &gt; 10<br>UPDATE posts SET github = &#39;github.com/william_j&#39; WHERE author = &#39;william&#39;<br>DELETE FROM posts WHERE author = &#39;william&#39;</pre><p>If we use hash tables as the underlying data structure, when encountering the above scenarios, hash-based primary key indexes or secondary indexes may not be able to handle them quickly. They will perform poorly in range queries or sorting and can only perform full table scans and check each row one by one. Full table scans are terrible for databases, which means that the data structure we use has no effect on these queries, and the final performance may be worse than sequentially matching from logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLykPNfqTsqo2Ed0oPtjhQ.png" /></figure><p>Compared with hash tables, B trees and B+ trees have some similarities in terms of data structures. They can traverse the contents of indexes in a certain order. Compared with hash tables, B trees and B+ trees provide better performance for operations such as sorting and range queries. However, if the index is not well-established or the SQL query is very complex, it may still result in a full table scan.</p><p>Compared with B trees and B trees, tables with hash tables as the underlying data structure may provide O(1) performance for single-row data operations. However, when facing range queries or sorting, they will result in full table scans. On the other hand, B trees and B+ trees, although requiring O(log n) time for single-row data operations, store data with similar index columns in order, thus avoiding full table scans.</p><h4><strong>Data Loading</strong></h4><p>Since using hash tables cannot handle common operations such as sorting and range queries in our SQL statements, why don’t we choose B trees? The reason is simple — computers load data from disk to memory in pages. The size of a page may vary depending on the operating system, but in most operating systems, the page size is 4KB. You can use the following command to obtain the page size on the operating system:</p><pre>$ getconf PAGE_SIZE<br>4096</pre><p>I uses macOS, and the page size on their system is 4KB. Of course, different computers may have different results.</p><p>When we need to query data in a database, the CPU finds that the data is on the disk rather than in memory, and triggers I/O operations to load the data into memory for access. Data is loaded in units of pages. Loading data from disk to memory is very time-consuming. Loading data from a regular disk (non-SSD) involves processes such as queuing, seeking, rotating, and transferring, which takes about 10ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkDkD8z8y_jEHq-c4AOqFg.png" /></figure><p>When estimating MySQL queries, we can use the magnitude of 10ms to estimate the time occupied by random I/O. It should be noted that random I/O has a significant impact on MySQL’s query performance, while sequential reading of data from a disk can achieve a speed of up to 40MB/s. The performance gap between these two methods is several orders of magnitude. Therefore, we should try to minimize the number of random I/O operations to improve performance.</p><p>The biggest difference between B trees and B+ trees is that B trees can store data in non-leaf nodes, while all data in B+ trees is stored in leaf nodes. When the underlying data structure of a table is a B tree, if we need to access all data that is “greater than 4 and less than 9”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3URMLiXzxSEF2lmvup9rw.png" /></figure><p>If we don’t consider any optimization, in the simple B tree shown above, we will need to perform four random I/O operations to find all the data rows that meet the conditions:</p><ol><li>Load the page where the root node is located and find that the first element of the root node is 6, which is greater than 4.</li><li>Load the page where the left child node is located through the pointer of the root node and traverse the data in the page to find 5.</li><li>Reload the page where the root node is located and find that the root node does not contain the second element.</li><li>Load the page where the right child node is located through the pointer of the root node and traverse the data in the page to find 7 and 8.</li></ol><p>Of course, we can optimize the above process in various ways. However, most optimizations that can be applied to B trees can also be applied to B+ trees. Therefore, we do not need to consider the benefits brought by optimizing B trees and directly look at the optimizations that B+ trees can achieve but B trees cannot.</p><p>Since all nodes may contain the target data, we always need to traverse the subtree from the root node to find data rows that meet the conditions. This characteristic results in a large number of random I/O operations, which is the biggest performance problem of B trees.</p><p>B+ trees do not have this problem because all data rows are stored in leaf nodes, and these leaf nodes are connected in order through “pointers”. When traversing data in a B+ tree like the one shown above, we can directly jump between multiple child nodes, which can save a lot of disk I/O time and avoid concatenation and sorting of data between different levels of nodes. By starting from the leftmost leaf node of a B+ tree, we can traverse all the data in the tree like a linked list. We can also introduce a doubly linked list to ensure the performance of reverse traversal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rccu2L96GCDRvb5uB7Nq_Q.png" /></figure><p>Some readers may think that using B+ trees as the data structure will increase the height of the tree and overall time consumption. However, a B+ tree with a height of 3 can store tens of millions of data rows. In practice, the height of a B+ tree is usually no more than 4 or 5, so this is not a fundamental problem affecting performance.</p><h4>Summary</h4><p>Any design that does not consider application scenarios is not the best design. Once we have clearly defined the common query requirements when using MySQL and understood the scenarios, selecting different data structures becomes a matter of course. Although B+ trees may not have the best performance for all queries in OLTP scenarios, they can solve most problems.</p><p>Let’s review the reasons why MySQL’s default storage engine chooses B+ trees instead of hash tables or B trees:</p><ul><li>Although hash tables can provide O(1) performance for single-row operations, they cannot support range queries and sorting well, resulting in full table scans.</li><li>B trees can store data in non-leaf nodes, but this may result in more random I/O when querying continuous data. On the other hand, all leaf nodes of B+ trees can be connected through pointers, reducing additional random I/O time during sequential traversal. B trees cannot achieve this.</li></ul><p>If you want to pursue extreme performance in all aspects, it is not impossible, but it will bring higher complexity. We can build both B+ trees and hash-based storage structures for a table, so different types of queries can choose the relatively faster data structure. However, this will require manipulating multiple sets of data during updates and deletions.</p><p>From today’s perspective, B+ trees may not be the optimal choice for InnoDB, but they were the best choice to meet the design requirements at that time. From the time B+ trees were chosen as the underlying storage structure for databases to today, which has been decades, we have to say that excellent engineering design indeed has enough vitality. As engineers, when choosing a database, we should also have a clear understanding of the suitable scenarios for different databases, because there is no silver bullet in software engineering.</p><p>Finally, let’s look at some more open-ended related questions. Interested readers can carefully consider the following questions:</p><ul><li>What kind of data structure is commonly used to store data in OLAP databases used for analysis? Why?</li><li>How does Redis store data persistently? What are the common data structures used?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7807ed3090bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Explanation: Share Memory By Communicating]]></title>
            <link>https://medium.com/@relieved_gold_mole_613/golang-explanation-share-memory-by-communicating-8be944cbf8f8?source=rss-db132d2bd3fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be944cbf8f8</guid>
            <category><![CDATA[whys-the-design]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[csp]]></category>
            <category><![CDATA[actor-model]]></category>
            <dc:creator><![CDATA[William Johnson]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 04:13:09 GMT</pubDate>
            <atom:updated>2024-03-01T04:14:01.990Z</atom:updated>
            <content:encoded><![CDATA[<p>“Do not communicate by sharing memory; instead, share memory by communicating.” This is a viewpoint often heard from programmers using the Go programming language. However, we may have never carefully considered why Go encourages us to follow this design philosophy. In this article, we will explain why we should prefer using communication to exchange messages instead of using shared memory.</p><p><strong>Overview</strong><br>Using communication to share memory is not only a philosophy advocated by Go, but also followed by the older Erlang language. However, these two languages have some differences in their specific implementations. The former uses Communication Sequential Process (CSP), while the latter uses the Actor model. Both of these different concurrency models are specific implementations of “sharing memory by communicating”, and their main purpose is to exchange information between different threads or coroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZIhG_s65HQlHKj4DQHWIQ.png" /></figure><p>Fundamentally, the synchronization of information between threads and coroutines on a computer is achieved through “shared memory”. Because no matter which communication model is used, threads or coroutines ultimately retrieve data from memory. Therefore, a more accurate statement would be “Why do we use message passing to synchronize information instead of directly sharing memory between multiple threads or coroutines?”</p><p>To understand this issue, we need to understand the advantages and disadvantages of these two different information synchronization mechanisms and compare their strengths and weaknesses. This way, we can fully understand the reasons behind the decisions made by Go and other languages and frameworks.</p><p><strong>Design</strong><br>In this article, we will mainly discuss why we should choose to use communication to ensure information synchronization between multiple threads or coroutines from the following aspects:</p><ul><li>Different synchronization mechanisms have different levels of abstraction.</li><li>Synchronizing information through message passing can reduce coupling between different components.</li><li>Using messages to share memory does not lead to thread contention issues.</li></ul><p>Although these three perspectives may overlap or be incomplete, they can still provide us with enough information to make judgments and choices, and understand how Go is influenced by this design philosophy and how it shapes the current form of its concurrency model.</p><p><strong>Abstraction Level</strong><br>Sending messages and sharing memory are two different ways of transmitting information. However, they have different levels of abstraction. Sending messages is a relatively “high-level” abstraction. However, different languages also use the locking mechanisms provided by the operating system to implement this mechanism. Shared memory, as the most primitive and essential way of information transmission, is implemented using locking concurrency mechanisms.</p><p>We can understand it like this: more advanced and abstract methods of information transmission are actually just combinations and encapsulations of lower-level interfaces. The channel in Go provides a way for Goroutines to communicate with each other. Internally, it extensively uses shared memory and locks. By combining the two, it provides a higher-level synchronization mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pu2167hBfmH-6QK2065S8Q.png" /><figcaption>golang channel with shared memory</figcaption></figure><p>Since both methods can help us transmit information between different threads or coroutines, we should try to use methods with higher levels of abstraction. These methods often provide better encapsulation and designs that are more relevant and suitable for the domain. Only when higher-level abstractions cannot meet our requirements should we consider methods with lower levels of abstraction, such as when we encounter scenarios that require finer-grained control over resources or have extremely high performance requirements.</p><p><strong>Coupling</strong><br>Using message passing instead of shared memory can also help us reduce coupling between multiple modules. Suppose we use shared memory to transmit information between multiple Goroutines, and each Goroutine can be both a producer and a consumer of resources. They need to acquire a mutex lock that protects the resource before reading or writing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8XpiuXH50kvNjaFW6nF4A.png" /></figure><p>However, using message passing allows us to decouple multiple threads or coroutines. Previously, multiple threads that depended on the same shared memory can now become producers and consumers of messages. Multiple threads no longer need to manually handle resource acquisition and release. Go’s implementation of the CSP mechanism decouples Goroutines by introducing channels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjtQhh4whtTyUlwW9uHrpg.jpeg" /></figure><p>Another concurrent control mechanism, the Actor model, which uses message passing, omits the concept of channels. Each actor holds a mailbox for pending messages locally, and multiple actors can directly send messages to a target actor using its identifier. All messages will wait in the local mailbox for the current actor to process.</p><p>This decoupling through message passing, especially the CSP model implemented in Go, is very similar to message queues. By introducing channels as an intermediate layer, we make the producers and consumers of resources clearer. When we need to add new producers or consumers, we only need to directly add the sending and receiving ends of the channel.</p><p><strong>Thread Contention</strong><br>In many environments, many problems caused by concurrent programming are due to the incorrect implementation of accessing shared memory. However, Go encourages us to pass shared variables into channels. The shared variables will not be accessed by multiple active Goroutines at the same time. This ensures that only one Goroutine can access the corresponding value at any given time. Therefore, problems of data conflicts and thread contention are not possible to occur in the design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6YAMjP9u694qIecKkItvg.png" /></figure><p>It should be noted that if we send a pointer instead of a value to a channel, the sender actually retains the right to modify the value corresponding to the pointer after sending the message to the channel. If both the sender and receiver try to modify the value corresponding to the pointer, data conflicts will still occur.</p><p>For programs running on the same machine and process, since the memory is visible to the current process, we cannot avoid such problems. We can only say that this is not an encouraged practice or a conventional behavior. When we need to deal with such scenarios, using lower-level mutex locks is the correct approach. However, in most cases, this implies incorrect design, and we need to rethink the relationships between threads.</p><p><strong>Summary</strong><br>The design of Go’s concurrency model is deeply influenced by the CSP model. Let’s summarize why we should use communication to share memory:</p><blockquote>Do not communicate by sharing memory; instead, share memory by communicating.</blockquote><p>First, using message passing to synchronize information is a more advanced abstraction compared to directly using shared memory and mutex locks. Using higher-level abstractions can provide better encapsulation and make the program logic clearer.<br>Second, in terms of decoupling, message passing has certain advantages over shared memory. We can divide the responsibilities of threads into producers and consumers and decouple them through message passing, without relying on shared memory.<br>Finally, by choosing message passing, Go ensures that only one active thread can access the shared data at any given time. This naturally avoids thread contention and data conflicts from a design perspective.<br>Although the above points may not fully explain all aspects of why Go chooses this design, they provide sufficient reasons to encourage the use of communication to synchronize information. We should also learn this way of thinking in designing and implementing Go programs, making our programs easier to understand. Now we can discuss some more open-ended questions. Readers can think about the answers to the following questions:</p><p>Apart from using message passing and shared memory, what other methods can we choose to exchange messages between different threads?<br>Is there any similarity between shared memory and shared databases as synchronization mechanisms? What are the similarities and differences between them?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be944cbf8f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why does TCP connection establishment require three-way handshake?]]></title>
            <link>https://medium.com/@relieved_gold_mole_613/why-does-tcp-connection-establishment-require-three-way-handshake-2f9e2c5da1ce?source=rss-db132d2bd3fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f9e2c5da1ce</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[tcp-ip]]></category>
            <category><![CDATA[whys-the-design]]></category>
            <category><![CDATA[tcp]]></category>
            <dc:creator><![CDATA[William Johnson]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 07:53:55 GMT</pubDate>
            <atom:updated>2024-02-29T07:57:36.463Z</atom:updated>
            <content:encoded><![CDATA[<p>The majority of network connections are established based on TCP protocol. Those who have studied computer networks or have some understanding of TCP protocol know that establishing a connection using TCP requires a three-way handshake.</p><p>It is important to note that our focus will be on <strong>why</strong> TCP connection establishment requires a “three-way handshake,” rather than just “three” handshakes.</p><h4>Overview</h4><p>Before delving into the specific analysis of today’s question, let’s first address a commonly used but misleading analogy about the TCP connection process. For a long time, the author believed that this analogy could well explain why TCP connection establishment requires three-way handshake:</p><ol><li>Can you hear me?</li><li>I can hear you, can you hear me?</li><li>I can hear you too.</li></ol><p>However, relying on analogies to explain a problem often leads to incomplete understanding. When someone uses an analogy to answer the question “why,” we need to carefully consider where the analogy may have loopholes. Analogies can only provide partial similarity, and we can never find a perfect analogy. They can only be useful when we want to present the characteristics of something in a popular and easy-to-understand way. We will explain later why this analogy is flawed, and readers can read the rest of the content with this question in mind.</p><p>When many people try to answer or think about this question, they often focus on the three steps involved in the three-way handshake. While these steps are indeed important, if we reexamine the question, do we really understand “what is a connection”? Only by understanding the definition of a connection can we attempt to answer why TCP connection establishment requires three-way handshake.</p><blockquote>The reliability and flow control mechanisms described above require that TCPs initialize and maintain certain status information for each data stream. The combination of this information, including sockets, sequence numbers, and window sizes, is called a connection.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s7VYFW7yJwxCW38gu4I9g.png" /></figure><p><a href="https://datatracker.ietf.org/doc/html/rfc793">RFC 793 — Transmission Control Protocol</a> clearly defines what a connection is in TCP. In summary: the information used for reliability and flow control mechanisms, including sockets, sequence numbers, and window sizes, is called a connection.</p><p>So, establishing a TCP connection means that the two parties in communication need to reach a consensus on the three types of information mentioned above. A pair of sockets in a connection is composed of an Internet address identifier and a port. Window size is mainly used for flow control. The initial sequence number is used to track the sequence number of data packets sent by the initiator, and the receiver can confirm the successful receipt of a specific data packet by using the sequence number.</p><p>At this point, we have transformed the original question into “why do we need a three-way handshake to initialize sockets, window sizes, and initial sequence numbers?” Next, we will analyze and seek explanations for this refined question.</p><h4>Design</h4><p>This article will mainly discuss why we need a three-way handshake to initialize sockets, window sizes, initial sequence numbers, and establish a TCP connection from the following perspectives:</p><ul><li>A three-way handshake is needed to prevent the confusion caused by the initialization of historical duplicate connections.</li><li>A three-way handshake is needed to initialize the initial sequence numbers of both parties in communication.</li><li>Discuss the possibility of establishing a connection with a different number of handshakes.</li></ul><p>Among these arguments, the first one is the main reason why TCP chooses to use a three-way handshake. The other reasons are relatively minor. We discuss them here to provide a more comprehensive perspective and a better understanding of this interesting design decision.</p><h4>Historical Connections</h4><p><a href="https://datatracker.ietf.org/doc/html/rfc793">RFC 793 — Transmission Control Protocol </a>actually points out the primary reason why TCP connection uses a three-way handshake — to prevent confusion caused by the initialization of duplicate historical connections.</p><blockquote>The principle reason for the three-way handshake is to prevent old duplicate connection initiations from causing confusion.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lMTtafgqHmdfRAGWydTAA.png" /></figure><p>Imagine this scenario: if the number of communications between the two parties is only two, once the sender sends a connection establishment request, it cannot retract this request. In a complex or poor network condition, if the sender continuously sends multiple connection establishment requests, and if TCP connection only allows two communications, the receiver can only choose to accept or reject the sender’s request without knowing whether this request is an expired connection due to network congestion.</p><p>Therefore, TCP chooses to use a three-way handshake to establish a connection and introduces the RST control message. When the receiver receives a request, it sends the sender’s SEQ+1 to the sender. The sender then determines whether the current connection is a historical connection:</p><p>If the current connection is a historical connection, meaning the SEQ has expired or timed out, the sender will directly send an RST control message to terminate the connection.<br>If the current connection is not a historical connection, the sender will send an ACK control message, and the two parties in communication will successfully establish a connection.<br>Using a three-way handshake and RST control message gives the sending party the ultimate control over whether to establish a connection. Only the sending party has enough context to determine whether the current connection is erroneous or expired. This is also the primary reason why TCP uses a three-way handshake to establish a connection.</p><h4>Initial Sequence Numbers</h4><p>Another important reason for using a three-way handshake is that both parties in communication need to obtain an initial sequence number (ISN) for sending messages. As a reliable transport layer protocol, TCP needs to build a reliable transport layer in an unstable network environment. The network’s uncertainty may lead to problems such as data duplication caused by multiple transmissions from the sender, packet loss during transmission, and the inability of the receiving party to receive packets in the order they were sent.</p><p>To address these potential issues, TCP requires the sender to include a “sequence number” field in the data packet. With the corresponding sequence number for each data packet, we can:</p><p>The receiver can deduplicate repeated data packets based on the sequence numbers.<br>The sender can retransmit the corresponding data packet if it is not acknowledged.<br>The receiver can reorder the data packets based on their sequence numbers.<br>Sequence numbers play a vital role in TCP connections, and the initial sequence number, as part of a TCP connection, needs to be initialized during the three-way handshake. Since both parties in a TCP connection need to obtain the initial sequence number, they need to send SYN control messages to each other and include their expected initial sequence numbers (SEQ). After receiving the SYN message, the other party confirms it by sending an ACK control message and SEQ+1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkLLW6l_-A2aeJUFCSTYpw.png" /></figure><p>As shown in the above figure, the two TCPs, A and B, send SYN and ACK control messages to each other. Once both parties obtain their expected initial sequence numbers, they can start communication. Due to the design of the TCP message header, we can combine the two intermediate communications into one. TCP B can send both ACK and SYN control messages to TCP A simultaneously, reducing the four-way communication to three.</p><p>“A three-way handshake is necessary because sequence numbers are not tied to a global clock in the network, and TCPs may have different mechanisms for picking the ISN’s. The receiver of the first SYN has no way of knowing whether the segment was an old delayed one or not unless it remembers the last sequence number used on the connection (which is not always possible), and so it must ask the sender to verify this SYN. The three-way handshake and the advantages of a clock-driven scheme are discussed in [3].”</p><p>In addition to the reasons mentioned above, as a distributed system, there is no global clock for counting in the network. TCP can initialize sequence numbers using different mechanisms. As the receiver of a TCP connection, we cannot determine whether the received initial sequence number is expired. Therefore, we need to rely on the sender to make this judgment. It is not practical for the receiver to save and verify sequence numbers, which reinforces the point we raised in the previous section — avoiding the initialization of erroneous historical connections.</p><h4>Number of Communications</h4><p>When discussing the number of communications required for TCP connection establishment, we often focus on why it takes three communications to establish a connection instead of two or four. Discussing using more communications to establish a connection is often meaningless because we can always use more communications to exchange the same information. Therefore, it is technically feasible to use four, five, or more communications to establish a connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N59myBWXn0XBPyYFzpNSCw.png" /></figure><p>This issue of increasing the number of communications in TCP connection establishment is often not worth discussing. What we pursue is completing information exchange with the fewest number of communications (the theoretical limit). This is why we repeatedly emphasize in the previous two sections that a “two-way handshake” cannot establish a TCP connection, and a three-way handshake is the minimum number of communications required to establish a connection.</p><h4>Summary</h4><p>In this article, we have discussed why TCP connection establishment requires a three-way handshake. Before analyzing this specific question, we first reconsidered what a TCP connection actually is. RFC 793 — Transmission Control Protocol — IETF Tools provides a clear definition of a TCP connection — data used for reliability and flow control mechanisms, including sockets, sequence numbers, and window sizes.</p><p>The three-way handshake in TCP can effectively prevent the establishment of erroneous historical connections, reducing unnecessary resource consumption for the two parties in communication. The three-way handshake helps the two parties obtain initial sequence numbers, ensuring that data packets are transmitted without duplication or loss and maintaining their correct order. By now, it is clear why we cannot use a “two-way handshake” and why a “four-way handshake” is not necessary:</p><p>“Two-way handshake”: Cannot prevent the initialization of erroneous historical connections and wastes the receiver’s resources.<br>“Four-way handshake”: The design of TCP allows us to simultaneously transmit both ACK and SYN control messages, reducing the number of communications required. Therefore, there is no need to use more communications to transmit the same information.</p><p>Returning to the question raised at the beginning of the article, why is it incorrect to explain TCP’s three-way handshake using analogies? This is mainly because the analogy does not explain the core issue — avoiding the initialization of historical duplicate connections. In the end, let’s consider some open-ended questions. Interested readers can carefully think about the following:</p><p>Besides using sequence numbers, are there other ways to ensure the non-duplication and non-loss of messages?<br>Does UDP protocol have the concept of connection? Can it guarantee the reliability of data transmission?</p><p>If there are any questions or if you want to learn more about the reasons behind certain design decisions in software engineering, you can leave a comment below the blog. I will promptly respond to related questions and select suitable topics for future content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f9e2c5da1ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>