<?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 Arash Cordi on Medium]]></title>
        <description><![CDATA[Stories by Arash Cordi on Medium]]></description>
        <link>https://medium.com/@arash-cordi?source=rss-3a600894d711------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*85MnhVVIWZnkD5DH.jpg</url>
            <title>Stories by Arash Cordi on Medium</title>
            <link>https://medium.com/@arash-cordi?source=rss-3a600894d711------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:32:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arash-cordi/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[dark corners of go]]></title>
            <link>https://arash-cordi.medium.com/dark-corners-of-go-4e29aafcd4b9?source=rss-3a600894d711------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e29aafcd4b9</guid>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Arash Cordi]]></dc:creator>
            <pubDate>Sat, 22 May 2021 00:54:17 GMT</pubDate>
            <atom:updated>2021-05-22T00:54:17.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*eZvOYSecLNX78c8TVaWhLA.png" /><figcaption>gopher</figcaption></figure><p>go is an easy to learn language with purposefully limited features. but there are some lesser known features which you may not know about. i have tried to list a few of them here.</p><h4>number literals</h4><p>For readability, an underscore character _ may appear after a base prefix or between successive digits; such underscores do not change the literal&#39;s value.</p><pre>1_000_000<br>0_600<br>0x_42_af_3d</pre><h4>prevent unkeyed literals</h4><pre>type X struct {<br>    A, B int<br>    _ struct{}<br>}<br><br>x := X{A: 1, B: 2} <em>// OK<br></em>x := X{1, 2}       <em>// Error: too few values</em></pre><p>note that go vet also complains about unkeyed literals.</p><p>to <a href="https://dave.cheney.net/2015/10/09/padding-is-hard">prevent extra padding</a> we can move the zero field to the top of the struct:</p><pre>type X1 struct {<br>    A, B int<br>    _ struct{}<br>}<br><br>type X2 struct {<br>    _ struct{}<br>    A, B int<br>}<br><br>var (<br>    x1 *X1<br>    x2 *X2<br>)<br><br>fmt.Printf(<br>    &quot;sizeof(X1) = %d sizeof(X2) = %d\n&quot;,<br>    unsafe.Sizeof(*x1), unsafe.Sizeof(*x2)<br>    ) <em>// sizeof(X1) = 24 sizeof(X2) = 16</em></pre><h4>type grouping</h4><p>group syntax can also be used for types:</p><pre>type (<br>    T1 struct{}<br>    T2 struct{}<br>)</pre><h4>pass multiple return value to another function</h4><p>generally you can’t do this except for this <a href="https://golang.org/ref/spec#Calls">special case</a>:</p><p>if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(<em>parameters_of_g</em>)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value.</p><pre>func add2(x, y int) (int, int) {<br> return x+2, y+2<br>}</pre><pre>func add4(x, y int) (int, int) {<br> return x+4, y+4<br>}</pre><pre>func main() {<br> // OK x = 7, y = 8<br> x, y := add4(add2(1, 2))</pre><pre> // ERROR multiple-value add2() in single-value context<br> fmt.Printf(&quot;x = %d y = %d&quot;, add2(1, 2))<br>}</pre><h4>interface composition</h4><p>interfaces can be union of other interfaces just like struct composition.</p><pre>type I1 interface {<br>    X() int<br>}<br><br>type I2 interface {<br>    Y()<br>}<br><br>type I3 interface {<br>    I1<br>    I2<br>    Z() int<br>}</pre><p>methods with same name must have similar signatures.</p><pre>type I1 interface {<br>    X() int<br>}<br><br>type I2 interface {<br>    X()<br>}<br><br>type I3 interface {<br>    I1 <br>    I2 // ERROR: duplicate method &#39;X&#39;<br>}</pre><h4>typed iota</h4><p>you can specify a type for iota</p><pre>const (<br>	_ = iota<br>	testvar // will be int<br>)</pre><p>vs</p><pre>type myType int<br>const (<br>	_ myType = iota<br>	testvar // will be myType<br>)</pre><h4>type alias vs type definition</h4><p>this is a type alias:</p><pre>type SameMutex = sync.Mutex</pre><p>this is a new type:</p><pre>type NewMutex sync.Mutex</pre><p>SameMutex is just another name for Mutex and will have all the functionality of Mutex, but NewMutex being a different type, does not inherit any methods bound to the given type:</p><pre>m1 := SameMutex{}<br>m2 := NewMutex{}<br>m1.Lock() <em>// OK<br></em>m2.Lock() <em>// ERROR: Unresolved reference &#39;Lock&#39;</em></pre><h4>package init()</h4><p>a package may have one or multiple init() functions which are called during package initialization after all package-level variables are initialized.</p><p>importing a package for side effects runs this function:</p><pre>import _ &quot;net/http/pprof&quot;</pre><p>there are a few rules about the order of variable evaluation; in the sample code below, x2 is initialized before init() so the output will be 0.</p><pre>package main</pre><pre>var X int</pre><pre>func init() {<br> X = 1<br>}</pre><pre>var x2 = 2 * X</pre><pre>func main() {<br> println(x2)<br>}</pre><h4>special packages and directories</h4><p><strong>/internal</strong><br>internal package is used to make specific packages unimportable. a package .../a/b/c/internal/d/e/f can be imported only by code in the directory tree rooted at .../a/b/c. It cannot be imported by code in .../a/b/g or in any other repository. this layout pattern is enforced on all repositories by <em>go</em> compiler since go 1.5</p><p><strong>/vendor</strong><br>you can use /vendor to put external package dependencies inside application directory. these dependencies can be managed manually or by go mod.</p><p>The go mod vendor command will create the /vendor directory for you. Note that you might need to add the -mod=vendor flag to your go build command if you are not using Go 1.14 where it&#39;s on by default.</p><p>some go tools like go list ignore this directory. others like gofmt and golint don’t. you can use a command like this if you wish to exclude this directory:</p><pre>go list ./... | grep -v /vendor/ | xargs -L1 golint -set_exit_status</pre><p><strong>testdata</strong></p><p>The go tool will ignore a directory named “testdata”, making it available to hold ancillary data needed by the tests.</p><p>when you run go test, for each package in scope, the test binary will be executed with its working directory set to the source directory of the package under test.</p><p>putting these together, locating test data from your test code is simply:</p><pre>os.Open(&quot;testdata/data.json&quot;)</pre><h4>type hint</h4><p>you can pass a zero value of a type to a function to inform it of the type you desire:</p><pre>type A struct {<br>    X string<br>    Y string<br>}<br><br>func Decode(useThisType interface{}, binaryData []byte) interface{} {<br>    json.Unmarshal(binaryData, useThisType)<br>    return useThisType<br>}<br><br>func main() {<br>    value := Decode(&amp;A{}, []byte(`{&quot;X&quot;:&quot;10&quot;, &quot;Y&quot;:&quot;20&quot;}`))<br>    fmt.Println(value)<br>}</pre><h4>detailed output with %v</h4><p>use %v of printf family functions to print data with sufficient details:</p><pre>type A struct {<br>    X string<br>    Y string<br>}<br><br>func main() {<br>    fmt.Printf(&quot;%v&quot;, A{X: &quot;10&quot;, Y:&quot;20&quot;})<br>    fmt.Printf(&quot;%+v&quot;, A{X: &quot;10&quot;, Y:&quot;20&quot;})<br>    fmt.Printf(&quot;%#v&quot;, A{X: &quot;10&quot;, Y:&quot;20&quot;})<br>}</pre><p>output:</p><pre>{10 20}<br>{X:10 Y:20}<br>main.A{X:&quot;10&quot;, Y:&quot;20&quot;}</pre><p>check <a href="https://yourbasic.org/golang/fmt-printf-reference-cheat-sheet/">this cheat sheet</a> for other <em>annotation verbs.</em></p><h4>Example functions</h4><pre>func Example() {...}<br>func ExampleT() {...}</pre><p>functions with these signatures can be used to place usage examples in godoc. Examples should be placed in a file with a _test suffix. you can document the output of the example by adding an output comment at its end.</p><pre>func ExampleExamples_output() {<br>    fmt.Println(&quot;Hello&quot;)<br>    // Output: Hello<br>}</pre><p>also, if output is provided go test will run the example and compares it’s output with the output specified in the comment section and report the example function as passed if they match. if no output is provided go test will only compile it.</p><h4>error wrapping</h4><p>since go 1.13 errors can wrap another error creating a hierarchy of errors.</p><p>%w directive in fmt.Errorf is used for wrapping an error:</p><pre>e1 := errors.New(&quot;error one&quot;)<br>e2 := fmt.Errorf(&quot;e2 : %w&quot;, e1)<br>fmt.Println(e2)</pre><p>output:</p><pre>e2 : error one</pre><p>use Unwrap() to unwrap errors:</p><pre>e3 := errors.Unwrap(e2)<br>fmt.Println(e3)</pre><p>output:</p><pre>error one</pre><p>check <a href="https://golangbyexample.com/wrapping-and-unwrapping-error-golang/">this post</a> for a detailed explanation on error wrapping.</p><h4>embed files</h4><p>as of go 1.16 you can natively embed files using embed package</p><pre>package main<br><br>import _ &quot;embed&quot;<br><br>func main() {<br>	//go:embed &quot;hello.txt&quot;<br>	var s string<br>	print(s)<br>}</pre><p>output:</p><pre>Hello, Gophers!</pre><p>read more about embedding <a href="https://golang.org/pkg/embed/">here</a>.</p><h4>forcing a type to json marshal</h4><p>the default type for integer values is float64 and int64 values may overflow. use this syntax to force encoding into string:</p><pre>type Data struct {<br>	ID int64 `json:&quot;id,string&quot;`<br>}</pre><h4>block forever</h4><p>you can use an empty select to block forever:</p><pre>select {<br>}</pre><p>a common use case is when you have a single server with multiple http listeners. you can spawn each was with a goroutine in main() and block forever using select{} . this is also a good place to check os signals.</p><p>you can find other ways to block <a href="https://blog.sgmansfield.com/2016/06/how-to-block-forever-in-go/">here</a>.</p><h4>comment magic</h4><p>for most parts comments are just comments. but there are situations where comments may have some side effects, we have seen two of these situations so far (the embed command and example function output), here are other situations:</p><p><strong>godoc text</strong></p><p>godoc uses the comment block immediately before a declaration as the documentation of the declaration; the first line of the comment should start with the name of declaration:</p><pre><em>// Object is an object<br></em>type Object struct {}</pre><p><strong>build constraints</strong></p><p>a comment that adheres to the following rules is recognized as a build constraint by go build :</p><ul><li>located at the start of the file</li><li>start with the prefix +build followed by one or more <em>tags</em></li></ul><pre>// +build linux</pre><p>this build tag tells the go compiler to use this file for linux only.</p><p>build tags can be combined with the following rules:</p><ul><li>build tags starting with ! are negated</li><li>space-separated tags are logically OR’d</li><li>comma-separated tags and line-separated tags are logically AND’d</li></ul><p>this constraint requires windows or linux :</p><pre>// +build linux windows</pre><p>this constraint requires both linux and 386 architecture:</p><pre>// +build linux,386</pre><p>a full detail of build constraints can be found <a href="https://golang.org/pkg/go/build/#hdr-Build_Constraints">here</a>.</p><p><strong>go generate</strong></p><p>when you run the command go generate, the tool search for comments of the form //go:generate command arguments . this command can be anything and doesn’t have any requirements.</p><p><strong>cgo</strong></p><p>Cgo allows Go programs to call C code directly. comment immediately preceding #import “C” directive (AKA <em>the</em> <em>preamble</em>) will be treated as standard code and can the be accessed via the C package:</p><pre><em>// #include &lt;stdio.h&gt;<br>//<br>// static void myprint(char *s) {<br>//     printf(&quot;%s\n&quot;, s)<br>// }<br></em>import &quot;C&quot;<br>C.myprint(C.String(&quot;foo&quot;))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e29aafcd4b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing DNSSEC Using Black-lies]]></title>
            <link>https://arash-cordi.medium.com/implementing-dnssec-using-black-lies-4ae218c14f10?source=rss-3a600894d711------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae218c14f10</guid>
            <dc:creator><![CDATA[Arash Cordi]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 12:20:00 GMT</pubDate>
            <atom:updated>2020-07-15T17:11:05.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*kgXadvIR-PrW_rV__K4Zvw.jpeg" /></figure><h3>Introduction</h3><p>DNSSEC adds a signature record for every record type in the response, guaranteeing the integrity of the response and preventing man-in-the-middle attacks.</p><p>but what if the response is empty?</p><p>The way negative answers are handled in DNSSEC is not straightforward. originally a new record type called NSEC was introduced. NSEC returns the previous and next name in zone which proves that the name in requested query cannot exist. there are two main problems with this solution:</p><p>1- zone walking: you can start from root and ask for next location using NSEC</p><p>2- response size: additional NSEC and RRSIG record required for authentication can cause the response size to get too big, making dns server vulnerable to amplification attacks.</p><p><a href="https://tools.ietf.org/html/rfc5155">NSEC3</a>, an update to NSEC made zone walking harder but not completely impossible.</p><p>another solution was proposed in <a href="https://www.ietf.org/rfc/rfc4470.txt">RFC-4470</a> aka while-lies. it proposes to create dummy locations slightly before and after the requested name for NXDOMAIN responses.</p><p><a href="https://tools.ietf.org/html/draft-valsorda-dnsop-black-lies">Black-lies</a> goes even further by changing NXDOMAIN responses to NODATA.</p><p>a detailed explanation of this technique can be found here: <a href="https://blog.cloudflare.com/black-lies/">Economical With The Truth: Making DNSSEC Answers Cheap</a></p><p>here I will show the result of our implementation in different scenarios.</p><h3>Cases</h3><p>we used the sample zone from <a href="https://tools.ietf.org/html/rfc4035#appendix-A">RFC-4035</a> to discuss different cases, (RRSIG and DNSKEY values are omitted):</p><pre>example.       3600 IN SOA ns1.example. bugs.x.w.example. (<br>                              1081539377 3600 300 3600000 3600)<br>               3600 NS     ns1.example.<br>               3600 NS     ns2.example.<br>               3600 MX     1 xx.example.<br>               3600 NSEC   a.example. NS SOA MX RRSIG NSEC DNSKEY<br>a.example.     3600 IN NS  ns1.a.example.<br>               3600 IN NS  ns2.a.example.<br>               3600 DS     57855 5 1 (<br>                              B6DCD485719ADCA18E5F3D48A2331627FDD3<br>                              636B )<br>               3600 NSEC   ai.example. NS DS RRSIG NSEC<br>ns1.a.example. 3600 IN A   192.0.2.5<br>ns2.a.example. 3600 IN A   192.0.2.6<br>ai.example.    3600 IN A   192.0.2.9<br>               3600 HINFO  &quot;KLH-10&quot; &quot;ITS&quot;<br>               3600 AAAA   2001:db8::f00:baa9<br>               3600 NSEC   b.example. A HINFO AAAA RRSIG NSEC<br>b.example.     3600 IN NS  ns1.b.example.<br>               3600 IN NS  ns2.b.example.<br>               3600 NSEC   ns1.example. NS RRSIG NSEC<br>ns1.b.example. 3600 IN A   192.0.2.7<br>ns2.b.example. 3600 IN A   192.0.2.8<br>ns1.example.   3600 IN A   192.0.2.1<br>               3600 NSEC   ns2.example. A RRSIG NSEC<br>ns2.example.   3600 IN A   192.0.2.2<br>               3600 NSEC   *.w.example. A RRSIG NSEC<br>*.w.example.   3600 IN MX  1 ai.example.<br>               3600 NSEC   x.w.example. MX RRSIG NSEC<br>x.w.example.   3600 IN MX  1 xx.example.<br>               3600 NSEC   x.y.w.example. MX RRSIG NSEC<br>x.y.w.example. 3600 IN MX  1 xx.example.<br>               3600 NSEC   xx.example. MX RRSIG NSEC<br>xx.example.    3600 IN A   192.0.2.10<br>               3600 HINFO  &quot;KLH-10&quot; &quot;TOPS-20&quot;<br>               3600 AAAA   2001:db8::f00:baaa<br></pre><h4>1 —Answer</h4><p>A successful query to an authoritative server.</p><pre>;; QUESTION SECTION:<br>;x.w.example. IN MX</pre><p>here we return the same answer:</p><pre>;; ANSWER SECTION:<br>x.w.example. 3600 IN MX 1 xx.example.<br>x.w.example. 3600 IN RRSIG MX 8 3 3600 20200715093313 20200707063313 28743 example. ...</pre><h4>2 — Name Error</h4><p>An authoritative name error.</p><pre>;; Question<br>   ml.example.         IN A</pre><p>Normal Answer:</p><pre>;; Header: QR AA DO RCODE=3</pre><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>example.       3600 IN SOA ns1.example. bugs.x.w.example. (<br>                           1081539377<br>                           3600<br>                           300<br>                           3600000<br>                           3600<br>                           )<br>example.       3600 RRSIG  SOA 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>b.example.     3600 NSEC   ns1.example. NS RRSIG NSEC<br>b.example.     3600 RRSIG  NSEC 5 2 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>example.       3600 NSEC   a.example. NS SOA MX RRSIG NSEC DNSKEY<br>example.       3600 RRSIG  NSEC 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...</pre><p>The NSEC RRs prove that the name does not exist and that no covering wildcard exists.</p><p>Black-lies answer:</p><pre>;; Header: QR AA DO RCODE=0</pre><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>example.     3600 IN SOA ns1.example. bugs.x.w.example. (<br>                         1081539377 3600 300 3600000 3600)<br>example.     3600 IN RRSIG SOA 8 1 3600 20200715094623 (<br>                           20200707064623 28743 example.<br>                           ...<br>ml.example.  3600 IN NSEC \000.ml.example. RRSIG NSEC<br>ml.example.  3600 IN RRSIG NSEC 8 2 3600 20200715094623 (<br>                           20200707064623 28743 example.<br>                           ...</pre><p>here we respond with RCODE=0 (SUCCESS, NODATA). there is one RRSIG for SOA and one black-lies RRSIG for ml.example., claiming that ml.example. exists but only contains RRSIG and NSEC records.</p><h4>3 — No Data Error</h4><p>A &quot;no data&quot; response.</p><pre>;; Question<br>   ns1.example.        IN MX</pre><p>Normal answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>example.       3600 IN SOA ns1.example. bugs.x.w.example. (<br>                           1081539377 3600 300 3600000 3600)<br>example.       3600 RRSIG  SOA 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>ns1.example.   3600 NSEC   ns2.example. A RRSIG NSEC<br>ns1.example.   3600 RRSIG  NSEC 5 2 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...</pre><p>The NSEC RR proves that the name exists and that the requested RR type does not.</p><p>Black-lies answer:</p><pre>;; AUTHORITY SECTION:<br>example.     3600 IN SOA ns1.example. bugs.x.w.example. (<br>                         1081539377 3600 300 3600000 3600)<br>example.     3600 RRSIG  SOA 8 1 3600 20200715100708<br>                         20200707070708 28743 example.                            <br>                         ...<br>ns1.example. 3600 NSEC   \000.ns1.example. A<br>                         CNAME PTR TXT AAAA SRV RRSIG NSEC TLSA CAA<br>ns1.example. 3600 RRSIG  NSEC 8 2 3600 20200715100708<br>                         20200707070708 28743 example.<br>                         ...</pre><p>our answer here is similar to the normal except that in NSEC record for ns1.example. we add all supported RR types except for the one requested.</p><h4>4 — Referral to Signed Zone</h4><pre>;; Question<br>mc.a.example.       IN MX</pre><p>The DS RR contains the data which the resolver will need to validate the corresponding DNSKEY RR in the child zone’s apex.</p><p>answers are the same here:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>a.example.     3600 IN NS  ns1.a.example.<br>a.example.     3600 IN NS  ns2.a.example.<br>a.example.     3600 DS     57855 5 1 (<br>                           B6DCD485719ADCA18E5F3D48A2331627FDD3<br>                           636B )<br>a.example.     3600 RRSIG  DS 5 2 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>;; Additional<br>ns1.a.example. 3600 IN A   192.0.2.5<br>ns2.a.example. 3600 IN A   192.0.2.6</pre><h4>5 — Referral to Unsigned Zone</h4><pre>;; Question<br>mc.b.example.       IN MX</pre><p>Normal answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>b.example.     3600 IN NS  ns1.b.example.<br>b.example.     3600 IN NS  ns2.b.example.<br>b.example.     3600 NSEC   ns1.example. NS RRSIG NSEC<br>b.example.     3600 RRSIG  NSEC 5 2 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...</pre><p>The NSEC RR proves that no DS RR for this delegation exists in the parent zone.</p><p>Black-lies answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>b.example.     3600 IN NS ns1.b.example.<br>b.example.     3600 IN NS ns2.b.example.<br>b.example.     3600 IN NSEC \000.b.example. NS RRSIG NSEC<br>b.example.     3600 IN RRSIG NSEC 8 2 3600 20200715102857 (<br>               20200707072857 28743 example.<br>               ...</pre><p>there’s a problem with NSEC’s next label; we can’t use \000.b.example. because it’s outside our authority, and we can’t/don’t want to return the next label inside authority (ns.example. in this case). using root or any other default label can also cause trouble, recursors may mark anything in between as NXDOMIAN and negative-cache them. as of now I dont have a better soolution for this problem.</p><h4>6 — Wildcard Expansion</h4><p>A successful query that was answered via wildcard expansion.</p><pre>;; Question<br>a.z.w.example.      IN MX</pre><p>Normal answer:</p><pre>;; Answer<br>a.z.w.example. 3600 IN MX  1 ai.example.<br>a.z.w.example. 3600 RRSIG  MX 5 2 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>;; Authority<br>example.       3600 NS     ns1.example.<br>example.       3600 NS     ns2.example.<br>example.       3600 RRSIG  NS 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>x.y.w.example. 3600 NSEC   xx.example. MX RRSIG NSEC<br>x.y.w.example. 3600 RRSIG  NSEC 5 4 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...</pre><p>The label count in the answer’s RRSIG RR indicated that a wildcard RRset was expanded to produce this response, and the NSEC RR proves that no closer match exists in the zone.</p><p>Black-lies answer:</p><pre>;; Answer<br>a.z.w.example.    3600 IN MX 1 ai.example.<br>a.z.w.example.    3600 IN RRSIG MX 8 4 3600 20200715104329 (<br>                          20200707074329 28743 example.<br>                          ...</pre><p>here we claim that there was no wildcard expansion and return a normal answer.</p><h4>7 — Wildcard No Data Error</h4><p>A &quot;no data&quot; response for a name covered by a wildcard.</p><pre>;; Question<br>a.z.w.example.      IN AAAA</pre><p>Normal answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>example.       3600 IN SOA ns1.example. bugs.x.w.example. (<br>                           1081539377 3600 300 3600000 3600)<br>example.       3600 RRSIG  SOA 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>x.y.w.example. 3600 NSEC   xx.example. MX RRSIG NSEC<br>x.y.w.example. 3600 RRSIG  NSEC 5 4 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>*.w.example.   3600 NSEC   x.w.example. MX RRSIG NSEC<br>*.w.example.   3600 RRSIG  NSEC 5 2 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...</pre><p>The NSEC RRs proce that the matching wildcard name does not have any RRs of the requested type and that no closer match exists in the zone.</p><p>Black-lies answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>a.z.w.example.  3600 NSEC \000.a.z.w.example.<br>                     A CNAME PTR MX TXT SRV RRSIG NSEC TLSA CAA<br>a.z.w.example.  3600 RRSIG NSEC 8 4 3600 20200715105328<br>                     20200707075328 28743 example. <br>                     ...<br>example.        3600 SOA ns1.example. bugs.x.w.example. (<br>                     1081539377 3600 300 3600000 3600)<br>example.        3600 RRSIG SOA 8 1 3600 20200715105328<br>                     20200707075328 28743 example. <br>                     ...</pre><p>here again we ignore wildcard expansion and return a normal NODATA response.</p><h4>8 — DS Child Zone No Data Error</h4><p>A &quot;no data&quot; response for a QTYPE=DS query that was mistakenly sent to<br> a name server for the child zone.</p><pre>;; Question<br>example.            IN DS</pre><p>Normal answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>example.       3600 IN SOA ns1.example. bugs.x.w.example. (<br>                           1081539377 3600 300 3600000 3600)<br>example.       3600 RRSIG  SOA 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...<br>example.       3600 NSEC   a.example. NS SOA MX RRSIG NSEC DNSKEY<br>example.       3600 RRSIG  NSEC 5 1 3600 20040509183619 (<br>                           20040409183619 38519 example.<br>                           ...</pre><p>Black-lies answer:</p><pre>;; Answer<br>;; (empty)<br><br>;; Authority<br>example.        3600 IN SOA ns1.example. bugs.x.w.example. (<br>                            1081539377 3600 300 3600000 3600)<br>example.        3600 RRSIG SOA 8 1 3600 20200715110009<br>                           20200707080009 28743 example.<br>                           ...<br>example.        3600 NSEC \000.example.<br>                     A NS SOA PTR MX TXT AAAA<br>                     SRV RRSIG NSEC TLSA CAA<br>example.        3600 RRSIG NSEC 8 1 3600 20200715110009<br>                           20200707080009 28743 example.<br>                           ...</pre><h3>Conclusion</h3><p>our implementation seems to work fine. although there are still some flaws. you can check out our code <a href="https://github.com/hawell/z42">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae218c14f10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Current state of DNS Standards]]></title>
            <link>https://arash-cordi.medium.com/current-state-of-dns-standards-594f8ad175f6?source=rss-3a600894d711------2</link>
            <guid isPermaLink="false">https://medium.com/p/594f8ad175f6</guid>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Arash Cordi]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 15:12:50 GMT</pubDate>
            <atom:updated>2020-01-15T15:12:50.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*ldVAKGH3cZEw7v9XAmIvEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2I8EQrIp85mH_EyBntoeQ.png" /></figure><p>this is a visualization of current state of DNS standards based on <a href="https://powerdns.org/dns-camel/">DNS Camel</a>.</p><p>SVG file can be found <a href="https://github.com/hawell/dns-mega-rfc/raw/master/graph.svg">here</a>.</p><p>graphviz code can be found <a href="https://github.com/hawell/dns-mega-rfc/raw/master/graph.gv">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=594f8ad175f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DNS query distribution and its effect on caching]]></title>
            <link>https://arash-cordi.medium.com/dns-query-distribution-and-its-effect-on-caching-part-1-1f035050d640?source=rss-3a600894d711------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f035050d640</guid>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <category><![CDATA[zipfs-law]]></category>
            <dc:creator><![CDATA[Arash Cordi]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 12:46:40 GMT</pubDate>
            <atom:updated>2020-07-15T17:10:07.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*7uVkXRxO3S8kCcXFHJb5yA.png" /></figure><p>Many studies suggest that internet resources (including dns resource records) follow a zipf-like distribution. see “<a href="http://nms.lcs.mit.edu/papers/dns-ton2002.pdf">DNS Performance and Effectiveness of Caching</a>”.</p><p>zipf law originally states that given a large sample of words used, the frequency of any word is inversely proportional to its rank in the frequency table.</p><p>we can check these claims using data from our own <a href="https://github.com/hawell/z42">authoritative DNS server</a>.</p><p>we use two different aggregation on queries, qname-qtype and qname . we also fetch data from two time frames, a 5-minute window and a 1-day window. here are sorted query frequencies of these 4 scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*l-s5b9MHRnGDxqYsp_Sxfg.png" /><figcaption>qname — 1day query frequency</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dgX7BzA4295jvRzrrtALlg.png" /><figcaption>(qname, qtype) — 1day query frequency</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yKBNC3lc2-SjBsNYpL8jAw.png" /><figcaption>qname — 5min query frequency</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*B0ue3flnkHio9LSiIBAhxw.png" /><figcaption>(qname, qtype) — 5min query frequency</figcaption></figure><p>we can see the familiar long-tail pattern in all our data sets ( although it looks more <a href="https://en.wikipedia.org/wiki/Laplace_distribution">laplacian</a> than power-law). but <a href="http://bactra.org/weblog/491.html">not all long-tail patterns are power-law</a>. here are the results of curve fitting using matlab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWM4caMMT4sr9SWyk3NvGw.png" /><figcaption>qname — 1day log-log diagram</figcaption></figure><pre>General model:<br>     f(x) = (x^(-(a+1)))/zeta(a+1)<br>Coefficients (with 95% confidence bounds):<br>       a =       0.039  (0.03837, 0.03962)It worth to mention another</pre><pre>Goodness of fit:<br>  SSE: 0.001408<br>  R-square: 0.6219<br>  Adjusted R-square: 0.6219<br>  RMSE: 0.0003753</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7OwQj9UgOuLPN6M-d-fig.png" /><figcaption>(qname, qtype) — 1day log-log diagram</figcaption></figure><pre>General model:<br>     f(x) = (x^(-(a+1)))/zeta(a+1)<br>Coefficients (with 95% confidence bounds):<br>       a =     0.02773  (0.02719, 0.02828)</pre><pre>Goodness of fit:<br>  SSE: 0.001122<br>  R-square: 0.5046<br>  Adjusted R-square: 0.5046<br>  RMSE: 0.000335</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wk0DN2qeK0OOXiJvy49JyQ.png" /><figcaption>qname — 5min log-log diagram</figcaption></figure><pre>General model:<br>     f(x) = (x^(-(a+1)))/zeta(a+1)<br>Coefficients (with 95% confidence bounds):<br>       a =     0.03655  (0.03585, 0.03725)</pre><pre>Goodness of fit:<br>  SSE: 0.001314<br>  R-square: 0.6033<br>  Adjusted R-square: 0.6033<br>  RMSE: 0.0004222</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htmiG7QflmV2K2l_rYyfkA.png" /><figcaption>(qname, qtype) — 5min log-log diagram</figcaption></figure><pre>General model:<br>     f(x) = (x^(-(a+1)))/zeta(a+1)<br>Coefficients (with 95% confidence bounds):<br>       a =     0.02935  (0.02889, 0.02982)</pre><pre>Goodness of fit:<br>  SSE: 0.0008184<br>  R-square: 0.6101<br>  Adjusted R-square: 0.6101<br>  RMSE: 0.0002861</pre><h4>is there a better fit?</h4><p>probably, for example check this distribution called “<a href="https://en.wikipedia.org/wiki/Burr_distribution">Burr Distribution</a>” identified by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*0I6aJFSs2ggqSlAfMDjfvA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbT7VSpJ2vza6cyiPGkiTQ.png" /><figcaption>(qname, qtype) — 1day log-log diagram</figcaption></figure><p>although it is mostly used for describing the frequency of an event over time, the fitting (not taking into account the initial rise of log-logistic distributions) is uncanny. this may or may not mean something; but first we should take a step back and ask ourselves this question:</p><h4>should we really care?</h4><p>probably not.</p><p>all we need to now is that we have a consistent 80–20 situation. there are three areas in caching strategy where this has an effect:</p><ul><li><strong>size limit eviction:</strong></li></ul><p>in a size-limited cache we want to keep the top 20% resources and discard or not allow the tail items.</p><p>a big enough cache can eliminate this problem, but this is not always possible.</p><ul><li><strong>time limit eviction</strong></li></ul><p>we prefer to keep our top 20% resources in cache at all time. in case of an external expiration (e.g. dns ttl value) we can still somehow keep our resource (pre-fetching or using stale value).</p><p>time limit eviction may not be in our best interest.</p><ul><li><strong>sharding</strong></li></ul><p>sharding is the process of distributing cache items across multiple <em>storages</em> in order to optimize parallel access.</p><p>in this case we want to distribute most of the shards between top 20% resources.</p><h4>cache state in golang</h4><p>it’s now time to benchmark a few popular cache libraries of our programming language of choice, golang, and see how they perform under these conditions. the code for these tests can be found <a href="https://github.com/hawell/cache-compare">here</a>.</p><p>we tested the following libraries:</p><ul><li><a href="https://github.com/goburrow/cache">goburrow</a></li><li><a href="https://github.com/dgraph-io/ristretto">ristretto</a></li><li><a href="https://github.com/karlseguin/ccache">ccache</a></li><li><a href="https://godoc.org/github.com/VictoriaMetrics/fastcache">fastcache</a></li><li><a href="https://github.com/coocood/freecache">freecache</a></li><li><a href="https://github.com/allegro/bigcache">bigcache</a></li></ul><h4>hit rate</h4><p>for hit rate, there’s also a theoretical optimal case which uses future information. note that the zipf generator we used have a <em>heavier</em> tail than our sample data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpcRz0lhqMbLGtc2rHjBmQ.png" /></figure><h4>Throughput</h4><p>throughput benchmarks ran on an Intel Core i7–8750H with 16 GB of RAM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*heLvm6kPoa7FyjTqG0iccA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96e11aUdAyeIsx0RIwkvMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2HskOHnLIzuHnpZ2uw2_Q.png" /></figure><h4>conclusion</h4><p>goburrow has the best hit rate, ristretto has the best performance in read heavy scenarios, and fastcache in write heavy scenarios</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f035050d640" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we optimized our DNS server using go tools]]></title>
            <link>https://arash-cordi.medium.com/how-we-optimized-our-dns-server-using-go-tools-d753e1a5e709?source=rss-3a600894d711------2</link>
            <guid isPermaLink="false">https://medium.com/p/d753e1a5e709</guid>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Arash Cordi]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 07:47:16 GMT</pubDate>
            <atom:updated>2023-09-22T21:47:27.587Z</atom:updated>
            <content:encoded><![CDATA[<h4>background</h4><p>with tens of thousands of web sites using our <a href="https://github.com/hawell/z42">authoritative dns server</a>, we respond to millions of requests every day. dns attacks are getting more and more widespread these days, dns is a crucial part of our system and we must make sure that we can perform well under high pressure.</p><p><a href="https://github.com/hawell/dns-flood">dns-flood</a> is a small tool I found capable of producing huge number of udp requests.</p><pre># timeout 20s ./dnsflood example.com 127.0.0.1 -p 2053</pre><p>monitoring our systems showed that memory usage of our service was growing so fast that we had stop our service or we would get into OOM errors. this looks like a memory-leak problem; there are different causes for “Kind-of” memory leaks and “Real ” memory leaks in go:</p><ul><li>hanging goroutines</li><li>incorrect use of defer &amp; finalizer</li><li>substring &amp; subslices</li><li>global variables</li></ul><p><a href="https://go101.org/article/memory-leaking.html">this post</a> has an in-dept explanation of different leak cases.</p><p>before jumping to any conclusions let’s do some profiling first</p><h4>GODEBUG</h4><p>different debug facilities can be enabled using GODEBUG environment variable by passing a list of comma separated name=value pairs.</p><p><strong>scheduler trace</strong></p><p>scheduler trace can provide information about the run-time behavior of goroutines. to enable scheduler trace, run the program with GODEBUG=schedtrace=100 the value means output period in ms.</p><pre>$ GODEBUG=schedtrace=100 ./z42 -c config.json<br>SCHED 2952ms: ... runqueue=3 [26 11 7 18 13 30 6 3 24 25 11 0]<br>SCHED 3053ms: ... runqueue=3 [0 0 0 0 0 0 0 0 4 0 21 0]<br>SCHED 3154ms: ... runqueue=0 [0 6 2 4 0 30 0 5 0 11 2 5]<br>SCHED 3255ms: ... runqueue=1 [0 0 0 0 0 0 0 0 0 0 0 0]<br>SCHED 3355ms: ... runqueue=0 [1 0 0 0 0 0 0 0 0 0 0 0]<br>SCHED 3456ms: ... runqueue=0 [0 0 0 0 0 0 0 0 0 0 0 0]<br>SCHED 3557ms: ... runqueue=0 [13 0 3 0 3 33 2 0 10 8 10 14]<br>SCHED 3657ms: ...runqueue=3 [14 1 0 5 19 54 9 1 0 1 29 0]<br>SCHED 3758ms: ... runqueue=0 [67 1 5 0 0 1 0 0 87 4 0 0]<br>SCHED 3859ms: ... runqueue=6 [0 0 3 6 0 0 0 0 3 2 2 19]<br>SCHED 3960ms: ... runqueue=0 [0 0 1 0 1 0 0 1 0 1 0 0]<br>SCHED 4060ms: ... runqueue=5 [4 0 5 0 1 0 0 0 0 0 0 0]<br>SCHED 4161ms: ... runqueue=0 [0 0 0 0 0 0 0 1 0 0 0 0]<br>SCHED 4262ms: ... runqueue=4 [0 128 21 172 1 19 8 2 43 5 139 37]<br>SCHED 4362ms: ... runqueue=0 [0 0 0 0 0 0 0 0 0 0 0 0]<br>SCHED 4463ms: ... runqueue=6 [0 28 23 39 4 11 4 11 25 0 25 0]<br>SCHED 4564ms: ... runqueue=354 [51 45 33 32 15 20 8 7 5 42 6 0]</pre><p>runqueue is the length of global run-able goroutine queue. numbers in bracket are length of per process queue.</p><p>an ideal situation is where all processes are busy running goroutines and a reasonable runqueue length evenly distributed between all processes:</p><pre>SCHED 2449ms: gomaxprocs=12 idleprocs=0 threads=40 spinningthreads=1 idlethreads=1 runqueue=20 [20 20 20 20 20 20 20 20 20 20 20]</pre><p>looking at our schedtrace output we can see there are time frames when almost all processes are idle. this means we are not utilizing full cpu power.</p><p><strong>garbage collector trace</strong></p><p>To enable the garbage collector (GC) trace, run the program with GODEBUG=gctrace=1 environment variable:</p><pre>GODEBUG=gctrace=1 ./z42 -c config1.json<br>.<br>.<br>.<br>gc 30 <a href="http://twitter.com/3">@3</a>.727s 1%: 0.066+21+0.093 ms clock, 0.79+128/<strong>59</strong>/0+1.1 ms cpu, 67-&gt;71-&gt;45 MB, <strong>76 MB</strong> goal, 12 P<br>gc 31 <a href="http://twitter.com/3">@3</a>.784s 2%: 0.030+27+0.053 ms clock, 0.36+177/<strong>81</strong>/7.8+0.63 ms cpu, 79-&gt;84-&gt;55 MB, <strong>90 MB</strong> goal, 12 P<br>gc 32 <a href="http://twitter.com/3">@3</a>.858s 3%: 0.026+34+0.024 ms clock, 0.32+234/<strong>104</strong>/0+0.29 ms cpu, 96-&gt;100-&gt;65 MB, <strong>110 MB</strong> goal, 12 P<br>gc 33 <a href="http://twitter.com/3">@3</a>.954s 3%: 0.026+44+0.13 ms clock, 0.32+191/<strong>131</strong>/57+1.6 ms cpu, 117-&gt;123-&gt;79 MB, <strong>131 MB</strong> goal, 12 P<br>gc 34 <a href="http://twitter.com/4">@4</a>.077s 4%: 0.010+53+0.024 ms clock, 0.12+241/<strong>159</strong>/69+0.29 ms cpu, 142-&gt;147-&gt;91 MB, <strong>158 MB</strong> goal, 12 P<br>gc 35 <a href="http://twitter.com/4">@4</a>.228s 5%: 0.017+61+0.12 ms clock, 0.20+296/<strong>179</strong>/94+1.5 ms cpu, 166-&gt;174-&gt;105 MB, <strong>182 MB</strong> goal, 12 P<br>gc 36 <a href="http://twitter.com/4">@4</a>.391s 6%: 0.017+73+0.086 ms clock, 0.21+492/<strong>216</strong>/4.0+1.0 ms cpu, 191-&gt;198-&gt;122 MB, <strong>210 MB</strong> goal, 12 P<br>gc 37 <a href="http://twitter.com/4">@4</a>.590s 7%: 0.049+85+0.095 ms clock, 0.59+618/<strong>253</strong>/0+1.1 ms cpu, 222-&gt;230-&gt;140 MB, <strong>244 MB</strong> goal, 12 P<br>.<br>.<br>.</pre><p>as we can see here, in-use memory is increasing and the amount of time needed for gc to do it’s job is also increasing. this means that we are consuming more memory than gc can process.</p><p>more on GODEBUG and some other golang env variables <a href="https://dave.cheney.net/tag/godebug">here</a>.</p><h4>enabling the profiler</h4><p>go tool pprof is the tool for analyzing and profiling data. there are two ways to set up pprof either by directly calling runtime/pprof functions like pprof.StartCPUProfile() in your code or setting up net/http/pprof http listener and getting data from there which is the way we used. pprof has very little overhead so it is safe to use in production, but profile endpoint should not be exposed publicly because they may reveal sensitive data.</p><p>for the second option all we need to to do is import “net/http/pprof” package:</p><pre>import (<br>   _ &quot;net/http/pprof&quot;<br>)</pre><p>then add a http listener:</p><pre>go func() {<br>   log.Println(http.ListenAndServe(&quot;localhost:6060&quot;, nil))<br>}()</pre><p>pprof has several default profiles:</p><ul><li><strong>allocs</strong>: A sampling of all past memory allocations</li><li><strong>block</strong>: Stack traces that led to blocking on synchronization primitives</li><li><strong>goroutine</strong>: Stack traces of all current goroutines</li><li><strong>heap</strong>: A sampling of memory allocations of live objects.</li><li><strong>mutex</strong>: Stack traces of holders of contended mutexes</li><li><strong>profile</strong>: CPU profile.</li><li><strong>threadcreate</strong>: Stack traces that led to the creation of new OS threads</li><li><strong>trace</strong>: A trace of execution of the current program.</li></ul><p>note: trace endpoint unlike all other endpoints is a <em>trace</em> profile not a <em>pprof</em> profile, you can view it using go tool trace instead of go tool pprof.</p><p>now that we have our tools up and running we can look at the available tools.</p><h4>cpu profiler</h4><pre>‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍$ go tool pprof <a href="http://localhost:6060/debug/pprof/profile?seconds=12">http://localhost:6060/debug/pprof/profile?seconds=10</a></pre><p>cpu profiler runs for 30 seconds by default (we can change this with seconds parameter) and collect samples every 100 milliseconds then it enters the interactive mode. there are several commands available the most common are top, list, web</p><p>use top n to view top hottest entries in text format, there are two options to sort the output, -cum for cumulative order and -flat</p><pre>(pprof) top 10 -cum<br>Showing nodes accounting for 1.50s, 6.19% of 24.23s total<br>Dropped 347 nodes (cum &lt;= 0.12s)<br>Showing top 10 nodes out of 186<br> flat  flat%   sum%  cum   cum%<br>0.03s 0.12% 0.12% 16.7s 69.13% (*Server).serveUDPPacket<br>0.05s 0.21% 0.33% 15.6s 64.51% (*Server).serveDNS<br>0     0%    0.33% 14.3s 59.10% (*ServeMux).ServeDNS<br>0     0%    0.33% 14.2s 58.73% HandlerFunc.ServeDNS<br>0.01s 0.04% 0.37% 14.2s 58.73% main.handleRequest<br>0.07s 0.29% 0.66% 13.5s 56.00% (*DnsRequestHandler).HandleRequest<br>0.99s 4.09% 4.75% 7.56s 31.20% runtime.gentraceback<br>0.02s 0.08% 4.83% 7.02s 28.97% runtime.systemstack<br>0.31s 1.28% 6.11% 6.62s 27.32% runtime.mallocgc<br>0.02s 0.08% 6.19% 6.35s 26.21% (*DnsRequestHandler).FindANAME<br>(pprof)</pre><p>use list to investigate a single function.</p><pre>(pprof) list handleRequest<br>Total: 24.23s<br>ROUTINE ======================== main.handleRequest in /home/arash/go/src/cloud/redins/redins.go<br>      10ms     14.23s (flat, cum) 58.73% of Total<br>         .          .     35: l          *handler.RateLimiter<br>         .          .     36: configFile string<br>         .          .     37:)<br>         .          .     38:<br>         .          .     39:func handleRequest(w dns.ResponseWriter, r *dns.Msg) {<br>      10ms      610ms     40: context := handler.NewRequestContext(w, r)<br>         .       50ms     41: logger.Default.Debugf(&quot;handle request: [%d] %s %s&quot;, r.Id, context.RawName(), context.Type())<br>         .          .     42:<br>         .          .     43: if l.CanHandle(context.IP()) {<br>         .     13.57s     44:  h.HandleRequest(context)<br>         .          .     45: } else {<br>         .          .     46:  context.Response(dns.RcodeRefused)<br>         .          .     47: }<br>         .          .     48:}<br>         .          .     49:<br>(pprof)</pre><p>web command can be used to generate a SVG graph of hotsopts and opens it in a browser.</p><pre>(pprof)web handleRequest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*4vzkeOVmsXoBjM6qzA7vnQ.png" /></figure><p>having lots of time spent in GC functions like runtime.mallocgc often means heavy allocation, which can put extra pressure on garbage collector and increase latency.</p><p>having lots of time spent on synchronization mechanisms like runtime.chansend or runtime.lock could be a sign of contention</p><p>having lots of time spent in syscall.Read/Write mean exsessive use of io operations</p><h4>memory profiler</h4><pre>$ go tool pprof <a href="http://localhost:6060/debug/pprof/alloc">http://localhost:6060/debug/pprof/allocs</a></pre><p>by default it shows lifetime allocated memory. we can see number of allocated objects using -alloc_objects, other useful options are -inuse_objects and -inuse_space for inspecting <em>live </em>memory.</p><p>generally if you want to reduce memory consumption you need to look at -inuse_space but if you want to improve latency look at -alloc_objects after a suficient execution time/load.</p><h4>identifying the bottleneck</h4><p>it is important to first identify the type of bottleneck (cpu, io, memory) we are dealing with. aside from profilers, there’s another kind of tool available.</p><p>go tool trace can show what our goroutines are really doing in details. to collect trace sample we need to send a http request to trace endpoint:</p><pre>$ curl <a href="http://localhost:6060/debug/pprof/trace?seconds=5">http://localhost:6060/debug/pprof/trace?seconds=5</a> --output trace.out</pre><p>generated file can be viewed using trace tool:</p><pre>$ go tool trace trace.out<br>2019/12/25 15:30:50 Parsing trace...<br>2019/12/25 15:30:59 Splitting trace...<br>2019/12/25 15:31:10 Opening browser. Trace viewer is listening on <a href="http://127.0.0.1:42703/">http://127.0.0.1:42703</a></pre><p>go tool trace is a web app which uses Chrome DevTools protocol, and only compatible with chrome browsers. main page looks something similar to this :</p><pre><a href="http://127.0.0.1:42703/trace?start=0&amp;end=1002182">View trace (0s-409.575266ms)</a><br><a href="http://127.0.0.1:42703/trace?start=1002182&amp;end=2000009">View trace (411.075559ms-747.252311ms)</a><br><a href="http://127.0.0.1:42703/trace?start=2000009&amp;end=2994454">View trace (747.252311ms-1.234968945s)</a><br><a href="http://127.0.0.1:42703/trace?start=2994454&amp;end=3990349">View trace (1.234968945s-1.774245108s)</a><br><a href="http://127.0.0.1:42703/trace?start=3990349&amp;end=4998414">View trace (1.774245484s-2.111339514s)</a><br><a href="http://127.0.0.1:42703/trace?start=4998414&amp;end=5994557">View trace (2.111339514s-2.674030898s)</a><br><a href="http://127.0.0.1:42703/trace?start=5994557&amp;end=6980207">View trace (2.674031362s-3.044145798s)</a><br><a href="http://127.0.0.1:42703/trace?start=6980207&amp;end=7955112">View trace (3.044145798s-3.458795252s)</a><br><a href="http://127.0.0.1:42703/trace?start=7955112&amp;end=8917871">View trace (3.43953778s-4.075080634s)</a><br><a href="http://127.0.0.1:42703/trace?start=8917871&amp;end=9878421">View trace (4.075081098s-4.439271287s)</a><br><a href="http://127.0.0.1:42703/trace?start=9878421&amp;end=10847838">View trace (4.439271635s-4.814869651s)</a><br><a href="http://127.0.0.1:42703/trace?start=10847838&amp;end=11181263">View trace (4.814869651s-5.253597835s)</a><br><br><a href="http://127.0.0.1:42703/goroutines">Goroutine analysis</a><br><a href="http://127.0.0.1:42703/io">Network blocking profile</a> (<a href="http://127.0.0.1:42703/io?raw=1">⬇</a>)<br><a href="http://127.0.0.1:42703/block">Synchronization blocking profile</a> (<a href="http://127.0.0.1:42703/block?raw=1">⬇</a>)<br><a href="http://127.0.0.1:42703/syscall">Syscall blocking profile</a> (<a href="http://127.0.0.1:42703/syscall?raw=1">⬇</a>)<br><a href="http://127.0.0.1:42703/sched">Scheduler latency profile</a> (<a href="http://127.0.0.1:42703/sche?raw=1">⬇</a>)<br><a href="http://127.0.0.1:42703/usertasks">User-defined tasks</a><br><a href="http://127.0.0.1:42703/userregions">User-defined regions</a><br><a href="http://127.0.0.1:42703/mmu">Minimum mutator utilization</a></pre><p>trace splits trace time to make sure your browser can handle it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFawpA2QksTjPfccEniv1A.png" /></figure><p>there are myriads of data here which makes it almost decipherable if we don’t now what we are looking for. let’s leave it for now.</p><p>the next link on the main page is “goroutine analysis” which shows different <em>kind</em> of goroutines running in the program during the trace period:</p><pre>Goroutines:<br><a href="http://127.0.0.1:42703/goroutine?id=9863328">github.com/miekg/dns.(*Server).serveUDPPacket</a> <strong>N=441703</strong><br><a href="http://127.0.0.1:42703/goroutine?id=4354496">runtime.gcBgMarkWorker</a> N=12<br><a href="http://127.0.0.1:42703/goroutine?id=10956672">github.com/karlseguin/ccache.(*Cache).worker</a> N=2<br><a href="http://127.0.0.1:42703/goroutine?id=11504448">main.Start.func1</a> N=1<br><a href="http://127.0.0.1:42703/goroutine?id=4377248">runtime.bgsweep</a> N=1<br><a href="http://127.0.0.1:42703/goroutine?id=11372896">cloud/redins/handler.NewHandler.func2</a> N=1<br><a href="http://127.0.0.1:42703/goroutine?id=11479744">runtime/trace.Start.func1</a> N=1<br><a href="http://127.0.0.1:42703/goroutine?id=8338816">net/http.(*conn).serve</a> N=1<br><a href="http://127.0.0.1:42703/goroutine?id=4551248">runtime.timerproc</a> N=3<br><a href="http://127.0.0.1:42703/goroutine?id=8316656">net/http.(*connReader).backgroundRead</a> N=1<br>N=40</pre><p>click on the first item with N=441703 and this is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnGCMhzg6KU-3CEmUW7lXg.png" /><figcaption>goroutines analysis</figcaption></figure><p>this is very interesting. most of goroutines spend almost no time in execution and most of the time is spend in Sync block. let’s have a closer look at one of them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85ggeRId_MOHOB2jbBXTUw.png" /><figcaption>goroutine trace diagram</figcaption></figure><p>it appears our goroutine is almost always inactive waiting on a rwlock. from here we can directly go to block tool; blocking profile is disabled by default, we first need to enable it in our code:</p><pre>runtime.SetBlockProfileRate(1)</pre><p>now we can get our block samples:</p><pre>$ go tool pprof <a href="http://localhost:6060/debug/pprof/block">http://localhost:6060/debug/pprof/block</a><br>(pprof) top<br>Showing nodes accounting for 16.03wks, 99.75% of 16.07wks total<br>Dropped 87 nodes (cum &lt;= 0.08wks)<br>Showing top 10 nodes out of 27<br>      flat  flat%   sum%        cum   cum%<br>  10.78wks 67.08% 67.08%   10.78wks 67.08%  internal/poll.<strong>(*fdMutex).rwlock</strong><br>   5.25wks 32.67% 99.75%    5.25wks 32.67%  sync.<strong>(*Mutex).Lock</strong><br>         0     0% 99.75%    5.25wks 32.67%  cloud/redins/handler.(*DnsRequestHandler).Filter<br>         0     0% 99.75%    5.25wks 32.68%  cloud/redins/handler.(*DnsRequestHandler).FindANAME<br>         0     0% 99.75%   16.04wks 99.81%  cloud/redins/handler.(*DnsRequestHandler).HandleRequest<br>         0     0% 99.75%   10.78wks 67.08%  cloud/redins/handler.(*DnsRequestHandler).Response<br>         0     0% 99.75%   10.78wks 67.08%  cloud/redins/handler.(*RequestContext).Response<br>         0     0% 99.75%    5.25wks 32.67%  cloud/redins/handler.ChooseIp<br>         0     0% 99.75%   16.04wks 99.81%  github.com/miekg/dns.(*ServeMux).ServeDNS<br>         0     0% 99.75%   16.04wks 99.81%  github.com/miekg/dns.(*Server).serveDNS<br>(pprof)</pre><p>here we have two different lock (poll.fdMutex and sync.Mutex) responsible for almost 100% of blocks. this verifies our guess about lock contention, now we only need to find were these happens:</p><pre>(pprof) svg lock</pre><p>this command creates a vector graph of all nodes accounting for contention with focus on lock functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*9YUzsrY9uR-nh7ctO-79hA.png" /><figcaption>block endpoint svg graph</figcaption></figure><p>we can get the same result from our goroutine endpoint:</p><pre>$ go tool pprof <a href="http://localhost:6060/debug/pprof/goroutine">http://localhost:6060/debug/pprof/goroutine</a></pre><p>and then:</p><pre>(pprof) top<br>Showing nodes accounting for 294412, 100% of 294424 total<br>Dropped 84 nodes (cum &lt;= 1472)<br>Showing top 10 nodes out of 32<br>      flat  flat%   sum%        cum   cum%<br>    294404   100%   100%     294404   100%  <strong>runtime.gopark</strong><br>         8 0.0027%   100%     294405   100%  github.com/miekg/dns.(*Server).serveUDPPacket<br>         0     0%   100%      58257 19.79%  cloud/redins/handler.(*DnsRequestHandler).Filter<br>         0     0%   100%      58259 19.79%  cloud/redins/handler.(*DnsRequestHandler).FindANAME<br>         0     0%   100%     293852 99.81%  cloud/redins/handler.(*DnsRequestHandler).HandleRequest<br>         0     0%   100%     235406 79.95%  cloud/redins/handler.(*DnsRequestHandler).Response<br>         0     0%   100%     235406 79.95%  cloud/redins/handler.(*RequestContext).Response<br>         0     0%   100%      58140 19.75%  cloud/redins/handler.ChooseIp<br>         0     0%   100%     293852 99.81%  github.com/miekg/dns.(*ServeMux).ServeDNS<br>         0     0%   100%     293900 99.82%  github.com/miekg/dns.(*Server).serveDNS<br>(pprof)</pre><p>almost all our goroutines are staying at runtime.gopark, this is go scheduler putting goroutines to sleep; a very common cause for this to happen is lock contention</p><pre>(pprof) svg gopark</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mitkUjpi03jmy4MokjDlpA.png" /><figcaption>goroutines endpoint svg graph</figcaption></figure><p>here we have our two sources of contention:</p><h4>UDPConn.WriteMsg()</h4><p>looks like all responses ended up writing to the same fd (hence the lock), this makes sense because they all have the same source address.</p><p>we did a little experiment on different solutions, at the end we decided to use multiple listeners to balance the load, this way we let OS balance incoming request between different connection and reduce contention.</p><h4>Rand()</h4><p>looks like there’s a lock underneath generic math/rand functions (more on this <a href="https://blog.sgmansfield.com/2016/01/the-hidden-dangers-of-default-rand/">here</a>). this can be easily fixed using Rand.New() which creates a random generator without the locking wrapper</p><pre>rg := rand.New(rand.NewSource(int64(time.Now().Nanosecond())))</pre><p>this is a little better but creating a new source every time is expensive. can we do better? in our case we don’t really need random number. we just need an even distribution for our load balancing and it turns out that Time.Nanoseconds() can do just fine.</p><p>now that we have eliminated all extra blockings. let’s see the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0DpMHF-GYiAJ7DRnQzLNw.png" /><figcaption>goroutine analysis</figcaption></figure><p>looks better but still most of time is spent on sync block. let’s take a look at synchronization blocking profile from trace UI main page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*F-IPcuWO62oaoI1RynQIDw.png" /><figcaption>sync block time graph</figcaption></figure><p>let’s take a look at ccache promote function from pprof’s block endpoint:</p><pre>(pprof) list promote<br>ROUTINE ======================== github.com/karlseguin/ccache.(*Cache).promote in ...<br>         0   9.66days (flat, cum) 99.70% of Total<br>         .          .    155: h.Write([]byte(key))<br>         .          .    156: return c.buckets[h.Sum32()&amp;c.bucketMask]<br>         .          .    157:}<br>         .          .    158:<br>         .          .    159:func (c *Cache) promote(item *Item) {<br>         .   9.66days    160: <strong>c.promotables &lt;- item</strong><br>         .          .    161:}<br>         .          .    162:<br>         .          .    163:func (c *Cache) worker() {<br>         .          .    164: defer close(c.donec)<br>         .          .    165:</pre><p>all ccache.Get() calls end up sending to a single c.promotables channel. cache being a crucial part of our service, we have to consider other options; <a href="https://github.com/dgraph-io/dgraph">Dgraph</a> has an excellent article about <a href="https://blog.dgraph.io/post/caching-in-go/">state of cache in go,</a> they also have an excellent cache module called <a href="https://github.com/dgraph-io/ristretto">ristretto</a>. unfortunately ristretto doesn’t support Ttl based eviction yet, we could workaround this problem by using a very large MaxCost and keep a timeout value in our cache struct (we wish to keep stale data in cache). let’s see the result using ristretto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkknA6ZP9KZ6ytlwcl7ZRw.png" /><figcaption>goroutine analysis</figcaption></figure><p>Great!</p><p>we managed to reduce maximum goroutine runtime from 5000 ms to 22 ms. still most of the execution time is split between “sync block” and “”scheduler wait”. let’s see if there’s anything we can do about that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*t9LyET5ROZZ_ldbZ4bu7UQ.png" /><figcaption>sync block time graph</figcaption></figure><p>there’s little more we can do about fdMutex.rwlock let’s now focus on the other one : gcMarkDone which is responsible for 53% of block time. this function is part of go garbage collection process. having these on hot spot are often a sign that we are putting a lot of pressure on gc.</p><h3>alloc optimization</h3><p>at this point it may be useful to see how go garbage collection works; go uses a tri-color mark and sweep collector. it keeps tracking of everything that’s allocated and once it reaches twice (or whatever value GOGC is set to) the size of previous size, GC sweep starts. mark happens in three phases:</p><ul><li>Mark Setup (STW)</li><li>Marking (concurrent)</li><li>Mark Termination (STW)</li></ul><p>Stop The World phases put the entire exectution to halt, although they’re generally very short, tight loops can extend their duration. that’s because currently (go v1.13) goroutines are only preemptible at function call points, thus it is possible for a tight loop to cause arbitrarily long pause time since GC waits for all goroutines to stop.</p><p>during marking gc utilizes about 25% of GOMAXPROCS but additional goroutines can be forced into <strong>mark assist, </strong>this happens when a rapidly allocating goroutine outruns the background marker, in order to reduce the latency caused by gc we need minimize heap usage; there are two things to note:</p><ol><li>number of allocations matters more than size (e.g 1000 allocations of a 20 bytes struct puts much more stress on heap than a single 20000 bytes allocation)</li><li>unlike languages like C/C++, not all allocations end up in heap. go compiler decides whether a variable escapes to heap or it can be allocated inside stack frame. unlike heap-allocated variables, stack-allocated variables do not put pressure on gc</li></ol><p>for more information on go memory model and gc design check this <a href="https://www.youtube.com/watch?v=M0HER1G5BRw">presentation</a>.</p><p>for alloc optimization we use a collection of go tools:</p><ul><li>cpu profiler to find hot allocations</li><li>memory profiler to track allocations</li><li>tracer for GC patterns</li><li>escape analysis to find why allocations happen</li></ul><p>let’s start with cpu profiler:</p><pre>$ go tool pprof http://localhost:6060/debug/pprof/profile?seconds=20<br>(pprof) top 20 -cum<br>Showing nodes accounting for 7.27s, 29.10% of 24.98s total<br>Dropped 315 nodes (cum &lt;= 0.12s)<br>Showing top 20 nodes out of 201<br>      flat  flat%   sum%        cum   cum%<br>         0     0%     0%     16.42s 65.73%  github.com/miekg/dns.(*Server).serveUDPPacket<br>     0.02s  0.08%  0.08%     16.02s 64.13%  github.com/miekg/dns.(*Server).serveDNS<br>     0.02s  0.08%  0.16%     13.69s 54.80%  github.com/miekg/dns.(*ServeMux).ServeDNS<br>     0.01s  0.04%   0.2%     13.48s 53.96%  github.com/miekg/dns.HandlerFunc.ServeDNS<br>     0.02s  0.08%  0.28%     13.47s 53.92%  main.handleRequest<br>     0.24s  0.96%  1.24%     12.50s 50.04%  cloud/redins/handler.(*DnsRequestHandler).HandleRequest<br>     0.81s  3.24%  4.48%      6.91s 27.66%  runtime.gentraceback<br>     3.82s 15.29% 19.78%      5.48s 21.94%  syscall.Syscall<br>     0.02s  0.08% 19.86%      5.44s 21.78%  cloud/redins/handler.(*DnsRequestHandler).Response<br>     0.06s  0.24% 20.10%      5.25s 21.02%  cloud/redins/handler.(*RequestContext).Response<br>     0.03s  0.12% 20.22%      4.97s 19.90%  cloud/redins/handler.(*DnsRequestHandler).FindANAME<br>     0.56s  2.24% 22.46%      4.92s 19.70%  <strong>runtime.mallocgc</strong><br>     0.07s  0.28% 22.74%      4.90s 19.62%  github.com/miekg/dns.(*response).WriteMsg<br>     0.04s  0.16% 22.90%      4.40s 17.61%  github.com/miekg/dns.(*response).Write<br>     0.01s  0.04% 22.94%      4.36s 17.45%  github.com/miekg/dns.WriteToSessionUDP<br>     1.43s  5.72% 28.66%      4.30s 17.21%  runtime.pcvalue<br>     0.01s  0.04% 28.70%      4.15s 16.61%  runtime.newstack<br>     0.06s  0.24% 28.94%      4.09s 16.37%  runtime.copystack<br>     0.01s  0.04% 28.98%      4.05s 16.21%  net.(*UDPConn).WriteMsgUDP<br>     0.03s  0.12% 29.10%      4.04s 16.17%  net.(*UDPConn).writeMsg</pre><p>we are particularly intereseted in functions linked with mallocgc, this is where mark assists happen</p><pre>(pprof) svg mallocgc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCAtsahAc5q7XaZSsehSwg.png" /></figure><p>we can track allocation using alloc endpoint, alloc_object option means total allocations count, there are other options for in use memory and allocation space.</p><pre>$ go tool pprof -alloc_objects <a href="http://localhost:6060/debug/pprof/allocs">http://localhost:6060/debug/pprof/allocs</a><br>(pprof) top -cum<br>Active filters:<br>   show=handler<br>Showing nodes accounting for 58464353, 59.78% of 97803168 total<br>Dropped 1 node (cum &lt;= 489015)<br>Showing top 10 nodes out of 19<br>      flat  flat%   sum%        cum   cum%<br>  15401215 15.75% 15.75%   70279955 71.86%  cloud/redins/handler.(*DnsRequestHandler).HandleRequest<br>   2392100  2.45% 18.19%   27198697 27.81%  cloud/redins/handler.(*DnsRequestHandler).FindANAME<br>    711174  0.73% 18.92%   14936976 15.27%  cloud/redins/handler.(*DnsRequestHandler).Filter<br>         0     0% 18.92%   14161410 14.48%  cloud/redins/handler.(*DnsRequestHandler).Response<br>  14161410 14.48% 33.40%   14161410 14.48%  cloud/redins/handler.(*RequestContext).Response<br>   7284487  7.45% 40.85%   11118401 11.37%  cloud/redins/handler.NewRequestContext<br>  10439697 10.67% 51.52%   10439697 10.67%  cloud/redins/handler.reverseZone<br>         0     0% 51.52%   10371430 10.60%  cloud/redins/handler.(*DnsRequestHandler).FindZone<br>   2680723  2.74% 54.26%    8022046  8.20%  cloud/redins/handler.(*GeoIp).GetSameCountry<br>   5393547  5.51% 59.78%    5393547  5.51%  cloud/redins/handler.(*DnsRequestHandler).LoadLocation</pre><p>from here on we can use list on each function and see if we can reduce memory allocation. let’s check a few :</p><h4>printf-like functions</h4><pre>(pprof) list handleRequest<br>Total: 97803168<br>ROUTINE ======================== main.handleRequest in /home/arash/go/src/cloud/redins/redins.go<br>   2555943   83954299 (flat, cum) 85.84% of Total<br>         .          .     35: l          *handler.RateLimiter<br>         .          .     36: configFile string<br>         .          .     37:)<br>         .          .     38:<br>         .          .     39:func handleRequest(w dns.ResponseWriter, r *dns.Msg) {<br>         .   11118401     40: context := handler.NewRequestContext(w, r)<br>   <strong>2555943</strong>    <strong>2555943</strong>     <strong>41</strong>: <strong>logger.Default.Debugf(&quot;handle request: [%d] %s %s&quot;, r.Id, context.RawName(), context.Type())</strong><br>         .          .     42:<br>         .          .     43: if l.CanHandle(context.IP()) {<br>         .   70279955     44:  h.HandleRequest(context)<br>         .          .     45: } else {<br>         .          .     46:  context.Response(dns.RcodeRefused)<br>         .          .     47: }<br>         .          .     48:}<br>         .          .     49:</pre><p>line 41 is particularly interesting, even when debug is disabled there’s still memory allocation, we can use escape analysis to investigate it more</p><p>go escape analysis tool is actually a compiler flag</p><pre>$ go build -gcflags &#39;-m&#39;</pre><p>you can add another -m for more information</p><pre>$ go build -gcflags &#39;-m -m&#39;</pre><p>for a better interface use <a href="https://github.com/loov/view-annotated-file">view-annotated-file</a>.</p><pre>$ go build -gcflags &#39;-m&#39;<br> </pre><pre>.<br>.<br>.</pre><pre>../redins.go:39:20: leaking param: w<br>./redins.go:39:42: leaking param: r<br>./redins.go:41:55: r.MsgHdr.Id escapes to heap<br>./redins.go:41:75: context.RawName() escapes to heap<br>./redins.go:41:91: context.Request.Type() escapes to heap<br>./redins.go:41:23: handleRequest []interface {} literal does not escape<br>./redins.go:219:17: leaking param: path</pre><pre>.<br>.<br>.</pre><p>here, all Debugf parameters escape to heap. this happens because of the way Debugf is defined:</p><pre>func (l *EventLogger) Debugf(format string, args ...interface{})</pre><p>all args parameters convert to interface{} type which always escape to heap. we can either remove debug logs or use a zero allocation log library like <a href="https://github.com/rs/zerolog">zerolog</a>.</p><p>for more information about escape analysis see “<a href="https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/">allocation eficiency in golang</a>”.</p><h4>string manipulation</h4><pre>(pprof) list reverseZone<br>Total: 100817064<br>ROUTINE ======================== cloud/redins/handler.reverseZone in /home/arash/go/src/cloud/redins/handler/handler.go<br>   6127746   10379086 (flat, cum) 10.29% of Total<br>         .          .    396:  logger.Default.Warning(&quot;log queue is full&quot;)<br>         .          .    397: }<br>         .          .    398:}<br>         .          .    399:<br>         .          .    400:func reverseZone(zone string) string {<br>         .    <strong>4251340    401: x := strings.Split(zone, &quot;.&quot;)</strong><br>         .          .    402: var y string<br>         .          .    403: for i := len(x) - 1; i &gt;= 0; i-- {<br>   <strong>6127746    6127746    404:  y += x[i] + &quot;.&quot;</strong><br>         .          .    405: }<br>         .          .    406: return y<br>         .          .    407:}<br>         .          .    408:<br>         .          .    409:func (h *DnsRequestHandler) LoadZones() {<br>(pprof)</pre><p>Since Go’s string is immutable, making temporary string cause allocations. Beginning with Go 1.10 there is a strings.Builder to efficiently build a string.</p><pre>(pprof) list reverseZone<br>Total: 93437002<br>ROUTINE ======================== cloud/redins/handler.reverseZone in /home/arash/go/src/cloud/redins/handler/handler.go<br>         0    7580611 (flat, cum)  8.11% of Total<br>         .          .    396:  logger.Default.Warning(&quot;log queue is full&quot;)<br>         .          .    397: }<br>         .          .    398:}<br>         .          .    399:<br>         .          .    400:func reverseZone(zone string) string {<br>         .    3681140    401: x := strings.Split(zone, &quot;.&quot;)<br>         .          .    402: var sb strings.Builder<br>         .    3899471    403: sb.Grow(len(zone)+1)<br>         .          .    404: for i := len(x) - 1; i &gt;= 0; i-- {<br>         .          .    405:  sb.WriteString(x[i])<br>         .          .    406:  sb.WriteByte(&#39;.&#39;)<br>         .          .    407: }<br>         .          .    408: return sb.String()</pre><p>since we don’t care about the value of reversed string we can eliminate Split() by simply reversing the whole string.</p><pre>(pprof) list reverseZone<br>Total: 89094296<br>ROUTINE ======================== cloud/redins/handler.reverseZone in /home/arash/go/src/cloud/redins/handler/handler.go<br>   3801168    3801168 (flat, cum)  4.27% of Total<br>         .          .    400:func reverseZone(zone string) []byte {<br>         .          .    401: runes := []rune(&quot;.&quot; + zone)<br>         .          .    402: for i, j := 0, len(runes)-1; i &lt; j; i, j = i+1, j-1 {<br>         .          .    403:  runes[i], runes[j] = runes[j], runes[i]<br>         .          .    404: }<br>   3801168    3801168    405: return []byte(string(runes))<br>         .          .    406:}<br>         .          .    407:<br>         .          .    408:func (h *DnsRequestHandler) LoadZones() {<br>         .          .    409: h.LastZoneUpdate = time.Now()<br>         .          .    410: zones, err := h.Redis.SMembers(&quot;redins:zones&quot;)</pre><p>more on string manipulation <a href="https://go101.org/article/string.html">here</a>.</p><h4>sync.Pool</h4><pre>(pprof) list GetASN<br>Total: 69005282<br>ROUTINE ======================== cloud/redins/handler.(*GeoIp).GetASN in /home/arash/go/src/cloud/redins/handler/geoip.go<br>   1146897    1146897 (flat, cum)  1.66% of Total<br>         .          .    231:func (g *GeoIp) GetASN(ip net.IP) (uint, error) {<br>   1146897    1146897    232: <strong>var record struct {<br>         .          .    233:  AutonomousSystemNumber uint `maxminddb:&quot;autonomous_system_number&quot;`</strong><br>         .          .    234: }<br>         .          .    235: err := <strong>g.ASNDB.Lookup(ip, &amp;record)</strong><br>         .          .    236: if err != nil {<br>         .          .    237:  logger.Default.Errorf(&quot;lookup failed : %s&quot;, err)</pre><pre>(pprof) list GetGeoLocation<br>Total: 69005282<br>ROUTINE ======================== cloud/redins/handler.(*GeoIp).GetGeoLocation in /home/arash/go/src/cloud/redins/handler/geoip.go<br>   1376298    3604572 (flat, cum)  5.22% of Total<br>         .          .    207:<br>         .          .    208:func (g *GeoIp) GetGeoLocation(ip net.IP) (latitude float64, longitude float64, country string, err error) {<br>         .          .    209: if !g.Enable || g.CountryDB == nil {<br>         .          .    210:  return<br>         .          .    211: }<br>   1376298    1376298    212: <strong>var record struct {<br>         .          .    213:  Location struct {<br>         .          .    214:   Latitude        float64 `maxminddb:&quot;latitude&quot;`<br>         .          .    215:   LongitudeOffset uintptr `maxminddb:&quot;longitude&quot;`<br>         .          .    216:  } `maxminddb:&quot;location&quot;`<br>         .          .    217:  Country struct {<br>         .          .    218:   ISOCode string `maxminddb:&quot;iso_code&quot;`<br>         .          .    219:  } `maxminddb:&quot;country&quot;`<br>         .          .    220: }</strong><br>         .          .    221: // logger.Default.Debugf(&quot;ip : %s&quot;, ip)<br>         .          .    222: if err := <strong>g.CountryDB.Lookup(ip, &amp;record)</strong>; err != nil {<br>         .          .    223:  logger.Default.Errorf(&quot;lookup failed : %s&quot;, err)<br>         .          .    224:  return 0, 0, &quot;&quot;, err<br>         .          .    225: }<br>         .    2228274    226: _ = g.CountryDB.<strong>Decode(record.Location.LongitudeOffset, &amp;longitude)</strong><br>         .          .    227: // logger.Default.Debug(&quot;lat = &quot;, record.Location.Latitude, &quot; lang = &quot;, longitude, &quot; country = &quot;, record.Country.ISOCode)<br>         .          .    228: return record.Location.Latitude, longitude, record.Country.ISOCode, nil<br>         .          .    229:}<br>         .          .    230:<br>         .          .    231:func (g *GeoIp) GetASN(ip net.IP) (uint, error) {</pre><p>we use <a href="http://github.com/oschwald/maxminddb-golang">maxmiddb</a> functions to get geolocation data. these functions take interface{} as parameters which as we saw earlier can cause heap escapes.</p><p>we can use sync.Pool to cache allocated but unused items for later reuse</p><pre>type MMDBGeoLocation struct {<br>   Coordinations struct {<br>      Latitude        float64 `maxminddb:&quot;latitude&quot;`<br>      Longitude       float64<br>      LongitudeOffset uintptr `maxminddb:&quot;longitude&quot;`<br>   } `maxminddb:&quot;location&quot;`<br>   Country struct {<br>      ISOCode string `maxminddb:&quot;iso_code&quot;`<br>   } `maxminddb:&quot;country&quot;`<br>}<br><br>type MMDBASN struct {<br>   AutonomousSystemNumber uint `maxminddb:&quot;autonomous_system_number&quot;`<br>}</pre><pre>func (g *GeoIp) GetGeoLocation(ip net.IP) (*MMDBGeoLocation, error) {<br>   if !g.Enable || g.CountryDB == nil {<br>      return nil, EMMDBNotAvailable<br>   }<br>   var record *MMDBGeoLocation = g.LocationPool.Get().(*MMDBGeoLocation)<br>   logger.Default.Debugf(&quot;ip : %s&quot;, ip)<br>   if err := g.CountryDB.Lookup(ip, &amp;record); err != nil {<br>      logger.Default.Errorf(&quot;lookup failed : %s&quot;, err)<br>      return nil, err<br>   }<br>   _ = g.CountryDB.Decode(record.Coordinations.LongitudeOffset, &amp;record.Coordinations.Longitude)<br>   logger.Default.Debug(&quot;lat = &quot;, record.Coordinations.Latitude, &quot; lang = &quot;, record.Coordinations.Longitude, &quot; country = &quot;, record.Country.ISOCode)<br>   return record, nil<br>}<br><br>func (g *GeoIp) GetASN(ip net.IP) (uint, error) {<br>   var record *MMDBASN = g.AsnPool.Get().(*MMDBASN)<br>   err := g.ASNDB.Lookup(ip, record)<br>   if err != nil {<br>      logger.Default.Errorf(&quot;lookup failed : %s&quot;, err)<br>      return 0, err<br>   }<br>   logger.Default.Debug(&quot;asn = &quot;, record.AutonomousSystemNumber)<br>   return record.AutonomousSystemNumber, nil<br>}</pre><p>more on sync.Pool <a href="https://medium.com/a-journey-with-go/go-understand-the-design-of-sync-pool-2dde3024e277">here</a>.</p><p>there are many other small optimimazions possible, but at this point it seems we have done enough. for more information about memory optimization techniques check <a href="https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/">Allocation efficiency in high-performance Go services</a></p><h3>results</h3><p>to visualize the result of our memory optimizations we use a diagram in go tool trace called “Minimum Mutator Utilization”, here Mutator means not gc.</p><p>before optimizations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*Rs7684xZdrmfU9LScTLlgA.png" /></figure><p>here we have a window of about 500 milliseconds while we have almost no utilization(gc is consuming all resources) and we never get past 80% utilization in the long run. we want to have the zero utilization window as small as possible and get to 100% percent utilization as fast as possible, something like this:</p><p>after optimizations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*OzJRjaZ5mHf9cCu4qs5pVg.png" /></figure><h3>conclusion</h3><p>by using go tools we managed to optimize our service to handle high load of requests and better utilize system recources.</p><p>you can check our source code on <a href="https://github.com/arvancloud/redins">github</a>.</p><h3>further readings</h3><ul><li><a href="https://github.com/dgryski/go-perfbook">go perfbook</a></li><li><a href="https://golang.org/doc/effective_go.html">effective go</a></li><li><a href="https://bravenewgeek.com/so-you-wanna-go-fast/">so you wanna go fast</a></li><li><a href="https://go-talks.appspot.com/github.com/davecheney/presentations/writing-high-performance-go.slide">writing high performace go</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d753e1a5e709" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>