<?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[backend - Medium]]></title>
        <description><![CDATA[Server application design and implementation - Medium]]></description>
        <link>https://medium.com/backend?source=rss----57d84e1e0748---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>backend - Medium</title>
            <link>https://medium.com/backend?source=rss----57d84e1e0748---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:52:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/backend" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Don’t Worry if You Overslept This Class— Byte Order]]></title>
            <link>https://medium.com/backend/no-worries-if-you-oversleep-this-class-byte-order-d16eb5481c7d?source=rss----57d84e1e0748---4</link>
            <guid isPermaLink="false">https://medium.com/p/d16eb5481c7d</guid>
            <category><![CDATA[endianness]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[network-programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[byte-order]]></category>
            <dc:creator><![CDATA[Holmes He]]></dc:creator>
            <pubDate>Thu, 14 Mar 2019 01:46:22 GMT</pubDate>
            <atom:updated>2018-05-27T08:50:35.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PDz4jdJ38qCxkbKjVQAEQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/8b1cWDyvT7Y?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mitchell Hollander</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>When I was reading the source code of a network system, htons() and ntohs() are the very first two functions that confused me. To understand them, I decided to refresh the fading knowledge learned from college in order to squeeze out the last bit of conceptual doubt in byte order.</blockquote><p>We are lucky as computer science practitioners since we already understand the smallest unit in cyber space, that is, <em>bi</em>t. Thus, we only need to advance towards one direction, up.</p><p>A <em>bit</em> is simply a 0 or an 1. Physically it is sometimes represented as a tiny magnetic region on a metal plate.</p><p>Moving up, we have <em>byte</em> that is 8 <em>bits</em>. We generally use <em>byte</em> to measure the sizes of data, like we use meter to measure sizes of objects. So instead of saying “something is 32 <em>bits”</em>, we normally say “it is 4 <em>bytes”</em>.</p><p>Moving upward, we have <em>word </em>that is 4 <em>bytes</em> (or 32 <em>bits</em>)in 32 bit architecture. Note that I use 32 bit architecture throughout this text to keep it concise, and the concept can be easily ported to 64 bit architectures.</p><h3>Network and host byte order</h3><p><em>byte order</em> (also known as, <em>endianness</em>) controls how a <em>word</em> is stored in memory, and how it is transmitted over the network. In <em>big-endian</em>, the most significant <em>byte</em> is set at the lowest address; whilst in little India, some dishes are really hot…no…in <em>little-endian</em>, the most significant <em>byte</em> is set at the highest address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wKuGzRmYypdgf-B1.png" /><figcaption>One direction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JYkd3XA6L6HQsThe.png" /><figcaption>Or another</figcaption></figure><p>Laying <em>bytes</em> on physical media (that is, memory &amp; network) is like laying floors, in both cases it is OK to lay a wooden tile, or a 4-<em>bytes</em> <em>word</em> in both directions. However, a system designer has to make a decision so as to keep the style consistent. Defined by RFC 1700, network protocols designers chose <em>big-endian</em>. However, some designers of host systems disagree. In X86, it is <em>little-endian</em>; In ARM, it could be either. That means the actual data of the same value varies in different physical media. For instance, the value A1B2C3D4 (2712847316 in decimal) can have two forms, as given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*lAnnpQdIF5zSUDRC.png" /></figure><p>In the above figure, each box — for example, the box containing A1 — represents a <em>byte. </em>Please note that the “endianness shuffling” is based on the unit of <em>byte</em>, not <em>bit</em>.</p><p>Machines can process the two formats almost equally well, but humans complaint that the numbers in <em>little-endian</em> are reversed. Why? Isn’t it more logical to set the less significant <em>byte</em> to lower address, and more to higher?</p><p>The reason is: when we write digital on papers (that is, well, another physical media), we use <em>big endian</em> unconsciously. Taking the above number (A1B2C3D4) as the example, our sub-conscious draws the low and high addresses from left to right even though they are not there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*KClmJMvwSP145kxj5R-uYQ.png" /><figcaption>We use big endian unconsciously</figcaption></figure><p>But if we mandate our subconscious to draw them from right to left, maybe we can reconcile the conflicts between the rationale and intuition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*jUnsu10gxrNqLvLAtVZlYA.png" /><figcaption>It is NATURALLY little endian now!</figcaption></figure><p>In my opinion, it is perfectly acceptable because we use all kinds of coordinate systems when locating UI components on a screen (e.g., app, game development), for instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*7A1SHPelPThcTVr1YmxKaA.png" /></figure><p>What do you think?</p><p>Next we look at how the theories are used, and why they matter, in practice.</p><h3>htons() ntohs()</h3><p>These two functions fill the format gap between the network and hosts. Technically, when hosts communicates over network, they are used to convert the packet’s <em>byte order</em>. If the host and network <em>byte order</em> are the same (that means they both uses <em>big-endian</em>), the two functions simply do nothing. When they are different (that means the host uses <em>little-endian</em>), htons() converts the data from <em>little-endian</em> to <em>big-endian</em>, and ntohs() converts from <em>big-endian</em> back to <em>little-endian</em>.</p><p>There is another pair of functions of this kind, htonl() and ntohl() that operate on larger numbers than htons() and ntohs(). They are based on the same principle so I will not further discuss them.</p><h3>Fact-check</h3><p>I always need concrete code to be sure.</p><pre>#include &lt;stdio.h&gt;</pre><pre>#define BITS_PER_BYTE 8</pre><pre>int main() {<br>  unsigned int anint = 0xa1b2c3d4;<br>  unsigned char *truth = &amp;anint;</pre><pre>  printf(&quot;value in decimal: %u\n&quot;, anint);<br>  printf(&quot;0x&quot;);</pre><pre>  for (int i = 0; i &lt; sizeof(anint); i++) {<br>    printf(&quot;%2X&quot;, truth[i]);<br>  }</pre><pre>  printf(&quot;\n&quot;);<br>  <br>  unsigned int anint_net = htons(anint);<br>  truth = &amp;anint_net;</pre><pre>  printf(&quot;value in decimal after hton: %u\n&quot;, anint_net);<br>  printf(&quot;0x&quot;);</pre><pre>  for (int i = 0; i &lt; sizeof(anint_net); i++) {<br>    printf(&quot;%02X&quot;, truth[i]);<br>  }</pre><pre>  printf(&quot;\n&quot;);<br>}</pre><p>The result on my machine:</p><pre>value in decimal: 2712847316<br>0xD4C3B2A1<br>value in decimal after hton: 54467<br>0xC3D40000</pre><p>As given in the example, htons() changes the original value of anint using<em> big-endian</em> to prepare for network transmission and the original value will be recovered in the receiving host by ntohs(). Though the real network operations are not demonstrated in the example, I think you can get the idea.</p><h3>How to determine</h3><p>We can reuse some code from the above example to impelment a function that can show a machine’s <em>byte order</em>:</p><pre>int isLittle() {<br>  unsigned int anint = 0xa1b2c3d4;<br>  unsigned char *truth = &amp;anint;<br>  return truth[0] == 0xd4;<br>}</pre><p>In fact, there is a much simpler way, reading directly the CPU information. If <a href="https://askubuntu.com/questions/902907/check-system-is-little-endian-or-big-endian">asking Ubuntu</a>, you’ll know the code-free method:</p><pre>cpu | grep &quot;Byte Order&quot;</pre><p>I think the text is concise enough to spare a conclusion.</p><p>If you like this read please clap for it or follow by clicking the buttons. Thank you for your time and I hope to see you the next time.</p><p><em>Originally published at </em><a href="http://holmeshe.me/network-essentials-byte-order/"><em>holmeshe.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16eb5481c7d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend/no-worries-if-you-oversleep-this-class-byte-order-d16eb5481c7d">Don’t Worry if You Overslept This Class— Byte Order</a> was originally published in <a href="https://medium.com/backend">backend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[setsockopt, TCP_NODELAY and Packet Aggregation I]]></title>
            <link>https://medium.com/backend/setsockopt-tcp-nodelay-and-packet-aggregation-i-c1ea56aefb5e?source=rss----57d84e1e0748---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1ea56aefb5e</guid>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[setsockopt]]></category>
            <category><![CDATA[packet-aggregation]]></category>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Holmes He]]></dc:creator>
            <pubDate>Fri, 22 Jun 2018 10:49:37 GMT</pubDate>
            <atom:updated>2018-06-23T22:48:31.371Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w979ZH0JuKlaiARXFfAR0g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/e-S-Pe2EmrE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rowan Heuvel</a> on <a href="https://unsplash.com/search/photos/bird?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Latency, instead of throughput, is found as the system bottleneck more often than not. However, by default, the TCP socket enables a so-called <em>nagle algorithm</em>, which delays an egress packet in order to coalesces it with one that could be sent in the future, into a single TCP segment. This effectively reduces the number of TCP segments and the bandwidth overhead used by the TCP headers, whilst potentially imposes latency for every network request (response) being sent.</p><blockquote><em>Lock, and his temperamental brother, Block, are the two notorious villains in the world of programming. In the beginning, they always show up to assist. But sooner or later, they will kick your back-end very hard.</em></blockquote><p>When I consider about <em>nagle algorithem</em>, it seems to me another scenario involving block operations which are meant to be helpful. So I decide to put hands on a keyboard to test if I am wrong.</p><p><strong>Software setup</strong><br><em>Client OS: Debian 4.9.88</em><br><em>Server OS (LAN &amp; WAN): Unbutu 16.04</em><br><em>gcc: 6.3.0</em></p><p><strong>Hardware (or VM) setup</strong><br><em>Server (LAN): Intel® Core™2 Duo CPU E8400 @ 3.00GHz × 2, 4GB</em><br><em>Server (WAN): t2.micro, 1GB</em></p><h3>The impact nagle algorithm has on latency</h3><p>First thing first, the code of<br>client:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05df8b2052b0ac9c5c847f8e0911e87e/href">https://medium.com/media/05df8b2052b0ac9c5c847f8e0911e87e/href</a></iframe><p>and server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da58ed4f6c7b0a68c2a202f774832715/href">https://medium.com/media/da58ed4f6c7b0a68c2a202f774832715/href</a></iframe><p>The client code given above sends 1000 packets 4 bytes long in an interval indicated by the last command line argument. And as discussed, it adopts the default TCP behavior by default. The server is not different than a discard server, so the code is irrelevant here.</p><p>In this test, I will record the number of packets that are aggregated in different intervals, by adjusting the mentioned argument. This way, we can grasp the extent of latency the <em>nagle algorithm</em> can impose. The same test is conducted in both LAN (RTT &lt; 0.6ms) and WAN (RTT ≈ 200ms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*XyDhEH6EA2ke_b6SjLx4pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*ZTJgEFBqWdzVrlb3MA6uNQ.png" /></figure><p>As given in the figures, the number aggregated packets approaches to 0 when the interval is greater than the RTT. This conforms to what described in &lt;&lt;TCP/IP Illustrated&gt;&gt;</p><blockquote><em>This algorithm says that a TCP connection can have only one outstanding small segment that has not yet been acknowledged. No additional small segments can be sent until the acknowledgment is received.</em></blockquote><p>If looking at the tcpdump output, we can also see that this algorithm effectively changes the sending interval to the RTT regardless of the actual write(2) frequency of the program. And the packets between two sends are those being aggregated.</p><pre>…<br>18:34:52.986972 IP debian.53700 &gt; ******.compute.amazonaws.com.6666: Flags [P.], seq 4:12, ack 1, win 229, options [nop,nop,TS val 7541746 ecr 2617170332], length 8<br>18:34:53.178277 IP debian.53700 &gt; ******.amazonaws.com.6666: Flags [P.], seq 12:20, ack 1, win 229, options [nop,nop,TS val 7541794 ecr 2617170379], length 8<br>18:34:53.369431 IP debian.53700 &gt; ******.amazonaws.com.6666: Flags [P.], seq 20:32, ack 1, win 229, options [nop,nop,TS val 7541842 ecr 2617170427], length 12<br>18:34:53.560351 IP debian.53700 &gt; ******.amazonaws.com.6666: Flags [P.], seq 32:40, ack 1, win 229, options [nop,nop,TS val 7541890 ecr 2617170475], length 8<br>18:34:54.325242 IP debian.53700 &gt; ******.amazonaws.com.6666: Flags [P.], seq 68:80, ack 1, win 229, options [nop,nop,TS val 7542081 ecr 2617170666], length 12<br>…</pre><p><strong>As a result, the delay imposed on every packet by the algorithm is RTT on average and 2 * RTT in worst case.</strong></p><h3>Combined with delayed ACK</h3><p>Delayed ACK is another similar algorithm, here I will just use the lines from &lt;&lt;TCP/IP Illustrated&gt;&gt; to brief the mechanism</p><blockquote><em>TCP will delay an ACK up to 200 ms to see if there is data to send with the ACK.</em></blockquote><p><a href="https://news.ycombinator.com/item?id=10607422">Apperantly <em>nagle algorithm</em> is not happy with<em> delayed ACK</em></a>.</p><p>In some cases when the back-end do not reply instantly to a request, <em>delayed ACK</em> will have to wait for another request which is potentially delayed by <em>nagle algorithm</em> waiting for ACK. This scenario where two resources waiting for each other, in another word, is called a dead-lock.</p><blockquote><em>Remember the two brothers mentioned in the beginning?</em></blockquote><p>Unfortunately, in my environments, seems like the <em>delayed ACK</em> is disabled by default and I failed to enable it by</p><pre>flags = 0;<br>flglen = sizeof(flags);<br>getsockopt(sfd, SOL_TCP, TCP_QUICKACK, &amp;flags, &amp;flglen)</pre><p>So I could not hand test the compounded impact.</p><h3>Discussion</h3><p>At the moment when I am writing, except for <em>telnet</em>, most of the other applications, including those of front-end(<em>Firefox</em>, <em>Chromium</em>), back-end(<em>nginx</em>, <em>memcached</em>), and the <em>telnet</em>‘s substitute, <em>ssh</em>, disable <em>nagle algorithm</em> with some code like bellow,</p><pre>int flags =1;<br>setsockopt(sfd, SOL_TCP, TCP_NODELAY, (void *)&amp;flags, sizeof(flags));</pre><p>which indicates that the packets should be emitted as it is.</p><pre>…<br>18:22:38.983278 IP debian.43808 &gt; 192.168.1.71.6666: Flags [P.], seq 1:5, ack 1, win 229, options [nop,nop,TS val 7358245 ecr 6906652], length 4<br>18:22:38.984149 IP debian.43808 &gt; 192.168.1.71.6666: Flags [P.], seq 5:9, ack 1, win 229, options [nop,nop,TS val 7358246 ecr 6906652], length 4<br>18:22:38.985028 IP debian.43808 &gt; 192.168.1.71.6666: Flags [P.], seq 9:13, ack 1, win 229, options [nop,nop,TS val 7358246 ecr 6906653], length 4<br>18:22:38.985897 IP debian.43808 &gt; 192.168.1.71.6666: Flags [P.], seq 13:17, ack 1, win 229, options [nop,nop,TS val 7358246 ecr 6906653], length 4<br>18:22:38.986765 IP debian.43808 &gt; 192.168.1.71.6666: Flags [P.], seq 17:21, ack 1, win 229, options [nop,nop,TS val 7358246 ecr 6906653], length 4<br>…</pre><p>I think the reasons behind the prevalence of TCP_NODELAY are as follows,<br>1) the increasing bandwidth makes the benefits of <em>nagle algorithm</em> more and more negligible - it requires hundreds of thousands of tinygrams to saturate an edge node with mediocre bandwidth nowadays; and<br>2) app that generate a lot of tinygram tend to demand low latency.</p><p>To conclude, technically, it’s probably not a good idea to turn a modern real-time on-line battle arena into some (200 ms) turn based 80s RPG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*Tl80zyTR1gzt_tZWv1VuBA.gif" /></figure><h3>References</h3><p><a href="https://www.amazon.com/TCP-Illustrated-Vol-Addison-Wesley-Professional/dp/0201633469">TCP/IP Illustrated</a><br><a href="https://tools.ietf.org/html/rfc896">RFC 896</a><br><a href="https://news.ycombinator.com/item?id=10607422">Hacker news</a></p><p><em>Originally published at </em><a href="https://holmeshe.me/network-essentials-setsockopt-TCP_NODELAY/"><em>holmeshe.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1ea56aefb5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend/setsockopt-tcp-nodelay-and-packet-aggregation-i-c1ea56aefb5e">setsockopt, TCP_NODELAY and Packet Aggregation I</a> was originally published in <a href="https://medium.com/backend">backend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[setsockopt, SO_KEEPALIVE and Heartbeats]]></title>
            <link>https://medium.com/backend/setsockopt-so-keepalive-and-heartbeats-ebbd00f9281f?source=rss----57d84e1e0748---4</link>
            <guid isPermaLink="false">https://medium.com/p/ebbd00f9281f</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Holmes He]]></dc:creator>
            <pubDate>Sat, 02 Jun 2018 09:46:19 GMT</pubDate>
            <atom:updated>2018-06-05T04:09:17.969Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYRH2MT34p8SnCW0SzJO-g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/9K_tJ7dxYSU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rawpixel</a> on <a href="https://unsplash.com/search/photos/heartbeat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There are two end purposes for sending heartbeats through a persistent connection. For a back-end application, heartbeats are generally used to detect an absent client, so as to drop a connection and release the associated resources; for a client, on the contrary, it is to prevent connection resources stored within intermediate nodes being released (such as a <em>NAT</em> router), SO as to KEEP the connection ALIVE.</p><p>This article will examine how to configure the four socket options, SO_KEEPALIVE, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT with setsocketopt() to send heartbeats; and discuss the practice of keep-alive heartbeats in general.</p><p><strong>Experiment setting</strong>:<br><em>OS: Unbutu 16.04</em><br><em>gcc: 5.4.0</em></p><h3>To keep the connection alive</h3><p>One cause of silent connection drop is <em>NAT</em> entry timeout. A <em>NAT</em> entry consisting of the 4-tuple (source address, source port, destination address and destination port) is recorded by a <strong>network</strong> router internally for <strong>address</strong> <strong>translation</strong>. Due to limited memory available to the hardware, the router has to remove the entry belonging to an inactive session after a timeout. As a result, the connection is effectively closed even though neither ends have explicitly issued a FIN nor RST.</p><p>Reconnecting is expensive. An end user has to wait for at least 3xRTT spent by handshakes; and additional logic is required to smoothly restore the UX with the previously interrupted state after the user is back on-line.</p><blockquote><em>In order to avoid the unnecessary handshakes and the RTTs imposed, HTTP adopts KEEP-ALIVE so that the short-lived HTTP sessions can reuse the same established, persistent TCP connection, which is another story.</em></blockquote><p>Next, I will use two programs to illustrate how it works exactly. We look at the code of a server first,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad6da28cdf70e7c252cec1b43fab30bf/href">https://medium.com/media/ad6da28cdf70e7c252cec1b43fab30bf/href</a></iframe><p>For simplicity, I do not apply IO multiplexing so the server can accept connect from 1 client one time.</p><p>the code of client,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d28006427f564166865919610d9786/href">https://medium.com/media/82d28006427f564166865919610d9786/href</a></iframe><p>After setting the socket options mentioned before, the client initiates the TCP handshakes by connect(), and yield the CPU by sleep().</p><blockquote><em>If you are not familiar with network programming (</em><em>socket), please read </em><a href="http://www.cs.rpi.edu/~moorthy/Courses/os98/Pgms/socket.html"><em>this</em></a><em> first.</em></blockquote><p>Next, let’s see the network interaction in action.</p><pre>sudo tcpdump -i wlp3s0 dst net 192.168.1.71 or src net 192.168.1.71 and not dst port 22 and not src port 22</pre><pre>// ========================&gt; start handshakes<br>12:21:42.437163 IP 192.168.1.66.43066 &gt; 192.168.1.71.6666: Flags [S], seq 3002564942, win 29200, options [mss 1460,sackOK,TS val 7961984 ecr 0,nop,wscale 7], length 0<br>12:21:42.439960 IP 192.168.1.71.6666 &gt; 192.168.1.66.43066: Flags [S.], seq 3450454053, ack 3002564943, win 28960, options [mss 1460,sackOK,TS val 2221927 ecr 7961984,nop,wscale 7], length 0<br>12:21:42.440088 IP 192.168.1.66.43066 &gt; 192.168.1.71.6666: Flags [.], ack 1, win 229, options [nop,nop,TS val 7961985 ecr 2221927], length 0<br>// ========================&gt; end handshakes<br>12:21:52.452057 IP 192.168.1.66.43066 &gt; 192.168.1.71.6666: Flags [.], ack 1, win 229, options [nop,nop,TS val 7964488 ecr 2221927], length 0<br>12:21:52.454443 IP 192.168.1.71.6666 &gt; 192.168.1.66.43066: Flags [.], ack 1, win 227, options [nop,nop,TS val 2224431 ecr 7961985], length 0<br>12:22:02.468056 IP 192.168.1.66.43066 &gt; 192.168.1.71.6666: Flags [.], ack 1, win 229, options [nop,nop,TS val 7966992 ecr 2224431], length 0<br>12:22:02.470458 IP 192.168.1.71.6666 &gt; 192.168.1.66.43066: Flags [.], ack 1, win 227, options [nop,nop,TS val 2226935 ecr 7961985], length 0<br>12:22:12.484119 IP 192.168.1.66.43066 &gt; 192.168.1.71.6666: Flags [.], ack 1, win 229, options [nop,nop,TS val 7969496 ecr 2226935], length 0<br>12:22:12.489786 IP 192.168.1.71.6666 &gt; 192.168.1.66.43066: Flags [.], ack 1, win 227, options [nop,nop,TS val 2229440 ecr 7961985], length 0</pre><blockquote><em>Here I removed the irrelevant output of </em><em>ARPs. If you are not familiar with </em><em>tcpdump, please read </em><a href="https://danielmiessler.com/study/tcpdump/"><em>this</em></a><em> first.</em></blockquote><p>With the feet gotten wet, now it’s a good time to explain the heartbeat mechanism,</p><p>1) SO_KEEPALIVE enables (or disables) heartbeat;</p><pre>int flags =1;<br>if (setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&amp;flags, sizeof(flags))) { perror(“ERROR: setsocketopt(), SO_KEEPALIVE”); exit(0); };</pre><p>and</p><p>2) the side with heartbeat enabled (in this example, client) sends empty packets (👁 length 0); and</p><p>3) after received the packets, the other side (server) reply with ACKs (👁 Flags [.]); and</p><p>4) TCP_KEEPIDLE defines the heartbeat frequency (👁 timestamps).</p><pre>flags = 10;<br>if (setsockopt(sfd, SOL_TCP, TCP_KEEPIDLE, (void *)&amp;flags, sizeof(flags))) { perror(“ERROR: setsocketopt(), SO_KEEPIDLE”); exit(0); };</pre><p>Note that throughout the process, the read() is blocked from the server side, which means the heartbeat packets are transparent to the recipient (server).</p><h3>To detect an absent peer</h3><p>Besides <em>NAT</em> entry expiration, a connection can be dropped silently in one way or another (e.g., a loosen cable). It is crucial for a server application to identify such exception in time, so it can release the associated resources, invoke clean-up routines and/or notify other peer clients. This is why sending heartbeats from server-side makes more sense.</p><p>Since our feet is already wet.<br>5) TCP_KEEPINTVL defines the heartbeat frequency when there is no answer from the other side; and<br>6) TCP_KEEPCNT dictates how many unanswered heartbeat will indicate a dropped connection;</p><p>Next we modify the server and client code to test this feature</p><p>in server, we added all the mentioned socket options,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15f250952ecbee41c3cc1526cb07f6fa/href">https://medium.com/media/15f250952ecbee41c3cc1526cb07f6fa/href</a></iframe><p>and client is reduced to</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2020281262662947e0798ed18827c627/href">https://medium.com/media/2020281262662947e0798ed18827c627/href</a></iframe><p>and the tcpdump output (that is executed on server machine, because we are going to unplug the connection from client)</p><pre>// ========================&gt; handshakes are omitted here<br>20:04:12.535386 IP 192.168.1.66.49232 &gt; 192.168.1.71.6666: Flags [.], ack 1, win 229, options [nop,nop,TS val 12312604 ecr 9154395], length 0<br>20:04:22.538591 IP 192.168.1.71.6666 &gt; 192.168.1.66.49232: Flags [.], ack 1, win 227, options [nop,nop,TS val 9161936 ecr 12312604], length 0<br>20:04:22.570817 IP 192.168.1.66.49232 &gt; 192.168.1.71.6666: Flags [.], ack 1, win 229, options [nop,nop,TS val 12315113 ecr 9154395], length 0<br>// ========================&gt; we unplug the network connection here<br>20:04:32.586590 IP 192.168.1.71.6666 &gt; 192.168.1.66.49232: Flags [.], ack 1, win 227, options [nop,nop,TS val 9164448 ecr 12315113], length 0<br>20:04:37.594590 IP 192.168.1.71.6666 &gt; 192.168.1.66.49232: Flags [.], ack 1, win 227, options [nop,nop,TS val 9165700 ecr 12315113], length 0<br>20:04:42.602590 IP 192.168.1.71.6666 &gt; 192.168.1.66.49232: Flags [.], ack 1, win 227, options [nop,nop,TS val 9166952 ecr 12315113], length 0<br>20:04:47.610591 IP 192.168.1.71.6666 &gt; 192.168.1.66.49232: Flags [.], ack 1, win 227, options [nop,nop,TS val 9168204 ecr 12315113], length 0<br>20:04:52.618596 IP 192.168.1.71.6666 &gt; 192.168.1.66.49232: Flags [.], ack 1, win 227, options [nop,nop,TS val 9169456 ecr 12315113], length 0</pre><p>Because we set 5 as the threshold number of unacknowledged packets, and each is 5 seconds apart, (👁 timestamps)</p><pre>flags = 5;<br>if (setsockopt(sfd, SOL_TCP, TCP_KEEPCNT, (void *)&amp;flags, sizeof(flags))) { perror(“ERROR: setsocketopt(), SO_KEEPCNT”); exit(0); };</pre><pre>flags = 5;<br>if (setsockopt(sfd, SOL_TCP, TCP_KEEPINTVL, (void *)&amp;flags, sizeof(flags))) { perror(“ERROR: setsocketopt(), SO_KEEPINTVL”); exit(0); };</pre><p>after 5 heartbeats that are unanswered from the client, the</p><pre>n = read(rfd, buffer, BUF_SIZE);</pre><p>is unblocked with an n indicating a closed connection. So that the process of breaking a connection, unlike heartbeat itself, notifies the monitor (server in this case) which in turn can trigger the mentioned actions to finalize a broken connection.</p><h3>Considerations</h3><h4>When heartbeat should not be used</h4><p>In mobile network, periodic data transfer will unnecessarily keep the radio active. When this happens in background, the application drains the battery fast and surprises users. So I would go for the extra miles preparing to reconnecting in such case.</p><h4>When heartbeat could not be used</h4><p>For a back-end with heavy traffic, the packets generated by business logic alone can be indicators of connectivity. In such case, I would make the server drop a connection after a client has not been sending packets for a long period of time.</p><p>Alternatively, if I need to further reduce false-positive, I could activate the heartbeat mechanism (through setsockopt()) only for a prolonged silence of a client. It is worth noting that when modifying socket option midway, setsockopt() should work on the file descriptor returned by the accept(), i.e.,rdf which represents a established connection. (and other settings will be “inherited” from sdf)</p><h4>System wide setting</h4><p>Some of the discussed socket options can also be set using procfs and sysctl.</p><p>TCP_KEEPIDLE -&gt; /net/ipv4/tcp_keepalive_time<br>TCP_KEEPCNT -&gt; /net/ipv4/tcp_keepalive_probes<br>TCP_KEEPINTVL -&gt; /net/ipv4/tcp_keepalive_intvl</p><h3>References</h3><ul><li><a href="https://hpbn.co/">High Performance Browser Networking (O&#39;Reilly)</a></li><li><a href="https://www.tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO/">TCP Keepalive HOWTO</a></li><li><a href="https://notes.shichao.io/unp/ch7/#so_keepalive-socket-option">Chapter 7. Socket Options - Shichao&#39;s Notes</a></li></ul><p><em>Originally published at </em><a href="https://holmeshe.me/network-essentials-setsockopt-SO_KEEPALIVE/"><em>holmeshe.me</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebbd00f9281f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/backend/setsockopt-so-keepalive-and-heartbeats-ebbd00f9281f">setsockopt, SO_KEEPALIVE and Heartbeats</a> was originally published in <a href="https://medium.com/backend">backend</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Back End Applications, This is How I Break Up]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/backend/this-is-how-i-break-up-and-get-started-with-microservice-acf3bf6636b1?source=rss----57d84e1e0748---4"><img src="https://cdn-images-1.medium.com/max/2600/1*6pr9WzQHduCbwDhIYSy0Iw.jpeg" width="4288"></a></p><p class="medium-feed-snippet">My previous post concluded with approaches to enhance the success rate of all sorts of dates. This one will discuss the next step&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/backend/this-is-how-i-break-up-and-get-started-with-microservice-acf3bf6636b1?source=rss----57d84e1e0748---4">Continue reading on backend »</a></p></div>]]></description>
            <link>https://medium.com/backend/this-is-how-i-break-up-and-get-started-with-microservice-acf3bf6636b1?source=rss----57d84e1e0748---4</link>
            <guid isPermaLink="false">https://medium.com/p/acf3bf6636b1</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[soa]]></category>
            <dc:creator><![CDATA[Holmes He]]></dc:creator>
            <pubDate>Fri, 15 Dec 2017 11:22:48 GMT</pubDate>
            <atom:updated>2018-05-25T11:30:44.152Z</atom:updated>
        </item>
    </channel>
</rss>