<?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 Gowtham Tamilarasan on Medium]]></title>
        <description><![CDATA[Stories by Gowtham Tamilarasan on Medium]]></description>
        <link>https://medium.com/@gtamilarasan?source=rss-5bee897d1a00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lkZ_f9hKflkGWU_Q4FUfFg.jpeg</url>
            <title>Stories by Gowtham Tamilarasan on Medium</title>
            <link>https://medium.com/@gtamilarasan?source=rss-5bee897d1a00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:46:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gtamilarasan/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[Context Switching Performance — User vs Kernel modes]]></title>
            <link>https://medium.com/@gtamilarasan/context-switching-performance-user-vs-kernel-modes-0984c61092bc?source=rss-5bee897d1a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/0984c61092bc</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Gowtham Tamilarasan]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 04:09:24 GMT</pubDate>
            <atom:updated>2024-12-10T04:09:24.096Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context Switching Performance — User vs Kernel modes</h3><p>The process of moving a CPU execution from one process to another process is generally called a context switch. A process can run in two modes: user mode with limited access, and kernel mode with privileged access, switching between these modes is also a context switch.</p><p>A process typically runs in restricted user mode, where it has limited access to the resources available in the system. To access any protected resources, such as hardwares, it has to do it through the kernel via syscalls. Executing a syscall will transition the process from user mode to kernel mode.</p><p>For example, if a program wants to read from a file like below, it has to do it via the <strong><em>open()</em></strong>, and <strong><em>read()</em></strong> syscall.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> fd, err := os.Open(&quot;/tmp/secret&quot;) // Open syscall<br> if err != nil {<br>  fmt.Println(&quot;Failed to open file, reason: %s&quot;, err)<br>  return<br> }<br> var secret = make([]byte, 100)<br> _, err = fd.Read(secret) // Read syscall<br> if err != nil {<br>  fmt.Println(&quot;Failed to read file, reason: %s&quot;, err)<br>  return<br> }<br> fmt.Println(&quot;Secret: %s&quot;, string(secret))<br>}</pre><p>Instead of changing the CPU execution context from one process to another in a regular context switch, here, a process will switch from executing a user program to the kernel code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*GQqrEB7uKxCH-u8H" /></figure><p>In my <a href="https://medium.com/@gtamilarasan/context-switching-performance-threads-vs-processes-6a1b5d2c9954">previous blog post</a>, I explained the overhead involved in context switching between two different processes. If you haven’t read it yet, I recommend reading it. The overhead in context switching between user and kernel mode is relatively nominal.</p><p>Unlike a context switch between processes, the user kernel mode switch doesn’t require a memory context change, and hence it avoids the TLB cache flushes. This is because every process has kernel section mapped to its virtual memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEmoFxMQGXroWvRSG5MB9g.png" /></figure><p>The higher end of a process’s virtual memory address has a reserved space for kernel section. All processes in the system have the kernel code mapped to this exact same virtual address. This virtual address space is mapped to the physical memory shared by all processes, so the kernel is loaded into the memory only once. The kernel memory space can only be accessed in the kernel mode.</p><p>Here’s what happens during a mode switch:</p><p><strong>1. Saving the state:</strong> The running process’s state information from CPU registers, such as the program counter, stack pointer are saved in the memory in a special per process data structure called kernel stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GUpCu9ZgOpVraHf8" /></figure><p><strong>2. Mode Switch:</strong> The CPU then transitions to kernel mode, allowing the process to access and execute kernel routines in the kernel section of its virtual memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MMGjo3c2jPRDdwC4" /></figure><p><strong>3. Restoring the state:</strong> After executing the kernel routines, the process returns to user mode by restoring its previous execution state from memory to the CPU registers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kosox-TF9GAG5VsP" /></figure><p>Even though the cost of a context switch between user kernel modes are nominal when compared to an inter process context switch, frequent mode switches can still affect a system’s overall performance because:</p><ol><li>CPU cycles are consumed by context switching instead of executing any actual programs. If the system runs many CPU bound processes, some cpu cycles are wasted for context switches.</li><li>Time required to save and restore the state information from memory will add to the latency.</li></ol><h3>Work Story</h3><p>In one of my previous jobs, we wanted to monitor changes to important files in real time for security reasons. The contents of those important files were managed by a configuration management system that ensured the integrity of the files. We could have monitored the file changes through the logs of the config management tool, but since it runs periodically (every 30 mins or so) any changes made and reverted between those periodic runs will go unnoticed. For instance, imagine a malicious actor modifying an access definition file, providing access to an unauthorized entity, and then reverting it before the config management tool detects and logs it.</p><p>At that time, there were not many tools available in the market that could do this for us, so we had to implement our own solution. We wrote a golang agent using the <a href="https://github.com/fsnotify/fsnotify">fsnotify</a> library to monitor changes to certain important files and directories in real time. Fsnotify library, in turn, uses the Linux <a href="https://man7.org/linux/man-pages/man7/inotify.7.html">inotify</a> syscalls.</p><p>We were happy with this solution after our initial tests and began gradually rolling it out to our infrastructure. Everything worked fine until it was released to one of our data store servers. The performance of those servers was affected immediately and downstream applications started noticing increased latency. It turned out the performance problem was caused by our monitoring agent triggering frequent user kernel mode switches.</p><p>Once a file is monitored with inotify, it sends the change events to a file descriptor(FD). The agent has to keep reading that FD infinitely in a loop to capture all the changes. Everytime the agent reads from this FD, the agent process switches from user to kernel mode. There were far too many such events created in the data store servers, causing the agent process to frequently switch between the user and kernel modes.</p><p>The nominal overhead with user kernel mode switches, which I discussed earlier, built up to a point where it started affecting the performance of the data store application running on the servers.</p><p>So how did we solve it?</p><p>We identified the problem was because of the mode switches, so we had the option to either monitor the file changes from user space or from kernel space. There is no way to do this monitoring in just user mode, because monitoring changes to a file is a privileged action that is not allowed in user mode. Could we do this entirely in kernel space? Yes! Enter <a href="https://ebpf.io/what-is-ebpf/">eBPF</a>.</p><blockquote>“eBPF is a revolutionary technology with origins in the Linux kernel that can run sandboxed programs in a privileged context such as the operating system kernel. It is used to safely and efficiently extend the capabilities of the kernel without requiring to change kernel source code or load kernel modules.</blockquote><p>We ended up writing an eBPF program that runs inside the kernel to monitor the file changes by attaching it to the file change syscalls, such as write. Instead of reading the change events one at a time in an infinite loop, we read the change events periodically once in a few seconds from the user program. This new solution no longer affected the performance of the data store server.</p><p>While many of us may never encounter such issues, understanding these nitty gritty of operating system internals can help us troubleshoot rare occurrences like the one I experienced.</p><p>I hope you enjoyed reading this article and learned something new today. If you did, please consider leaving a clap or comment; it will encourage me to write more such content and continue sharing my learnings with you all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0984c61092bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Switching Performance — Threads vs Processes]]></title>
            <link>https://medium.com/@gtamilarasan/context-switching-performance-threads-vs-processes-6a1b5d2c9954?source=rss-5bee897d1a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a1b5d2c9954</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Gowtham Tamilarasan]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 01:13:55 GMT</pubDate>
            <atom:updated>2025-01-21T13:13:20.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context Switching Performance — Threads vs Processes</h3><p>One of the core features of operating systems is multitasking — the ability to run multiple tasks in parallel on a CPU. These days, computers have multiple CPU cores to run tasks concurrently, even then, the number of tasks executed on a computer is far more than the number of CPUs it has. All these tasks are executed in parallel by the operating system by allotting each task a slice of CPU time, providing users with the illusion that all the tasks are executed concurrently.</p><p>After its time slice, when a running process is replaced by another process, the operating system stores the state of that running process in memory so that it can resume from where it left. The process of storing the state of a running process and replacing it with another process from its previous state is called context switching.</p><p>Context switching also occurs when handling an interrupt or when a process switches between user mode and kernel mode during execution of system calls like reading a file.</p><p>By default, in the Linux operating system, each process has a single thread called the main thread. A process can have more than one thread, and switching between these threads also involves context switching.</p><p>Context switching doesn’t come without cost, there’s some performance overhead involved. This overhead varies based on several factors such as size of the state to store and retrieve, processes involved — intra-process threads or not, etc.</p><p>Context switching between threads(of same process) has less overhead than context switching between two processes. In this blog post, let’s look into the performance overhead difference between processes and threads in action, and why.</p><p>Let’s first see what actually happens during context switching.</p><ol><li><strong>Saving the state</strong>: The running process’s state information from CPU registers, such as the program counter, stack pointer, virtual memory page table pointer are saved in the process control block(PCB). Every process will have its own PCB stored in memory managed by the kernel.</li><li><strong>Flushing cache</strong>: Translation Lookaside Buffer(TLB) entries for the process are invalidated. TLB is a cache in the memory management unit that helps with faster translation of virtual page addresses to the physical frame addresses. Different processes will have the same virtual address but might translate to different physical addresses, so this cache invalidation is essential.</li><li><strong>Restoring the state</strong>: State of the new process is read from its PCB and restored in the CPU registers.</li></ol><p>Time to see this in action.</p><p>We need a task that does a lot of cpu activity to observe context switching performance overhead. To do that let’s write a go program to generate prime numbers. We will then run it concurrently with multiple threads and processes to see the difference.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>const (<br> LIMIT = 30000<br>)<br><br>func exhaust_cpu(limit int) {<br> primes := 1<br> for i := 3; i &lt;= limit; i += 1 {<br>  divisible := 1<br>  for j := 2; j &lt;= limit; j++ {<br>   if i%j == 0 {<br>    divisible += 1<br>   }<br>  }<br>  if divisible == 2 {<br>   primes += 1<br>  }<br> }<br> fmt.Println(&quot;Primes: &quot;, primes)<br>}<br><br>func main() {<br> exhaust_cpu(LIMIT)<br>}</pre><p>Let’s use goroutines to run the program in 5 threads.</p><pre>$ cat threads.go<br>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;runtime&quot;<br>  &quot;sync&quot;<br>)<br><br>const (<br>  LIMIT = 30000<br>  THREADS = 5<br>)<br><br>func exhaust_cpu(wg *sync.WaitGroup, limit int){<br>  defer wg.Done()<br>  primes := 1<br>  for i:=3;i&lt;=limit;i+=1 {<br>    divisible := 1<br>    for j:=2;j&lt;=limit;j++ {<br>      if i%j == 0 {<br>        divisible += 1<br>      }<br>    }<br>    if divisible == 2 {<br>     primes += 1<br>    }<br>  }<br>  fmt.Println(&quot;Primes: &quot;, primes)<br>}<br><br>func main() {<br>  runtime.GOMAXPROCS(THREADS)<br>  wg := sync.WaitGroup{}<br>  for i:=0;i&lt;THREADS;i+=1 {<br>    go exhaust_cpu(&amp;wg, LIMIT)<br>    wg.Add(1)<br>  }<br>  wg.Wait()<br>}</pre><p>To run it in 5 processes, let’s set the individual process threads count to 1, and use a shell script to start 5 processes in the background and wait for it to complete.</p><pre># set the threads count to 1 for individual processes<br>$ diff threads.go procs.go<br>&lt;   THREADS = 5<br>---<br>&gt;   THREADS = 1<br><br>$ cat run_procs.sh<br>PROCS_COUNT=${1:-5}<br>go build procs.go<br>for i in $(seq 1 ${PROCS_COUNT})<br>do<br>  # Run process in background<br>  ./procs &amp;<br>done<br># Wait for background processes to complete<br>wait<br>echo &quot;Waited for all procs&quot;</pre><p>I am executing these programs in a multi core system, so to make context switching happen frequently, I will pin the processes to one of the CPU cores — core 0 using <a href="https://man7.org/linux/man-pages/man1/taskset.1.html">taskset</a> utility.</p><pre># Run threads on core 0<br>go build threads.go<br>time taskset -c 0 ./threads<br><br># Run process<br>grep taskset run_procs.sh<br> time  taskset -c 0 ./procs &amp;</pre><p>You can see below the threads are running only on core 0 from the `htop` output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4KbXW0oPCEyWi-AN" /></figure><p>In linux, threads of same processes get different PIDs, so do not confuse them as different processes.</p><pre># See the threads under the process in proc file system<br>ls /proc/10838/task/<br>10838 10839 10840 10841 10842 10843</pre><p>Let’s take a look at the time required for these programs to run.</p><pre>$ time taskset -c 0 ./threads<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br><br>real 0m43.525s<br>user 0m43.488s<br>sys 0m0.028s ****************<br><br>$ time bash run_procs.sh<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br><br>real 0m43.643s<br>user 0m8.728s<br>sys 0m0.008s<br><br><br>real 0m43.654s<br>user 0m8.712s<br>sys 0m0.016s<br><br><br>real 0m43.660s<br>user 0m8.724s<br>sys 0m0.004s<br><br>real 0m43.660s<br>user 0m8.728s<br>sys 0m0.000s<br><br>real 0m43.660s<br>user 0m8.720s<br>sys 0m0.012s<br><br>Waited for all procs<br><br>real 0m43.823s<br>user 0m43.776s<br>sys 0m0.072s ****************</pre><p>There is not much difference in the time taken to run the program in 5 threads and 5 processes(~1% diff). But didn’t I tell you the context switching overhead is less for threads?</p><p>I have intentionally left out one crucial piece of information earlier. Threads within a process share the same virtual memory space, so during context switching between those threads, page table pointer change, and TLB cache invalidation steps are skipped, thus reducing the overhead.</p><p>Since these processes do not use much memory, there’s not many entries in TLB, hence the overhead of TLB cache invalidation is not seen here.</p><p>So let’s make this program consume some memory.</p><pre>$ cat threads.go<br>package main<br>…<br>…<br>func exhaust_cpu(wg *sync.WaitGroup, limit int, mlist []int){<br>  defer wg.Done()<br>  primes := 1<br>  // Access the memory, so its virtual addresses gets cached in TLB<br>  for i:=3;i&lt;=limit;i+=1 {<br>    for i := range mlist {<br>      mlist[i] = 100<br>    }<br>    divisible := 1<br>    …<br>    … <br>  fmt.Println(&quot;Primes: &quot;, primes)<br>}<br><br>func main() {<br>  // Declare a large chunk of memory<br>  mlist := make([]int, 1000000)<br>  for i:=0;i&lt;THREADS;i+=1 {<br>    go exhaust_cpu(&amp;wg, LIMIT)<br>    …<br>  wg.Wait()<br>}<br><br>$ diff threads.go procs.go<br>13c13<br>&lt;   THREADS = 10<br>---<br>&gt;   THREADS = 1</pre><pre>$ time taskset -c 0 ./threads<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br><br>real 2m19.336s<br>user 2m19.256s<br>sys 0m0.072s *******************<br><br>$ time bash run_procs.sh<br>Primes:  3245<br>Primes:  3245<br><br>real 2m26.499s<br>user 0m29.156s<br>sys 0m0.120s<br><br>real 2m26.521s<br>user 0m29.144s<br>sys 0m0.148s<br><br>… <br>Waited for all procs<br><br>real 2m26.692s<br>user 2m25.920s<br>sys 0m0.784s *******************</pre><p>Now you can see the difference in runtime. Take note of the `<strong>sys`</strong> time in the output which includes the context switching time — 0m0.072s for threads, and 0m0.784s for processes. But here all 5 threads share the one 1M list, but the processes each have a separate 1M integer list. This would take 5X more time for the processes to access the memory allocated. So we need to allocate the same amount of memory for each thread as processes to make a fair comparison.</p><pre>$ diff threads.go.old threads.go<br>38c38,41<br>&lt;   mlist := make([]int, 1000000)<br>—<br>&gt;  // 1M integer list for each thread<br>&gt;   mlist := make([][]int, THREADS)<br>&gt;   for i := 0; i &lt; THREADS; i += 1 {<br>&gt;     mlist[i] = make([]int, 1000000)<br>&gt;   }<br>42c45<br>&lt;     go exhaust_cpu(&amp;wg, LIMIT, mlist)<br>---<br>&gt;     go exhaust_cpu(&amp;wg, LIMIT, mlist[i])</pre><pre>$ time taskset -c 0 ./threads<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br>Primes:  3245<br><br>real 2m26.029s<br>user 2m25.932s<br>sys 0m0.084s *******************<br><br>$ time bash run_procs.sh<br>Primes:  3245<br>Primes:  3245<br>… <br><br>real 2m26.366s<br>user 0m29.136s<br>sys 0m0.180s<br><br>real 2m26.442s<br>user 0m29.188s<br>sys 0m0.104s<br>…<br>Waited for all procs<br><br>real 2m26.601s<br>user 2m25.880s<br>sys 0m0.740s *******************</pre><p>Now we gave each thread and process the same amount of memory, and the runtime for processes is more than the threads. The <strong>sys </strong>time for running threads program is <strong>0.084s </strong>for all 5 threads, and for processes, every process takes <strong>0.100+ </strong>seconds totalling to <strong>0.740s. </strong>This shows the context switching overhead difference between processes and threads.</p><p>In conclusion, understanding the performance overhead of context switching between processes and threads is crucial for optimizing applications that require extensive multitasking. As demonstrated, context switching between threads of the same process is generally more efficient than between threads of different processes due their shared memory nature. However, this doesn’t mean you have to always choose threads for multi-tasking. Sharing memory also brings in other challenges like race conditions while accessing shared memory objects. Some multitasking applications might work better with processes than threads based on its architecture, and complexity. By carefully considering these factors, we can make an informed decision on whether to use threads or processes.</p><p>In <a href="https://medium.com/@gtamilarasan/context-switching-performance-user-vs-kernel-modes-0984c61092bc">another blog post</a>, I will write about the effect of context switching between user and kernel modes.</p><p>I hope you enjoyed reading this article and learned something new today. If you did, please consider leaving a clap or comment; it will encourage me to write more such content and continue sharing my learnings with you all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a1b5d2c9954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Closer Look at HTTP/3 & QUIC]]></title>
            <link>https://medium.com/@gtamilarasan/a-closer-look-at-http3-quic-1b2b97a5cd50?source=rss-5bee897d1a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b2b97a5cd50</guid>
            <category><![CDATA[udp]]></category>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Gowtham Tamilarasan]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 05:13:47 GMT</pubDate>
            <atom:updated>2025-01-20T03:57:54.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Hypertext Transfer Protocol(HTTP) is the basis for the world wide web. It is a set of rules used by clients like web browsers and web servers to exchange data over the internet. From scrolling through instagram feeds to making online transactions in the bank, we use HTTP everyday. As the significance and use of HTTP has grown tremendously over the years, HTTP has also been evolving to become faster, efficient and secure.</p><p>We now have three major versions of HTTP — 1, 2, and the latest being 3. In this article, we will take a closer look at the improvements made to HTTP/3, most importantly the change in transport layer protocol from TCP to QUIC which makes it more faster and secure.</p><h3>A brief history of HTTP/1 and HTTP/2</h3><p>The older versions of HTTP use TCP protocol in the transport layer. In HTTP/1, clients could only make one request at a time in a TCP connection, and there is a limit to the number of concurrent TCP connections a browser can establish per domain. This limit is 6 for browsers, such as Google Chrome and Mozilla Firefox. If a website had to load more than 6 resources, it may not be done concurrently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*pHzP03MxM0_5aqxH" /><figcaption><em>(HTTP/1 request flow)</em></figcaption></figure><p>Establishing a TCP connection involves some overhead, if HTTPS is used, which is most often the case, each connection has to spend some more time securing it through the TLS protocol. All this slowed down the load time of websites, as modern websites need to load several resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*X-tKzKFtMp2UIiuI" /><figcaption><em>(HTTP/2 request flow)</em></figcaption></figure><p>HTTP/2 addressed this problem by offering multiplexed streams in a TCP connection. Each request is sent in a stream allowing clients to make multiple parallel requests in a single TCP connection. This was a major performance boost in HTTP/2 that made websites load faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*5fQIypW1BhvdCyhP" /><figcaption><em>(HTTP/2 packet loss)</em></figcaption></figure><p>It still has another problem called head-of-line blocking(HOL). Streams are known to HTTP but not to TCP. Individual frames of different streams are numbered and transmitted as ordered segments in TCP. If a segment gets lost in transit, TCP will resend that after a timeout, blocking all other segments in the connection. So if a website had to load three resources(an image, a CSS file, and a JS file) in a single TCP connection, a packet loss for one of the resource requests will block the other two requests.</p><h3>HTTP/3 and QUIC</h3><p>Quick UDP Internet Connections(QUIC), pronounced as quick, is the transport layer protocol used by HTTP/3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*I0WoH38E5qeOF1iH" /><figcaption><em>(QUIC UDP packet)</em></figcaption></figure><p>HTTP/3 also offers multiplexed streams like HTTP/2 using QUIC in the transport layer. Data in a QUIC stream is split into smaller chunks called frames and transmitted in UDP packets. Frames inside a UDP packet will contain the sequence number and ID of a stream, so the receiver can reorder them if it is received out of order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*xsIhpEyLt9_Y_Jh8" /><figcaption><em>(HTTP/3 QUIC packet loss)</em></figcaption></figure><h4>No Head Of Line Blocking</h4><p>If a packet gets lost, QUIC will re-transmit it after a timeout just like TCP, but it won’t affect other streams as shown in the diagram above.</p><h3>Faster connection establishment</h3><h4>1 RTT Connection Establishment</h4><p>HTTP/3 and QUIC offer 1 Round Trip Time(1-RTT) connection establishment and 0-RTT connection resumption, while HTTP/2 requires 3 RTT for a secure connection establishment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*NzdidW6gOv1LygE5" /><figcaption><em>(HTTP/2 3-RTT secure connection establishment)</em></figcaption></figure><p>As shown above, in HTTP/2, the first 3 packet exchanges are for TCP connection establishment, and the last 4 packet exchanges are for securing the connection using TLS 1.2. The third packet for TCP ACK to the server is combined with the TLS ClientHello message. So in total a secure connection establishment in HTTP/2 with TLS1.2 requires 6 packet exchanges or 3-RTT.</p><p>TLS is embedded into QUIC making the connections secure by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*yrWmmqAzDDkCq6rP" /><figcaption><em>(HTTP/3 1-RTT secure connection establishment)</em></figcaption></figure><p>Unlike HTTP/2 where connection establishment, and securing the connection(HTTPS) are two separate sequential steps, HTTP/3 combines them into one single step. By using UDP instead of TCP, it eliminates the 3 way handshake, and by using TLS1.3, it reduces TLS handshakes from 2-RTT to 1-RTT.</p><h4>Enhanced Security</h4><p>TLS1.3 provides greater security by deprecating several weak cipher suite options available in the previous version and standardising on only 2 different key exchange options — ECDHE with X25519 or P-256. In TLS1.2 client and server use 1 RTT to just negotiate and agree on the key sharing algorithm, after that they both share their public parts and arrive at a common shared secret. The shared secret is then used for encrypting the connection. But In TLS 1.3 there is only one key sharing option — ECDHE, servers will typically support both the parameters X25519 and P-256 of ECDHE, so the client will select one of them and send its public part along with the initial message. In an unlikely situation where the server doesn’t support the selected ECDHE parameter, it will request the client to retry with the other parameter, in such a rare case connection establishment takes 2 RTT. You can learn more about the key exchanges and improvements in TLS 1.3 from this <a href="https://blog.cloudflare.com/rfc-8446-aka-tls-1-3/">article</a>.</p><h4>0-RTT Connection Resumption</h4><p>TLS1.3 allows encryption using a Pre-Shared-Key(PSK). After a successful connection establishment, client and server can share a key and store it for a later use. The key exchange can also be done out of band. For future connections to the same server, clients can then choose to encrypt and send some initial data using the pre-shared-secret in the first packet to the server. Only the initial data from client to the server is encrypted with the PSK, it will follow the 1-RTT handshake described above to arrive at a new secret for the rest of the connection to provide forward secrecy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*cnryDuCX01R021at" /><figcaption><em>(HTTP/3 connection resumption)</em></figcaption></figure><p>This greatly improves the performance when reconnecting to the same server, but has a downside to it; An attacker can intercept the packet and replay it at any time. Imagine the initial client data sent is for a banking application to register a transaction of 100$, the debiter will lose money if the packets are replayed. So the recommendation for servers is to accept the initial PSK encrypted data only for non state changing requests, in REST terms, only for GET requests.</p><h3>Connection Migration</h3><p>QUIC can persist a connection across network changes, unlike TCP which requires the same endpoint(IP and port) throughout the connection. The endpoint can change when a NAT binding of a client changes, or when a user switches between WiFi and mobile data on their phone. QUIC allows migration of connections from one endpoint to another except during connection establishment phase where the same endpoint is required for security.</p><p>To verify the new endpoint is owned by the client, and source IP is not spoofed, the server will do a path validation. Path validation is done by sending some arbitrary data to the client and verifying the client can decrypt and return the same. No man in the middle can see that arbitrary data because it is encrypted with the shared session secret obtained during connection establishment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*iCRbH0dk0yfjRXYD8KoeNA.png" /><figcaption><em>(HTTP/3 connection migration)</em></figcaption></figure><p>The connection ID will change after a successful connection migration. This is to make sure no one other than the client and server can associate a connection across different endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a46lt-5yE-E-EaLr" /></figure><p>More than 28% of websites use HTTP/3 today. There’s no doubt this percent will increase in the future, but it’s not going to be an easy walk. HTTP/2 migration from HTTP/1 was relatively easier since the underlying transport protocol TCP was not changed. HTTP/3 adoption goes beyond the client and server supporting it. Different network components such as load balancers and firewalls in the request path over the internet need to support QUIC. This, in my opinion, is the key challenge for HTTP/3 migration.</p><p>I hope you enjoyed reading this article and learned something new today. If you did, please consider leaving a clap or comment; it will encourage me to write more such content and continue sharing my learnings with you all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b2b97a5cd50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Network Throttling Mystery]]></title>
            <link>https://medium.com/@gtamilarasan/aws-network-throttling-mystery-8e14643b3f3d?source=rss-5bee897d1a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e14643b3f3d</guid>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[elasticache]]></category>
            <dc:creator><![CDATA[Gowtham Tamilarasan]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 07:11:18 GMT</pubDate>
            <atom:updated>2025-01-20T03:58:28.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>AWS imposes various limits on the resources we rent, one such limit is the network bandwidth utilisation. For this blog post, we will look at the network bandwidth limits applied on Elasticache nodes, and the hidden specifics behind it.</p><p>The <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/memory-optimized-instances.html#memory-network-perf">network bandwidth you get</a> is based on the instance type you use. For certain instance types, you get a guaranteed baseline bandwidth, as well as a burstable bandwidth on a best effort basis. For example, `r6g.2xlarge` instance type gets a baseline bandwidth of 2.5Gbps, and a burstable bandwidth of 10 Gbps(as of this writing). If the utilisation of a cache node goes beyond these limits AWS will throttle packets by queuing or dropping them.</p><p>To observe the network bandwidth utilisation of the cluster nodes, AWS provides the following <a href="https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/CacheMetrics.HostLevel.html">cache node level metrics</a>.</p><ol><li>NetworkBytesIn, NetworkBytesOut — Network bandwidth utilization of a node.</li><li>NetworkBandwidthInAllowanceExceeded, NetworkBandwidthOutAllowanceExceeded — Number of packets throttled.</li></ol><h3>Hidden Specifics</h3><p>The network bandwidth limit is applied on a per second basis i.e. bytes per second. But the network utilization metrics published are for a <a href="https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/CacheMetrics.ChoosingStatisticsAndPeriods.html">60 second period</a> i.e. bytes per minute.</p><p>Different resolutions for these metrics can hide micro bursts occurring in network utilization. Let’s say the utilization metric value reported is 300M bytes per minute, and the utilization was 250M bytes in one second, and 50M bytes in total for the remaining 59 seconds in a minute. This is called a microburst.</p><h3>Work Story</h3><p>AWS throttled one of the Elasticache clusters our team manages for breaching network bandwidth limits. That’s when I learned these specifics.</p><p>AWS recommends monitoring the `NetworkBandwidthAllowanceExceeded` metric to detect any network bandwidth throttling. We had this metric value non zero consistently for one of our Elasticache redis clusters. Sometimes causing negative impact to the application.</p><p>When incoming packets are dropped by throttling, the application will have to retransmit the dropped packets. It will cause increase in latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i2X9QOHbFQPGeqAo" /></figure><p>Above graph shows throttling. However, the network utilization graph below did not show any breach of bandwidth limits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rUd4G0W60c0CqPei" /></figure><p>The node type `r6g.2xlarge` we used had 2.5Gbps or 3125 MBps base line bandwidth. Our utilization graph showed a peak value of 64 MBps when packets were throttled for breaching network bandwidth limits. As you can see in the above diagram, our consumption was ~5 times less than the limit.</p><p>We reached out to AWS support to understand the reason. They confirmed network throttling on our cluster nodes, and suspected micro bursting as the reason. That could be true because we convert minutely usage rate metrics(NetworkBytesIn, NetworkBytesOut) into secondly rate by doing a divide by 60. Dividing by 60 can indeed mask brief spikes exceeding the limits.</p><h3>Validation</h3><p>AWS didn’t give us any evidence for micro bursts though. I didn’t just want to take the word from AWS. As a curious engineer, I decided to validate that micro bursting was actually happening.</p><p>This is not an EC2 instance where we can run monitoring tools like SAR to observe granular network bandwidth usage. Instances under AWS managed Elasticache service are not directly accessible by us.</p><p>So how did I validate that, then?</p><h3>Making sure baseline bandwidth is usable</h3><p>I first wanted to verify the baseline bandwidth is usable without any throttling. For that, I spun up a test cluster and ran load tests against that cluster using the <a href="https://redis.io/docs/management/optimization/benchmarks/">redis-benchmark</a> tool.</p><p>The test cluster used cache node type `m5.xlarge` with a baseline network bandwidth of 1.25 Gb/s or 156 MB/s.</p><p>To reproduce throttling, I ran a load test with throughput of ~240 MB/s. This is above the baseline bandwidth of 156 MB/s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gki9jL_LKggpXZw8" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eeVPGzM8DZaY_8mr" /></figure><p>As expected, some packets were throttled as shown above.</p><p>To verify the baseline bandwidth was usable without throttling, I ran another load test with throughput of ~120 MB/s, just less than the baseline bandwidth of 156 MB/s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8RrQaMuwyP7d5M4C" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z0rQKc3MuTLmNONR" /></figure><p>This time, there was no packet drop.</p><p>The load test concluded that the baseline network bandwidth was indeed usable without any throttling.</p><h3>Microburst evidence</h3><p>Since there’s no easy way to track per second network utilization at Elasticache node end, I decided to validate it at the redis client end. At the application EC2 instance.</p><p>I captured all the packets transmitted from the load test ec2 instance to the test cluster, using tcpdump.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*S2d2E55hzGg-PqII" /></figure><p>The throughput between the load test ec2 instance and Elasticache node was almost always consistent. There were no spikes reflecting micro bursts.</p><p>A similar packet capture was taken at the EC2 instance of application that talks to the affected production cluster.</p><p>The following graph shows the throughput between one of the application ec2 instances and Elasticache node experiencing throttling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*NpJOXLkVttg0ImxE" /></figure><p>When we compare this application throughput (bits/s) with the load test, we can clearly see sporadic data transfers.</p><p>As shown in the graph above, in a period of ~2 minutes, data transfer happened only for a 4–5 seconds period, there was almost no transfer at other times. Thus confirming the microburst.</p><p>To overcome this problem, we considered a couple ofbelow options:</p><ol><li>Reading from replica nodes. The application was using the primary node for both reading and writing. Sending read requests to replicas will distribute the throughput better across all cluster nodes.</li><li>Compress the data before storing in the cluster. This will reduce throughput bandwidth but increase cpu utilization and latency.</li></ol><p>Scaling the cluster is another option, but why spend more money when you don’t really have to.</p><p>Have you encountered similar challenges in your AWS deployments? What did you do to overcome them? Let me know in the comments.</p><p>I hope you enjoyed reading this article and learned something new today. If you did, please consider leaving a clap or comment; it will encourage me to write more such content and continue sharing my learnings with you all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e14643b3f3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you ever forget things?]]></title>
            <link>https://medium.com/@gtamilarasan/do-you-ever-forget-things-d6d391b7523b?source=rss-5bee897d1a00------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6d391b7523b</guid>
            <category><![CDATA[habit-building]]></category>
            <category><![CDATA[reminder]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Gowtham Tamilarasan]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 12:09:08 GMT</pubDate>
            <atom:updated>2023-10-05T12:09:08.690Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you often forget some of the meeting discussions?</p><p>Do you tell your friend you will check something for them but forget it completely?</p><p>Do you miss paying your credit card bill on time?</p><p>Is it because you try to keep everything in your mind? If the answer is yes, you will find this article super useful. If the answer is no, you might still find an easier way to keep track of everything.</p><p>Until a few years back, I tried to remember everything in my mind. Whether it was meeting discussions, or transferring money to parents, or something my manager asked me to check on later. I was not very good at remembering everything, unlike my brother who still remembers our small childhood fights. As a result, I missed many things I should have done.</p><p>As I started to miss things, I tried harder to remember. It didn’t help much. In fact, it made me anxious, often trying to recollect the pending things I had to do. I felt pressured thinking about not forgetting anything. The consequence of it was that I was focusing less on the work at hand.</p><p>It is until you realise not everyone can remember everything, and you are one of them. Then you start to look for alternate ways. That’s when I found the trick of taking notes.</p><p>In the beginning, I started taking notes in my notebook to capture meeting discussion points and action items, and to-do items for the day. This made my day easier at work.</p><p>Later I upgraded to taking notes in an app so I don’t have to carry my notebook everywhere. My personal favorite is the Google Keep app. You can use it with an app on your mobile, as well as on your laptop in a web browser. It syncs the notes across all your devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4HMEW0qw1oLb4vi1" /></figure><p>Keeping notes digital is actually better in certain ways. Instead of keeping dozens of articles open in my browser which I often close before reading many of them. I can copy the links to my “Read Later” notes section and not lose it.</p><p>These days I use it not only for work, but also in my personal life. I use it to create checklists for my upcoming travels, groceries to buy, personal to-do list, recipes, and ideas that strike me from time to time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*N647Qlo8W093C0vt" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*vWONaQP6Aex61uYE" /></figure><p>Google Keep is integrated with Google Calendar, so I don’t have to open the app frequently and check if I have anything to do. It can notify me when it’s time to transfer money to parents, pay credit card bills, and drink water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*ebrZR5VZ0Hz_sBpw" /></figure><p>I miss things very rarely these days. Thanks to the habit of taking notes.</p><p>There may be better apps out there than Google Keep. My intention is to promote the idea of taking notes and share how useful it has been for me.</p><p>This simple app made my life so much easier than before. I hope it does the same to some of you as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6d391b7523b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>