<?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 Akshay Deo on Medium]]></title>
        <description><![CDATA[Stories by Akshay Deo on Medium]]></description>
        <link>https://medium.com/@akshay_deo?source=rss-bd68ca4f9376------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MKGvmTa3JyumR0vrAC3VGA.jpeg</url>
            <title>Stories by Akshay Deo on Medium</title>
            <link>https://medium.com/@akshay_deo?source=rss-bd68ca4f9376------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:54:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akshay_deo/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[How did I improve latency by 700% using sync.Pool]]></title>
            <link>https://medium.com/@akshay_deo/how-did-i-improve-latency-by-700-using-sync-pool-46324c078c25?source=rss-bd68ca4f9376------2</link>
            <guid isPermaLink="false">https://medium.com/p/46324c078c25</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[scaling-microservices]]></category>
            <dc:creator><![CDATA[Akshay Deo]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 05:03:11 GMT</pubDate>
            <atom:updated>2019-10-17T05:03:11.709Z</atom:updated>
            <content:encoded><![CDATA[<p>We @media.net write superfast backends with at max 30–40ms turn-around time from web-service. We continuously try to reduce money spent per request. This blog enlists a few of our findings.</p><blockquote><em>Precautionary warning: It’s a long post with a lot of code. Comment if I am unclear, abstract or vague at any point.</em></blockquote><h3>Why use sync.Pool?</h3><p>sync.Pool [1] comes really handy when one wants to reduce the number of allocations happening during the course of a functionality written in Golang. A Pool is a set of temporary objects that may be individually saved and retrieved. fasthttp [2], zerolog [3] are couple of those most popuplar open source Golang libraries which uses sync.Pool at the core of their implementation.</p><h3>How to use sync.Pool?</h3><p>Consider the following example:</p><pre>import (<br>	&quot;fmt&quot;<br>	&quot;sync&quot;<br>	&quot;time&quot;<br>)<br><br>// Pool for our struct A<br>var pool *sync.Pool<br><br>// A dummy struct with a member <br>type A struct {<br>	Name string<br>}<br><br>// Func to init pool<br>func initPool() {<br>	pool = &amp;sync.Pool {<br>		New: func()interface{} {<br>			fmt.Println(&quot;Returning new A&quot;)<br>			return new(A)<br>		},<br>	}<br>}<br><br>// Main func<br>func main() {<br>	// Initializing pool<br>	initPool()<br>	// Get hold of instance one<br>	one := pool.Get().(*A)<br>	one.Name = &quot;first&quot;<br>	fmt.Printf(&quot;one.Name = %s\n&quot;, one.Name)<br>	// Submit back the instance after using<br>	pool.Put(one)<br>	// Now the same instance becomes usable by another routine without allocating it again<br>}</pre><h3>Benchmarks</h3><p>I picked one of the most commonly used API from our web-service which</p><ul><li>Performs 4 cache queries</li><li>Sends 5 separate events onto Kafka</li><li>Calls 2 separate micro-services synchronously</li></ul><p>I ran a load test of 10-rps on my local machine for 10 seconds first on pooled-flow and then on non-pooled flow.</p><blockquote><em>These latencies are higher because this service was running in Pune (India) office and communicating with other microservices running in Oregon (United States) :).</em></blockquote><h3>For pooled version</h3><pre>Requests      [total, rate]            100, 10.10<br>Duration      [total, attack, wait]    10.189033566s, 9.899999979s, 289.033587ms<br>Latencies     [mean, 50, 95, 99, max]  241.952809ms, 252.716311ms, 476.400585ms, 491.370124ms, 503.938792ms<br>Bytes In      [total, mean]            8400, 84.00<br>Bytes Out     [total, mean]            0, 0.00<br>Success       [ratio]                  100.00%<br>Status Codes  [code:count]             200:100<br>Error Set:</pre><h3>For non-pooled version</h3><pre>Requests      [total, rate]            100, 10.10<br>Duration      [total, attack, wait]    13.28824244s, 9.899999931s, 3.388242509s<br>Latencies     [mean, 50, 95, 99, max]  880.57307ms, 325.619739ms, 3.476523432s, 3.685206241s, 3.888228236s<br>Bytes In      [total, mean]            8400, 84.00<br>Bytes Out     [total, mean]            0, 0.00<br>Success       [ratio]                  100.00%<br>Status Codes  [code:count]             200:100</pre><h3>Observations</h3><ul><li><strong>We get an almost 700x performance boost. (95th percentile)</strong></li><li>For most of the objects, the ratio of allocation to reuse was almost 10–15 times. This means the object was allocated probably 5 times and being used almost 50–70 times, during the course of this benchmark.</li></ul><h3>Here are some of the outcomes of one of our services</h3><ul><li>Almost 78% of the objects were reused in course of a load test</li><li>During the distributed load, this number will improve a lot</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CYaM3f9Sf7GCh1sj.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WeGlwzSTM3DZiMuF.png" /></figure><h3>Precautions to be taken while using sync.Pool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*pmZN-qk--kSagRUN.jpg" /></figure><h3>What if you pass a pooled object to a go-routine and submit it back to the pool before go-routine yet to complete the execution?</h3><p>This is a pickle, once you put back the object, it’s ready for reuse. So before you putting back the object inside the pool, you have to be sure that nothing else is using the same object for any other operation.</p><p>Example code — <a href="https://play.golang.org/p/64SoX7W-x1H">play.golang.org</a></p><h3>Let’s consider this flow in a more practical use case</h3><p>Here is the typical flow for a Web-Service API.</p><blockquote><em>Let’s assume that our controller is using pooled struct to read body of the incoming request.</em></blockquote><ol><li>Go server accepts the request, spawns a go-routine and calls your controller. Typically a func like func HandleRequest(w http.ResponseWriter, r *http.Request).</li><li>Let’s consider it’s a POST API call, and we read the body of the request, map it to a struct A.</li><li>Now through the course of flow, we might do some of the operations on the object in async manner, in a separate go-routine.</li><li>At the end of controller functionality, we put back the object into the pool for reuse.</li></ol><p>Refer the following diagram showing the flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rMZFs-udmjCChUcM.png" /></figure><p><strong>The issue here is</strong>, what if Async Call 1 takes more time and before it completes it’s functionality, your controller has written the response, and object is put back into the pool!</p><h3>Solution</h3><p>The only solution to it is manual reference counting for the pooled objects. When I started googling about the solution, I came across a nicely written blog here[4].</p><p>The basic flow for Reference Counting will be:</p><ul><li>Increment the counter at the time of Acquiring the object</li><li>Decrement the counter once the routine is done using it</li><li>Increment the counter before passing the object inside a go-routine or channel</li><li>Decrement the counter once the routine is done with processing the object</li><li>An object is only put back into the pool when the reference count is zero.</li></ul><h3>Implementation</h3><blockquote><em>This implementation is highly inspired from the hydrogen18 blog, but has some modifications which are necessary for a practical web app.</em></blockquote><p>We will have an interface to have a blueprint of how a Reference Countable object will be implemented</p><pre>// Interface following reference countable interface<br>// We have provided inbuilt embeddable implementation of the reference countable pool<br>// This interface just provides the extensibility for the implementation<br>type ReferenceCountable interface {<br>	// Method to set the current instance<br>	SetInstance(i interface{})<br>	// Method to increment the reference count<br>	IncrementReferenceCount()<br>	// Method to decrement reference count<br>	DecrementReferenceCount()<br>}</pre><ul><li>IncrementReferenceCount to increase the reference count of the current object</li><li>DecrementReferenceCount to decrease the reference count of the current object</li></ul><p>We will write a struct that implements this interface, which can be embedded in our own structs.</p><pre>// Struct representing reference<br>// This struct is supposed to be embedded inside the object to be pooled<br>// Along with that incrementing and decrementing the references is highly important specifically around routines<br>type ReferenceCounter struct {<br>	count       *uint32                 `sql:&quot;-&quot; json:&quot;-&quot; yaml:&quot;-&quot;`<br>	destination *sync.Pool              `sql:&quot;-&quot; json:&quot;-&quot; yaml:&quot;-&quot;`<br>	released    *uint32                 `sql:&quot;-&quot; json:&quot;-&quot; yaml:&quot;-&quot;`<br>	Instance    interface{}             `sql:&quot;-&quot; json:&quot;-&quot; yaml:&quot;-&quot;`<br>	reset       func(interface{}) error `sql:&quot;-&quot; json:&quot;-&quot; yaml:&quot;-&quot;`<br>	id          uint32                  `sql:&quot;-&quot; json:&quot;-&quot; yaml:&quot;-&quot;`<br>}<br><br>// Method to increment a reference<br>func (r ReferenceCounter) IncrementReferenceCount() {<br>	atomic.AddUint32(r.count, 1)<br>}<br><br>// Method to decrement a reference<br>// If the reference count goes to zero, the object is put back inside the pool<br>func (r ReferenceCounter) DecrementReferenceCount() {<br>	if atomic.LoadUint32(r.count) == 0 {<br>		panic(&quot;this should not happen =&gt;&quot; + reflect.TypeOf(r.Instance).String())<br>	}<br>	if atomic.AddUint32(r.count, ^uint32(0)) == 0 {<br>		atomic.AddUint32(r.released, 1)<br>		if err := r.reset(r.Instance); err != nil {<br>			panic(&quot;error while resetting an instance =&gt; &quot; + err.Error())<br>		}<br>		r.destination.Put(r.Instance)<br>		r.instance = nil<br>	}<br>}<br><br>// Method to set the current instance<br>func (r *ReferenceCounter) SetInstance(i interface{}) {<br>	r.instance = i<br>}</pre><ul><li>Reference counter specifically does the job of thread safe reference counting</li><li>Along with that, it puts back the instance associated with the counter into the pool as soon as the reference count becomes zero</li><li>Reset function ideally resets all the members of the instance of an object.</li><li>This is necessary in most of the practical use cases</li></ul><p>Consider the following struct</p><pre>type A struct{<br>      First string `json:&quot;f&quot;`<br>      Second string `json:&quot;s&quot;`<br>      Third int `json:&quot;t&quot;`<br>  }</pre><p>Suppose that while using for the first time we got a JSON like following</p><pre>{<br>      &quot;f&quot; : &quot;one&quot;,<br>      &quot;t&quot; : 1,<br>  }</pre><ul><li>We do the processing and put back the object inside the pool.</li><li>Now we got the second request with following JSON</li></ul><pre>{<br>      &quot;s&quot; : &quot;second&quot;,<br>}</pre><ul><li>Technically the resulting struct should have First as “”, Third as 0. But as we are using pooled objects, First will be “one” and Third will be 1.</li><li>Hence we use a Reset function that reset all the members of the object before puting it back in the pool.</li></ul><p>And finally the pool, Reference coutable pool</p><pre>// Struct representing the pool<br>type referenceCountedPool struct {<br>	pool       *sync.Pool<br>	factory    func() ReferenceCountable<br>	returned   uint32<br>	allocated  uint32<br>	referenced uint32<br>}<br><br>// Method to create a new pool<br>func NewReferenceCountedPool(factory func(referenceCounter ReferenceCounter) ReferenceCountable, reset func(interface{}) error) *referenceCountedPool {<br>	p := new(referenceCountedPool)<br>	p.pool = new(sync.Pool)<br>	p.pool.New = func() interface{} {<br>		// Incrementing allocated count<br>		atomic.AddUint32(&amp;p.allocated, 1)<br>		c := factory(ReferenceCounter{<br>			count:       new(uint32),<br>			destination: p.pool,<br>			released:    &amp;p.returned,<br>			reset:       reset,<br>			id:          p.allocated,<br>		})<br>		return c<br>	}<br>	return p<br>}<br><br>// Method to get new object<br>func (p *referenceCountedPool) Get() ReferenceCountable {<br>	c := p.pool.Get().(ReferenceCountable)<br>	c.SetInstance(c)<br>	atomic.AddUint32(&amp;p.referenced, 1)<br>	c.IncrementReferenceCount()<br>	return c<br>}<br><br>// Method to return reference counted pool stats<br>func (p *referenceCountedPool) Stats() map[string]interface{} {<br>	return map[string]interface{}{&quot;allocated&quot;: p.allocated, &quot;referenced&quot;: p.referenced, &quot;returned&quot;: p.returned}<br>}</pre><p>Now start using the ReferenceCoutedPool as following:</p><p>Consider following struct Event</p><pre>// Struct representing an event<br>type Event struct {<br>	pool.ReferenceCounter `sql:&quot;-&quot;`<br><br>	Name      string    `json:&quot;name&quot;`<br>	Log       string    `json:&quot;log&quot;`<br>	Timestamp time.Time `json:&quot;timestamp&quot;`<br>}<br><br>// Method to reset event<br>func (e *Event) Reset() {<br>	e.Name = &quot;&quot;<br>	e.Log = &quot;&quot;<br>	e.Timestamp = 0<br>}<br><br>// Method to reset Event<br>// Used by reference countable pool<br>func ResetEvent(i interface{}) error {<br>	obj, ok := i.(*Event)<br>	if !ok {<br>		errors.New(&quot;illegal object sent to ResetEvent&quot;, i)<br>	}<br>	obj.Reset()<br>	return nil<br>}<br><br>// Method to create new event<br>func NewEvent(name, log string, timestamp time.Time) *Event {<br>	e := AcquireEvent()<br>	e.Name = name<br>	e.Log = log<br>	e.Timestamp = timestamp<br>	return e<br>}</pre><p>And finally the Event pool</p><pre>// Event pool<br>var eventPool = pool.NewReferenceCountedPool(<br>	func(counter pool.ReferenceCounter) pool.ReferenceCountable {<br>		br := new(Event)<br>		br.ReferenceCounter = counter<br>		return br<br>	}, ResetEvent)<br><br>// Method to get new Event<br>func AcquireEvent() *Event {<br>	return eventPool.Get().(*Event)<br>}</pre><p>Basic usage:</p><pre>e := models.NewEvent(&quot;test&quot;, &quot;this is a test log&quot;, time.Now())<br>defer e.DecrementReferenceCount()</pre><h3>Conclusion</h3><p>This entire method seems a bit of an overhead, and requires a lot more precision while coding. You miss Reference counting at one place and it could result in a lot of unwanted results. But this works like a charm (see the benchmarks) once you get it right.</p><p>Let me know your opinions, doubts, arguments here or at akshay[at]akshaydeo.com. Happy coding \m/</p><h3>References</h3><ul><li>[1] <a href="https://golang.org/pkg/sync/#Pool">https://golang.org/pkg/sync/#Pool</a></li><li>[2] <a href="https://github.com/valyala/fasthttp">https://github.com/valyala/fasthttp</a></li><li>[3] <a href="https://github.com/rs/zerolog">https://github.com/rs/zerolog</a></li><li>[4] <a href="http://www.hydrogen18.com/blog/reference-counted-pool-golang.html">http://www.hydrogen18.com/blog/reference-counted-pool-golang.html</a></li></ul><p><em>Originally published at </em><a href="https://www.akshaydeo.com/blog/2017/12/23/How-did-I-improve-latency-by-700-percent-using-syncPool/"><em>https://www.akshaydeo.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46324c078c25" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>