<?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 Tarun Batra on Medium]]></title>
        <description><![CDATA[Stories by Tarun Batra on Medium]]></description>
        <link>https://medium.com/@tbking?source=rss-f56925460d9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*FPggvG7jc4PKSaJ2qsERUg.png</url>
            <title>Stories by Tarun Batra on Medium</title>
            <link>https://medium.com/@tbking?source=rss-f56925460d9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:00:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tbking/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[Polling reliably at scale using DLQs]]></title>
            <link>https://medium.com/making-smalltalk/polling-reliably-at-scale-using-dlqs-841512659c8f?source=rss-f56925460d9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/841512659c8f</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Tarun Batra]]></dc:creator>
            <pubDate>Tue, 16 Jul 2019 10:38:47 GMT</pubDate>
            <atom:updated>2020-06-15T18:08:12.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Hf5GUNSLkcsNKJKXFPzhA.png" /></figure><h4>How we bid goodbye to long waiting times during order execution.</h4><p>Execution of computer programs is blazing fast. It’s only practical to sometimes need a delay in execution. Some of such use cases are:</p><ul><li>scheduling a task for some time in the future;</li><li>retrying a failed task with a backoff strategy</li></ul><p>At smallcase, we place orders to buy or sell equities on clients’ behalf. When the order is placed, it’s execution status is not immediately known. We need to poll the partner broker to know the status of the order on the exchange.</p><p>Intraday traders will tell you that stock markets are time-sensitive. Any platform that caters to them needs to be fast and deterministic. Polling for order status needs to happen in a timely manner after regular intervals because an endless loading is never a pleasant sight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*z237Zq0WoNlhxJBBnEbTHQ.gif" /></figure><blockquote>This blog explains the reliability issues we faced with our legacy system for scheduling polling and how we fixed it.</blockquote><h3>Delay mechanisms:</h3><p>We will discuss the following delay mechanisms we used in our platform:</p><ul><li><a href="#de86">Redis Keyspace Notifications</a></li><li><a href="#a2a5">In-memory timers</a></li><li><a href="#022f">Dead letter queues</a></li></ul><h3>Redis Keyspace Notifications</h3><p>This approach is very simple. We heavily use Redis in our stack, so it was easy for us to use it for scheduling triggers. Redis allows setting keys with expiry using its <a href="https://redis.io/commands/setex">SETEX</a> command. For instance, setting a key TESTKEY with value TESTVALUE and expiry of 10 seconds can be achieved with:</p><pre>&gt;redis SETEX TESTKEY 10 “TESTVALUE”</pre><p>Parallely, Redis provides <a href="https://redis.io/topics/notifications">Keyspace notifications</a> for data changing events which can be subscribed by clients and can be used to trigger the delayed tasks. Key expiry events can be subscribed using:</p><pre>SUBSCRIBE __keyevent@0__:expired</pre><h4>Pros:</h4><ol><li><strong>Stateless application code.</strong> The application doesn’t need to store the tasks to perform and delays in its memory. It is outsourced to Redis.</li><li><strong>Arbitrary delays.</strong> Delays of arbitrary length are possible without any extra configuration. Just changing the ttl parameter of SETEX command will work.</li></ol><h4>Cons:</h4><ol><li><strong>Unscalable.</strong> This strategy works only until there’s only one instance of the application listening to these events. In case this application is to be horizontally scaled, each instance of the application will receive the event because of its <a href="https://redis.io/topics/pubsub">publish-subscribe nature</a>.</li><li><strong>Unreliable.</strong> The keyspace notifications can get highly unreliable as the number of keys increase. This is clearly mentioned in the docs:</li></ol><blockquote>If no command targets the key constantly, and there are many keys with a TTL associated, there can be a significant delay between the time the key time to live drops to zero, and the time the expired event is generated.</blockquote><p>This worked fine for us in the beginning. But once the orders increased, a lot of clients started reporting really long waiting periods before they could see the status of their orders. On debugging, we saw delays of the tune of 40x and this was the deal-breaker for us.</p><h3>In-memory timers</h3><p>As a quick fix to this, we used in-memory timers. Timers are defined and executed by the application code itself and can be used to manage delays. Node.js provides a variety of in-built <a href="https://nodejs.org/en/docs/guides/timers-in-node/">timer functions</a>. Setting a 10-second timer is as simple as:</p><pre>setTimeout(() =&gt; {<br> console.log(‘This executes after 10 seconds’);<br>}, 10 * 1000);</pre><h4>Pros:</h4><ol><li><strong>Arbitrary delays.</strong> Delay time is controlled by the time argument only. Passing the required delay time in milliseconds is all that is required.</li><li><strong>Reliability.</strong> Timers in the code are quite reliable. Deviation of only up to few milliseconds is observed.</li></ol><h4>Cons:</h4><ol><li><strong>Stateful application code.</strong> The application adds to its state whenever a timer is set up. It also increases the memory footprint of the application.</li><li><strong>Unscalable.</strong> In-memory timers do not work well with horizontal scaling. Timer will always trigger the instance which set it in the first place, irrespective of the traffic distribution across the instances.</li></ol><blockquote>Timers worked well to mask the problem until we had bandwidth to think about the problem and fix it for good. Now we needed a permanent and reliable solution that would scale.</blockquote><h3>Dead Letter Queues</h3><p>After researching a bit about this topic, we decided to try Dead letter queues. DLQ is a sophisticated but robust way to delay message delivery used in message queues like Amazon SQS, RabbitMQ and ActiveMQ.</p><p>In very basic terms, a message with an expiry is put into a queue. The queue is instructed to take some action if the messages are expired without being read. If the expired messages are pushed to a different queue which is actively consumed by the target application, it simulates a delayed delivery of the message. Following diagram explains this concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*cbRY7OKUXTFQbopS" /><figcaption>Polling delay mechanism</figcaption></figure><p>We chose RabbitMQ based on AMQP 0–9–1 for our implementation due to the maturity of the protocol and its community.</p><h4>Pros:</h4><ol><li><strong>Stateless application code.</strong> The application doesn’t need to store any state. The messages in the queue represent the state in this case.</li><li><strong>Scalable.</strong> Unlike Redis events, message delivery in MQs can be configured to use <a href="https://www.rabbitmq.com/tutorials/tutorial-two-javascript.html">worker pattern</a> which load balances the consumers (subscribing instances of the application) to deliver the message.</li><li><strong>Reliability.</strong> Message Queues are expected to be highly reliable in the delivery of messages. In our testing with RabbitMQ, the results were found to be close to in-memory timers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*0llL-1sU3g22TIgr" /><figcaption>Source: RabbitMQ docs</figcaption></figure><h4>Cons:</h4><ol><li><strong>Fixed delays.</strong> In RabbitMQ’s implementation of DLQs, the TTL is bound to the queue and applies to all the incoming messages. There is a way to set message level TTL but it has its own <a href="https://www.rabbitmq.com/ttl.html#per-message-ttl-caveats">caveats</a>. One of the most serious side-effects of using message-level TTL is that a message with higher TTL will block the queue and delay the processing of messages with lower TTL behind it, which is a bigger problem. Hence, we are using DLQs with queue level TTL.</li></ol><p>The chart shown below analyzes the average delay observed in resolving the orders we handled in the past year and its relation with the delay mechanism being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hjr5Pe6RNEvjXJ7M" /><figcaption>Graph showing consistency in the polling scheduled using RabbitMQ DLQs</figcaption></figure><p>It is clear that the polling delay in Redis was large but consistent to start with but grew out of proportions quickly as the volumes increased. This was quickly fixed using timers but like all quick-fixes, it had a short life too. Finally, we revamped our systems and used DLQs.</p><blockquote>It is evident from the graph that DLQs brought consistency to the system.</blockquote><p>We traded flexibility with robustness and reliability by using DLQs to manage the delays in our polling for order status. If you’ve solved a related problem in any other way, do let us know in the comments.</p><p><em>Originally published at </em><a href="https://blog.smallcase.com/polling-reliably-at-scale-using-dlqs/"><em>https://blog.smallcase.com</em></a><em> on July 16, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=841512659c8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/making-smalltalk/polling-reliably-at-scale-using-dlqs-841512659c8f">Polling reliably at scale using DLQs</a> was originally published in <a href="https://medium.com/making-smalltalk">Making smalltalk</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pitfalls of Mocha’s built-in Promise support]]></title>
            <link>https://medium.com/@tbking/pitfalls-of-mochas-built-in-promise-support-49299409ba37?source=rss-f56925460d9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/49299409ba37</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Tarun Batra]]></dc:creator>
            <pubDate>Tue, 18 Apr 2017 21:59:26 GMT</pubDate>
            <atom:updated>2017-04-18T21:59:26.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*_iUXdgHo6UzzHnXnTAIKVw.png" /><figcaption>False positive test</figcaption></figure><p><a href="https://mochajs.org/">Mocha</a> is the leader when it comes to testing frameworks in <a href="https://nodejs.org/">Node</a>, and it’s great. I use it in all my projects, and I’m sure many others do too.</p><p>Mocha added support for Promises back in version 1.18.0. Recently while testing asynchronous code written using Promises, I was using the <a href="https://mochajs.org/#working-with-promises">built-in promise support</a> instead of the old-fashioned callbacks oriented <a href="https://mochajs.org/#asynchronous-code">done callback</a> and I found my tests were resulting in <strong>false positives</strong>. So here I’m explaining what happened and how to avoid it.</p><h3>Problem</h3><p>It’s easy to see that there are four possible cases when testing Promises:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Qmd8v82hpwrT3_g8OnbQZw.png" /></figure><h4>Case 1</h4><pre>var promise = Promise.resolve();</pre><pre>describe(&#39;the promise resolves expectedly&#39;, () =&gt; {<br>  it(&#39;should PASS the test&#39;, () =&gt; {<br>    return promise.then(() =&gt; {<br>      console.log(&#39;Promise resolved!&#39;) //  Called<br>    });<br>  });<br>});</pre><blockquote>Test Status: PASS</blockquote><p>The test expects the promise to resolve and so it does. The snippet above shows that the test passes expectedly.</p><h4>Case 2</h4><pre>var promise = Promise.reject(new Error(&#39;some-error&#39;));</pre><pre>describe(&#39;the promise rejects unexpectedly&#39;, () =&gt; {<br>  it(&#39;should FAIL the test&#39;, () =&gt; { // =&gt; Error: some-error<br>    return promise.then(() =&gt; {<br>      console.log(&#39;Promise resolved!&#39;) // Not called<br>    });<br>  });<br>});</pre><blockquote>Test status: FAIL</blockquote><p>In the case when test expects the promise to resolve, but it doesn’t, Mocha gracefully fails the test. In the snippet above, the then block was never executed and Mocha detected the error rejected by the code and failed the test.</p><h4>Case 3</h4><pre>var promise = Promise.reject(new Error(&#39;some-error&#39;));<br>describe(&#39;the promise rejects expectedly&#39;, () =&gt; {<br>  it(&#39;should PASS the test&#39;, () =&gt; {<br>    return promise.catch(() =&gt; {<br>      console.log(&#39;Rejected promise caught!&#39;);  // Called<br>    });<br>  });<br>});</pre><blockquote>Test status: PASS</blockquote><p>The test expects the promise to be rejected and it is caught by the catch block, which results in this test passing as expected.</p><h4>Case 4</h4><pre>var promise = Promise.resolve();</pre><pre>describe(&#39;the promise resolves unexpectedly&#39;, () =&gt; {<br>  it(&#39;should FAIL the test&#39;, () =&gt; {<br>    return promise.catch(() =&gt; {<br>      console.log(&#39;Rejected promise caught!&#39;) // Not called<br>    });<br>  });<br>});</pre><blockquote>Test status: PASS</blockquote><p>In this case, the test expects the promise to be rejected and the catch block to execute but instead, it doesn’t. The promise resolves. Mocha doesn’t throw an error here!</p><p>So while doing <a href="https://en.wikipedia.org/wiki/Negative_Testing">Negative Testing</a>, the built-in promises support doesn’t hold up well and can result in <strong>false positives</strong>. This is not a bug and the reason behind this behavior totally makes sense, once given a careful thought, but at the very least, it’s not intuitive and causes the tests to pass even when they shouldn’t.</p><h3>Solution</h3><h4>Good ol’ done callback</h4><p>The simplest way to avoid this situation is to always handle the rejection scenarios yourself, rather than asking Mocha to do it. Here’s how:</p><pre>var promise = Promise.resolve();</pre><pre>describe(&#39;the promise resolves unexpectedly&#39;, () =&gt; {<br>  it(&#39;should FAIL the test&#39;, (done) =&gt; {<br>    promise.catch(() =&gt; {<br>      console.log(&#39;Rejected promise caught!&#39;) // Not called<br>      done();                                 // Timeout!<br>    });<br>  });<br>});</pre><blockquote>Test status: FAIL</blockquote><p>The above test will fail due to timeout as Mocha waits for done to be called but it doesn’t, and times out eventually.</p><h4>Chained then block</h4><p>Another way to avoid this situation is to chain a then block to the existing catch block and assert that the catch was called.</p><pre>var expect = require(&#39;chai&#39;).expect;<br>var spy = require(&#39;sinon&#39;).spy;<br>var exceptionHandler = spy();<br>var promise = Promise.resolve();</pre><pre>describe(&#39;the promise resolves unexpectedly&#39;, () =&gt; {<br>  it(&#39;should FAIL the test&#39;, () =&gt; {<br>    return promise.catch(exceptionHandler)<br>    .then(() =&gt; {<br>      // Assert that catch block was called<br>      expect(exceptionHandler.calledOnce).to.be.true;<br>    });<br>  });<br>});</pre><blockquote>Test status: FAIL</blockquote><p>The above test tries to assert that the catch block was called using <a href="http://chaijs.com/">Chai</a> and <a href="http://sinonjs.org/">Sinon</a>, and fails.</p><p>If you know other elegant ways to avoid this behavior, please let me know in the comments!</p><p><strong>❤️ code</strong></p><p><em>Originally published at </em><a href="http://tarunbatra.com/blog/javascript/Pitfalls-of-Mocha-s-built-in-Promise-support/"><em>tarunbatra.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49299409ba37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why you should use named functions in JavaScript]]></title>
            <link>https://medium.com/@tbking/why-you-should-use-named-functions-in-javascript-a56320f5cfb5?source=rss-f56925460d9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56320f5cfb5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Tarun Batra]]></dc:creator>
            <pubDate>Tue, 28 Feb 2017 18:32:03 GMT</pubDate>
            <atom:updated>2019-07-22T09:58:02.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*FKk3fL4fl92eo0qBpB0kIQ.jpeg" /></figure><p>JavaScript functions can be categorized into <em>named</em> or <em>anonymous</em> on the basis of the value of their <strong>name</strong> property. A named function can be declared as follows:</p><pre>function add(a, b) {</pre><pre>  return a + b;</pre><pre>}</pre><pre>console.log(add.name) // =&gt; &quot;add&quot;</pre><p>All other ways, including ES2015’s much-touted <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> produce anonymous functions. One of these ways is:</p><pre>var add = function (a, b) {</pre><pre>  return a + b;</pre><pre>}</pre><pre>console.log(add.name) // =&gt; &quot;&quot;</pre><p><strong>NOTE</strong>: If you tried the above code in Chrome Dev Tools, you would’ve noticed that the <strong>name</strong> of the function is “add” even in the case of anonymous function. That’s because modern-day interpreters are smart enough to recognize the name from the expression.</p><p>Now, what’s special about <strong>named functions</strong>?</p><h3>Make sense with error stacks</h3><p>Error and call stacks are a great help in debugging code. But the use of anonymous functions reduces the usefulness of the call stacks. We all have seen the infamous <strong>(anonymous)</strong> littered over the stack trace.</p><p>Of course, one can always look at the line number of the error, but with the ever-increasing pre-processing on the code (read Babel, WebPack, Browserify), this is not a reliable method.</p><h3>Error stack using anonymous function</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftbking%2Fembed%2Fpreview%2FOpVLwZ%3Fheight%3D600%26amp%3Bslug-hash%3DOpVLwZ%26amp%3Bdefault-tabs%3Djs%2Cresult%26amp%3Bhost%3Dhttp%253A%252F%252Fcodepen.io%26amp%3Bembed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftbking%2Fpen%2FOpVLwZ&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1118411.OpVLwZ.small.77a4afb2-6ae3-4b6c-96f2-7f3afc1559f2.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/95e2c82703963ec19380a0a1d55ee7ce/href">https://medium.com/media/95e2c82703963ec19380a0a1d55ee7ce/href</a></iframe><h3>Error stack using named function</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftbking%2Fembed%2Fpreview%2FmWJdJK%3Fheight%3D600%26amp%3Bslug-hash%3DmWJdJK%26amp%3Bdefault-tabs%3Djs%2Cresult%26amp%3Bhost%3Dhttp%253A%252F%252Fcodepen.io%26amp%3Bembed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftbking%2Fpen%2FmWJdJK&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1118411.mWJdJK.small.188d007f-4a43-4a26-9e9b-cd39200ff5ac.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e587b990c16d464394a61d04b8c68592/href">https://medium.com/media/e587b990c16d464394a61d04b8c68592/href</a></iframe><p>JavaScript ecosystem is <a href="https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f">already confusing</a> as is and the developer can use as much help as she can get to make sense of the obscure errors.</p><h3>Use methods before declaration</h3><p>While interpreting code, JavaScript looks for statements starting with <strong>function</strong> keyword (i.e. named function expressions) and move them to the top. This is called <a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">Hoisting</a>.</p><p>So practically, a named function is available even before it’s declared, making the following code valid.</p><pre>add(1, 2); // =&gt; 3</pre><pre>function add (a, b) {</pre><pre>  return a + b;</pre><pre>}</pre><p>But the following code won’t work.</p><pre>add(1, 2); // =&gt; Error</pre><pre>var add = function (a, b) {</pre><pre>  return a + b;</pre><pre>}</pre><h3>Improves readability</h3><p>It’s fairly difficult to understand a callback function’s purpose in first glance. That’s what makes <a href="http://callbackhell.com/">callback hell</a> the problem it is.Look at the following jQuery code.</p><pre>$(&#39;form&#39;).submit(function () {</pre><pre>  // ...</pre><pre>});</pre><p>The above code provides no information on what’s going to happen to the submitted form. Adding names to callbacks improves readability and acts as implicit documentation, as the following code does.</p><pre>$(&#39;form&#39;).submit(function hitAPI () {</pre><pre>  // ...</pre><pre>});</pre><h3>Conclusion</h3><p>In my opinion, there’s no reason one should not use named functions when possible. Most of the JavaScript style guides out there don’t give due importance to them. <a href="http://eslint.org/">ESLint</a> users can use <a href="http://eslint.org/docs/rules/func-names">func-names</a> rule in their projects to require the use of named functions, and enjoy the benefits.</p><p><strong>❤️ code</strong><br>️</p><p><em>Originally published at </em><a href="http://tarunbatra.com/blog/javascript/why-you-should-use-named-functions-in-javascript/index.html"><em>tarunbatra.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56320f5cfb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>