<?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 Evgeni Kisel on Medium]]></title>
        <description><![CDATA[Stories by Evgeni Kisel on Medium]]></description>
        <link>https://medium.com/@evgeni.kisel?source=rss-47afec25e351------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oVMCPZB3If3kOdX2IFVfFw.jpeg</url>
            <title>Stories by Evgeni Kisel on Medium</title>
            <link>https://medium.com/@evgeni.kisel?source=rss-47afec25e351------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 19:36:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evgeni.kisel/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[Third-Party Cookies & Authentication]]></title>
            <link>https://itnext.io/third-party-cookies-authentication-769a08709330?source=rss-47afec25e351------2</link>
            <guid isPermaLink="false">https://medium.com/p/769a08709330</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Evgeni Kisel]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 12:47:23 GMT</pubDate>
            <atom:updated>2020-03-25T16:09:58.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*gXSUHjoQNi1Yjl9edD5tyQ.png" /></figure><p>Long story short: browsers from year after year protect our privacy and security more and more. One of the side-effects is that third party cookies are starting to be blocked widely.</p><p>In a nutshell: <strong>first party cookies</strong> are cookies that are created by visited domain. <strong>Third party cookies</strong> are cookies created by a domain that is different from the visited domain. Let’s consider an example. You visit <strong>awesome.com </strong>and use an integrated plugin (it’s integrated as an iframe) from <strong>my.plugin.com</strong>. Cookies from <strong>awesome.com</strong>, <strong>static.awesome.com </strong>are treated as first-party cookies, but cookies from <strong>my.plugin.com</strong>, <strong>plugin.com</strong> are treated as third-party cookies.</p><p>Blocking details:</p><ul><li><a href="https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/">Full Third-Party Cookie Blocking and More</a></li><li>Chrome <a href="https://chromestatus.com/feature/5633521622188032">rejects insecure cookies</a> with <em>SameSite=None </em>starting from Chrome 80<em>.</em></li></ul><h3>Authentication</h3><p>How do cookies correlate with authentication? Your app can be a standalone app and it is always used as a first party but your app can be a plugin into another system as well (e.g. Trello Power-Up, JIRA plugin and etc). In this case your app is treated as third-party by browser.</p><p>There are two common approaches for authentication. Let’s review them and how they work with third-party cookies.</p><h4>Stateless Authentication</h4><p>Usually it does not have anything common with cookies. Token is added in each request for authentication reason. It can be added as a header or as a query parameter.</p><p>Works well for both first and third party cases because it does not use cookies at all.</p><h4>Stateful Authentication</h4><p>It’s implemented via session. Common approach to set session id in cookie to be able to send it automatically with every request. As an alternative option session id can be passed as a query parameter.</p><p>If query parameter is used for session id then you don’t have any issues with cookies (because you don’t use cookies). But still have issues because session id will be visible, easier for <a href="https://owasp.org/www-community/attacks/Session_fixation">session fixation attack</a>, can be logged by proxies because it is part of request url.</p><p>If cookies are used then you may have issues if your app is third party (you are integrated into another app on another domain). Because you may not be able to set your own session cookies.</p><h4>How can it be fixed?</h4><p>If it’s possible then <strong>migrate on token based authentication</strong>. Usually integration providers (e.g. Trello, JIRA and etc) give a mechanism of obtaining, storing and refreshing short-lived token. But sometimes it has issues or does not fit your system.</p><p>Another option is to fix your cookies (currently it’s possible).</p><ol><li>Use OAuth for user authentication. Consent screen should be opened in a separate window (default approach due to <a href="https://interceptd.com/what-is-click-hijacking-and-how-does-it-work/">click hijacking</a> attack). In this case OAuth will be finished in that window as well and session cookie will be set as a first-party cookie. <strong>Actually the fact that the cookie was set as a first party will allow using your session cookie as a third party (it actually works now that way in Safari).</strong></li><li>Configure your cookie properly. Your session cookie should contain <em>SameSite</em> attribute. If this attribute is set to <em>None </em>then you must set <em>Secure </em>flag. Otherwise it will be blocked.</li></ol><blockquote>A cookie associated with a cross-site resource at &lt;URL&gt; was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application&gt;Storage&gt;Cookies and see more details at &lt;URL&gt; and &lt;URL&gt;.</blockquote><h3>How can I test that cookies are supported?</h3><p>It’s a common practice to show a placeholder page that cookies support is required. But it should be shown properly. If you google a lit bit about how to test then most likely you’ll find following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a3eb34c2a0c8affd6ab798bf9f8cd47/href">https://medium.com/media/9a3eb34c2a0c8affd6ab798bf9f8cd47/href</a></iframe><p>But it actually does not work now for third party case (at least in Chrome). It works for first party case. The code snippet can be adjusted a little bit to support third party case as well (looks awkward but it works):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41d8d7a78ebbd8b591c0ca4603ea3104/href">https://medium.com/media/41d8d7a78ebbd8b591c0ca4603ea3104/href</a></iframe><p>Also if OAuth flow is used then it’s better to run this check after OAuth completed. In this case completed OAuth can unblock your third party cookies.</p><h3>Storage Access</h3><p>It’s not related to authentication but it is still relevant to blocking third party access. As soon as third party cookies are blocked then access to local and session storage can be blocked as well. In this case I highly recommend to foresee this scenario and be ready to fallback to “in memory storage”. Simple example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/444a099778996e57ca9a776d39afe6fa/href">https://medium.com/media/444a099778996e57ca9a776d39afe6fa/href</a></iframe><h3>Further Reading</h3><ul><li><a href="https://clearcode.cc/blog/difference-between-first-party-third-party-cookies/#first-party-cookies">What’s the Difference Between First-Party and Third-Party Cookies?</a></li><li><a href="https://webkit.org/blog/10218/full-third-party-cookie-blocking-and-more/">Full Third-Party Cookie Blocking and More</a></li><li><a href="https://cookie-script.com/all-you-need-to-know-about-third-party-cookies.html">All you need to know about Third-Party Cookies</a></li><li><a href="https://chromestatus.com/feature/5633521622188032">Reject insecure SameSite=None cookies</a></li><li><a href="https://www.chromium.org/updates/same-site">Chromium — SameSite Updates</a></li><li><a href="https://www.theverge.com/2020/1/14/21064698/google-third-party-cookies-chrome-two-years-privacy-safari-firefox">Google to ‘phase out’ third-party cookies in Chrome, but not for two years</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769a08709330" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/third-party-cookies-authentication-769a08709330">Third-Party Cookies &amp; Authentication</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My List of Typical Performance Killers of NodeJS Web Applications]]></title>
            <link>https://itnext.io/my-list-of-typical-performance-killers-of-nodejs-web-applications-60349b898234?source=rss-47afec25e351------2</link>
            <guid isPermaLink="false">https://medium.com/p/60349b898234</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Evgeni Kisel]]></dc:creator>
            <pubDate>Mon, 17 Feb 2020 05:18:25 GMT</pubDate>
            <atom:updated>2020-02-18T08:16:34.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xv0A0bducoXrUSjJiPrOlg.jpeg" /><figcaption><a href="https://www.pexels.com/photo/close-up-of-snail-on-ground-320956/">Image source</a></figcaption></figure><blockquote><strong>20 percent</strong> of your activities will account for <strong>80 percent</strong> of your <strong>results</strong></blockquote><p>I’ve started with <strong>Pareto Principle </strong>because I think it totally fits the idea of the article. Actually fixing typical issues is around 20 percent of effort that developers may spend on fixing performance and get quite good results at the end.</p><p>Also, I’d like to mention that the article won’t contain anything about event loop because:</p><ol><li>there are tons of articles about <a href="https://www.journaldev.com/7462/node-js-architecture-single-threaded-event-loop">single thread, event loop</a> and etc</li><li>it’s not typical to write heavy computation or CPU intensive tasks with NodeJS. But if it was decided to do that way then, I believe, it was done intentionally. So the developer knows how to handle CPU intensive tasks (<a href="https://codeburst.io/cpu-intensive-node-js-part-1-1218b102e5ec">article link</a>).</li></ol><h3>Monitoring and alerting</h3><p>Before going to performance killers, I want to briefly go through monitoring and alerting because it is a crucial part of modern systems. They allow you to get quick feedback about the technical conditions of a system without even opening an application by the most convenient for you and your team channels (e.g. mail, Slack and etc). Also, it brings the possibility to track whether your fixes improve performance or not and how good the fixes are. In addition configured <a href="https://itnext.io/distributed-tracing-in-your-kibana-with-nodejs-610c9f07b4b4">distributed tracing</a> may shed light on insufficient cross service communication and communication with persistence storages.</p><p>Let’s imagine that the system does not have any monitoring. So in this case there are following ways to find out that system has performance issues:</p><ul><li>users feedback. But let’s be honest, users seldom write feedback. It’s much easier for them to leave your system. Exceptions are paid users.</li><li>inspecting logs. It’s time consuming and boring.</li></ul><p>What should at least be monitored?</p><ul><li>CPU usage. High CPU usage leads to general slow down and can be a symptom of event loop lags. Alert when CPU usage is higher than threshold (e.g. limitCpu * 0.5 &lt;= currentCpu).</li><li>Memory usage. High memory usage can lead to killing process due to Out-Of-Memory. Alert when memory usage is higher than threshold (e.g. limitMemory * 0.5 &lt;= currentMemory)</li><li>Critical path requests are slow. Each application has its own critical path with a list of requests that heavily influence it. Request timing can be tracked using logger or using any APM tools (btw I have an article about <a href="https://itnext.io/distributed-tracing-in-your-kibana-with-nodejs-610c9f07b4b4">elastic APM</a>). Configure alerts to be triggered when request time is greater than threshold. Personally I use 75 percentile for the last 12 hours.</li></ul><h3>Performance Killers</h3><h4>1. Chained async flow</h4><p>It is when async commands are run one after another like synchronous code. This kind of flow starts being an even more common issue since introducing async-await because this construction leads to writing synchronous like code. Here is a typical example of a readable code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4518a6ca73dc1be70f4a4a9c48b03727/href">https://medium.com/media/4518a6ca73dc1be70f4a4a9c48b03727/href</a></iframe><p>The issue of a code block above is depicted in the image below. There are two asynchronous requests that are independent from each other and they are executed in chained flow and waste time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Uj8gkIbxo14q20TyTlqvJA.png" /></figure><p>This issue can be easily fixed by running independent asynchronous commands in parallel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1499c80f944fae72a4e8768860a80922/href">https://medium.com/media/1499c80f944fae72a4e8768860a80922/href</a></iframe><p>In this case <em>getReportMetadata </em>and <em>getUser </em>are run in parallel and reduce total request time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*M9sFMHGsP3ZF1AmpmuAwwA.png" /></figure><h4>2. Calling async functions in a foreach/map/reduce and etc.</h4><p>Rather often code already contains simple asynchronous functions that work well with a single entity. E.g. function that fetch data then make some transformation and save it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e44ec2221764652da2c68364a06408c/href">https://medium.com/media/5e44ec2221764652da2c68364a06408c/href</a></iframe><p>Function looks pretty good but let’s imagine that a new requirement is received to support bulk updates. The first idea is to do something like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d359f54d081541433cf3974b8aaef0e9/href">https://medium.com/media/d359f54d081541433cf3974b8aaef0e9/href</a></iframe><p>But the price can be rather high. In this particular case there are 2*n db requests are made. Just to realize there are 100 concurrent requests for 50 entities.</p><p>At least it would be much easier to rework existing code in following way, performance-wise:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c15f72cb9be0884b3f544c664d98785e/href">https://medium.com/media/c15f72cb9be0884b3f544c664d98785e/href</a></iframe><p>For example with this approach data can be fetched using in where clause and updated using bulk write (e.g<a href="https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/"> mongo bulk write</a>, <a href="https://www.postgresql.org/docs/9.1/sql-values.html">update from values in postgre</a>)</p><h4>3. Blind middleware chain usage</h4><p>There are different approaches (<a href="https://khalilstemmler.com/articles/domain-driven-design-intro/">DDD</a>, <a href="https://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/understanding-onion-architecture.html">Onion Architecture</a>, <a href="https://dzone.com/articles/layered-architecture-is-good">Layered architecture</a> and etc) that say that business logic code should be detached from framework related code. But still there are a lot of projects that still use middleware (e.g. express and koa based) for business logic, data fetching and communication with external services and so on.</p><p>Typically code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/972ed61d8fe7e2f082b069cfffc2d2a8/href">https://medium.com/media/972ed61d8fe7e2f082b069cfffc2d2a8/href</a></iframe><p>The code looks great. It is simple, composable and clean. But there are two major possible performance issues:</p><ul><li><strong>Chained asynchronous flow.</strong></li></ul><p>It happens because each middleware is isolated and does not know about each other. Here is a sample of such middleware:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4601a5b592694cfeacc3ee6cac6a4b14/href">https://medium.com/media/4601a5b592694cfeacc3ee6cac6a4b14/href</a></iframe><p>Actually such middleware chain usage produces the same effect as a chain of asynchronous command in single function.</p><p>The issue can be resolved by refactoring the code and extracting a dedicated function/service that is responsible for data fetching and calculating data. In this case it’s possible to write a code that does parallel data fetching.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/629020ff942568ab7d4772f860322808/href">https://medium.com/media/629020ff942568ab7d4772f860322808/href</a></iframe><ul><li><strong>Perform Redundant Actions</strong></li></ul><p>Because there is no explicit relations between middleware it can be a case when middleware do redundant actions. By redundant actions I mean actions that are not required to perform major scenario of request. The most typical case is when middleware does data fetching that is not required.</p><p>Let revise our example above. Application does user fetching, report metadata fetching and schema fetching before calculating data. Let’s consider that after refactoring it’s not required any more to fetch schema. But the middleware was not removed. It was not removed because there is no explicit relations between fetchSchema and calculateData middleware. As a result there is a redundant external call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc14846da0c8746c48c8b87658fdfae/href">https://medium.com/media/3fc14846da0c8746c48c8b87658fdfae/href</a></iframe><p>The issue can be resolved in the same manner as the previous one. The code should be refactored by extracting dedicated service or function. In this case relations between data fetching and data processing will be explicit and redundant actions can be easily removed.</p><h4>4. Ignore NodeJS updates</h4><p>NodeJS development team regularly releases new versions. They constantly add new features (workers, v8 new features), fix issues (performance, security, bugs). By ignoring updates you create lock for improvements that in general come with a low price.</p><p>If you do not even update NodeJS version I strongly recommend to keep tracking <a href="https://github.com/nodejs/node/blob/master/CHANGELOG.md">changelog</a>. Probably you’ll find something useful.</p><p>My suggestions:</p><ul><li>use latest NodeJS version for new services</li><li>regular update NodeJS version during active service development</li></ul><h4>5. ORM/ODM pitfalls</h4><p>ORM/ODM is a great tool that can speed up application development. It abstracts your code from database code. But the power of ORM also has its weaknesses.</p><p>I believe a typical issue with ORM is that developers work without enabled query logging. As a result it leads to losing control under database abstraction and performance degradation.</p><p>Typical issues:</p><ol><li>Inefficient queries. ORM framework can generate subselect instead of join. Or even worse it can generate N+1 requests for a rather simple scenario.</li><li>Eager relations fetching. Eager fetching means that for each select ORM will select sub resources even if your code does not need it. As a result code spends valuable time for things that it does not need.</li></ol><p>My suggestions:</p><ol><li>enable request logging by default in development mode</li><li>prefer lazy fetching over eager. Implement a dedicated function for fetching entity with sub resources and call it only when entity is required to be fetched with sub resources.</li></ol><h4>6. Forget about DB indexes</h4><p>It’s said that premature optimization is a root of all evils. But it’s actually not totally true for DB indexes. During development persistent model most common queries should be taken into account. As a result it is clear how data is going to be used and which columns should be indexed.</p><p>Here are couple of obvious scenarios when indexes can be added without waiting for performance issue:</p><ol><li>There is a multi tenant application with table based strategy. In this case each table contains a tenant identifier. So in this case the tenant identifier column should be indexed in every table.</li><li>There is an application that contains orders. Usually orders contain line items. So during database design line item will have a link on order that will be widely used in querying. So order id is a great candidate to be indexed in line items table.</li></ol><p>My suggestion is to index foreign keys from the very beginning that should be widely used in querying and most likely rarely or never be changed.</p><h3>Conclusion</h3><p>I hope I was able to bring my idea that we should think about performance as well as functionality of your application during design and implementing system and don’t afraid to apply refactoring in scope of new features in sake of performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60349b898234" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/my-list-of-typical-performance-killers-of-nodejs-web-applications-60349b898234">My List of Typical Performance Killers of NodeJS Web Applications</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Tracing in your Kibana with Node.JS]]></title>
            <link>https://itnext.io/distributed-tracing-in-your-kibana-with-nodejs-610c9f07b4b4?source=rss-47afec25e351------2</link>
            <guid isPermaLink="false">https://medium.com/p/610c9f07b4b4</guid>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Evgeni Kisel]]></dc:creator>
            <pubDate>Sat, 14 Dec 2019 14:29:22 GMT</pubDate>
            <atom:updated>2019-12-18T13:59:09.591Z</atom:updated>
            <content:encoded><![CDATA[<p>Distributed tracing is a method used to profile and monitor applications, especially those built using a microservices architecture. Distributed tracing helps pinpoint where failures occur and what causes poor performance. In addition it can be used to visualize and understand communication between microservices without additional documentation (that rather often get stale quickly).</p><p>There were two major options for a long time to choose between, they are <a href="https://zipkin.io/">Zipkin</a> and <a href="https://www.jaegertracing.io/">Jaeger</a>. But there is a relatively new beast in Elastic stack called <a href="https://www.elastic.co/products/apm">APM</a>. By using Elastic APM it’s possible to store distributed tracing information inside Elasticsearch and visualize it in Kibana. This is extremely useful if you have already been using Elasticsearch and Kibana for logs as well because it opens up out-of-the-box solution for linking together logs and your tracing information. You needn’t any more jumping between systems to correlate your logs and traces.</p><h3>High-Level Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_MDO4q-A0xz9V1e3Vjusw.png" /><figcaption>Image was taken from <a href="https://www.elastic.co/guide/en/apm/get-started/current/images/apm-architecture-cloud.png">APM docs</a></figcaption></figure><p><strong>APM Agents</strong></p><p>APM agents are actually part of your services that collect and post tracing data to APM server. Elastic team has already created a bunch of Agents to the most popular programming languages (e.g. Go, Node.JS, .NET, Java and etc). Full list of supported agents and corresponding docs can be found in the <a href="https://www.elastic.co/guide/en/apm/agent/index.html">APM documentation</a>.</p><p><strong>APM Server</strong></p><p>APM Server is responsible for processing requests from agents. It performs validation, security scans, creates valid documents and stores them into Elasticsearch indices.</p><p><strong>Elasticsearch</strong></p><p>It’s distributed search and analytics engine. In simple words you can treat it as a kind of database.</p><p><strong>Kibana</strong></p><p>Rich visualization platform that works with Elasticsearch.</p><h3>Add APM Agent to Node.JS service</h3><p>It’s incredibly easy to add an APM agent to your existing service and it requires minimum amount of changes.</p><p>First of all it should be added to an app.</p><pre>npm install elastic-apm-node --save</pre><p>Next step is to add and start the agent.</p><pre>const apm = require(&#39;elastic-apm-node&#39;).start({<br>  serviceName: &#39;my-awesome-service&#39;,<br>  serverUrl: &#39;http://localhost:8200&#39;,<br>})</pre><p>The most important thing here is that it should be the first module you require in your app (details can be found below). Node.JS APM agent instruments libraries during start up. It wraps Node.JS core services and installed external libraries to be able to automatically starts, configure and ends transactions and spans. The list of instrumented modules can be found in the <a href="https://github.com/elastic/apm-agent-nodejs/tree/v3.3.0/lib/instrumentation/modules">elastic-apm-node repository</a> and in the official <a href="https://www.elastic.co/guide/en/apm/agent/nodejs/current/supported-technologies.html">docs</a>. As a developer you can actually disable instrumentation for any specific module by passing <a href="https://github.com/elastic/apm-agent-nodejs/tree/v3.3.0/lib/instrumentation/modules"><em>disableInstrumentation </em>configuration </a>to your agent or even disable instrumentation at all via <a href="https://www.elastic.co/guide/en/apm/agent/nodejs/3.x/configuration.html#instrument"><em>instrument</em></a><em> </em>property.</p><p>APM agent is up and running. It starts and finishes transaction for incoming HTTP requests, creates spans for outbound requests, external storage calls, passing corresponding HTTP headers to the next service (context propagation) and etc without any additional explicit line of code from service developer.</p><p>I’d rather mention that <em>start </em>function may include <a href="https://www.elastic.co/guide/en/apm/agent/nodejs/2.x/configuration.htmlhttps://www.elastic.co/guide/en/apm/agent/nodejs/2.x/configuration.html">tons of settings</a>. So it’s possible to make a fine grained configuration of your agent. Folks from Elastic made a great job with configuration by providing rather flexible approach. So it’s possible to use global settings, environment variables and configuration via code. Settings are applied in the <a href="https://github.com/elastic/apm-agent-nodejs/blob/v3.3.0/lib/config.js#L212-L218">following priority</a>:</p><ul><li>options passed via environment variables —<strong>the highest priority</strong></li><li>options passed in to <em>agent.start()</em></li><li>options from global config file</li><li>default options — the lowest priority</li></ul><p>Going back to staring APM agent. There was a phrase that:</p><h3>APM Agents Usage Recommendations</h3><p>The recommendations are based on my personal experience with Node.JS Elastic APM Agent.</p><p><strong>Inspect transactions and spans details</strong></p><p>If instrumentation is turned on then be ready to look through data the agent collects. E.g. APM agent stores request headers and body for inbound HTTP requests. It also adds current user information based on information in your request object and etc. There are following issues:</p><ol><li>storing senseless information that increase memory consumption by Elasticsearch</li><li>storing sensitive information. Rather often tokens and other sensitive information is passed via headers. (Luckily, 90% of cases APM server strips such kind of information)</li><li>the agent adds user id, name and email to transaction if it’s able to find such information in request object. E.g your app uses passport and passport stores user information in <em>request.user, </em>as a result if user is not specified explicitly the APM Agent will take values from request. Storing such information can be a GDPR issue</li></ol><p><strong>Use Labels and Customs</strong></p><p>There is a possibility to add additional information to transactions and spans. They are labels and customs. The main difference between them is that labels are indexed (searchable) and customs are not.</p><p>Examples for labels:</p><ul><li>System has already had a correlation id (<a href="https://medium.com/@evgeni.kisel/add-correlation-id-in-node-js-applications-fde759eed5e3">how to add correlation id</a>) before tracing. So correlation id is a good candidate to be added as a label to all transactions.</li><li>Blue-Green, Canary releases. Information can also be stored in labels to separate between different types of services. It’s even possible to use <a href="https://github.com/nodejs/node/issues/22360">global labels settings</a> in the APM Agent to set up such kind of labels.</li></ul><p>Examples for customs:</p><ul><li>stores context related information that does not make any sense during searching but helps during analyze by providing some app specific context.</li></ul><p><strong>Handle Multi-Cluster Environment</strong></p><p>If there are multiple clusters (e.g. separate clusters for specific customer or specific location) then, for sure, information about cluster should be tracked in transactions to be able to filter by this data. There are actually two options to track that data.</p><ul><li>The first option is to set cluster name via label. With this approach there will be only one record per service on a services page in Kibana.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*ee-3NiKWtizcvq0r_-q8Gg.png" /></figure><ul><li>The second option is to set cluster name via <a href="https://www.elastic.co/guide/en/apm/agent/nodejs/current/configuration.html#environment">environment</a> agent parameter. In this case you can easily filter by environment in Kibana. There is a dedicated quick filter on all pages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffcRY0J0ooOz9GGVGOvAzw.png" /></figure><p><strong>Inspect Resources Consumption</strong></p><p>When adopting tracing make sure that it was tested without sampling transactions. Memory consumption can be increased. Personally I had several memory leaks that luckily was fixed shortly.</p><p><strong>Support Quick Switch Between Sampling Rates</strong></p><p>Actually it does not make sense to have tracing enabled on full power all the time. Usually it is enabled on full power during direct performance research. All the remaining time it should work with 10–20% power to decrease senseless load on Elasticsearch. 10–20% power gives you a possibility to create reports and have high level vision on performance and issues of your system.</p><p>Unfortunately there is no “deep sampling”/”sampling propagation”. It means that if there are two services <em>ServiceA </em>and <em>ServiceB</em> and one calls another and both have sample rate configured that sampling is applying on each service separately. Side effect of this is that it’s possible to have <em>ServiceA</em> transactions but does not have any <em>ServiceB</em> transactions and vice-versa. The best scenario, IMHO, is if root transactions is persisted then it should force all sub-transactions to be persisted and if root transaction is NOT persisted then all sub-transactions should NOT be persisted as well. I call it sampling propagation.</p><p><strong>Enrich Log Records with Tracing Information</strong></p><p>To be able to correlate log records and tracing data it’s required to enrich log records with tracing information that includes one or more of the following fields:</p><ul><li><em>transaction.id</em></li><li><em>trace.id</em></li><li><em>span.id</em></li></ul><p>The agent provides API to get these values for currentation transaction <em>apm.currentTraceIds. </em>The only thing is to inject them into particular loggers.</p><p>In addition it makes sense to add <em>trace.id </em>and <em>transaction.id </em>to response headers.</p><p><strong>Be aware of custom thenables</strong></p><p>The most part of instrumentation works via <a href="https://nodejs.org/api/async_hooks.html">async-hooks</a>. So keep in mind that instrumentation won’t work for libraries which use custom thenables (e.g. mongoose uses own promises out of the box) due to V8 issue. More details regarding this issue can be found here:</p><ul><li><a href="https://github.com/elastic/apm-agent-nodejs/issues/1550">https://github.com/elastic/apm-agent-nodejs/issues/1550</a></li><li><a href="https://github.com/nodejs/node/issues/22360">https://github.com/nodejs/node/issues/22360</a></li></ul><p>How to fix mongoose?</p><ul><li>First, need register built-in promise as a default promise for mongoose</li></ul><pre>mongoose.Promise = global.Promise;</pre><ul><li>use exec() to run database operations</li></ul><pre>async function getDataNotTrackedByAPM() {<br>    const result = await Model.find();<br>    result result;<br>}</pre><pre>async function getData() {<br>    const result = await Model.find().exec();<br>    result result;<br>}</pre><p>How to make sure that custom thenable is not in use in your code? I have a rather dirty approach but it helps to migrate quite big codebase (but it requires good test coverage).</p><pre>if (<em>process</em>.env.NODE_ENV !== `production`) {<br>    mongoose.Query.prototype.then = function() {<br>        throw new <em>Error</em>(<br>            `use exec() because requests cannot be tracked by APM Agent`,<br>        );<br>    };<br>}</pre><h3>Configure Local Development Environment</h3><p>Configure local development environment is easy-peasy with docker. It requires only two files and docker:</p><ul><li>apm-server.yml</li></ul><pre>apm-server:<br>  host:<br>    &quot;0.0.0.0:8200&quot;<br><br>output.elasticsearch:<br>  hosts:<br>    [&quot;elasticsearch:9200&quot;]</pre><ul><li>docker-compose.yml</li></ul><pre>version: &quot;3&quot;<br>services:<br>  elasticsearch:<br>    image: docker.elastic.co/elasticsearch/elasticsearch:7.4.0<br>    ports:<br>      - 9200:9200<br>      - 9300:9300<br>    environment:<br>      - discovery.type=single-node<br><br>  apm-server:<br>    image: docker.elastic.co/apm/apm-server:7.4.0<br>    depends_on:<br>      - elasticsearch<br>    environment:<br>      - output.elasticsearch.hosts=[&quot;elasticsearch:9200&quot;]<br>    volumes:<br>      - &quot;./apm-server.yml:/usr/share/apm-server/apm-server.yml:ro&quot;<br>    ports:<br>      - 8200:8200<br><br>  kibana:<br>    image: docker.elastic.co/kibana/kibana:7.4.0<br>    depends_on:<br>      - elasticsearch<br>    ports:<br>      - 5601:5601<br>    environment:<br>      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200</pre><p>To be able to use distributed tracing docker-compose should be run. Then open Kibana by <a href="http://localhost:5601/">http://localhost:5601</a> url, find APM tab and follow the setup instructions.</p><p>There are some simple examples below how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSz1fwjhplId-pL_8C0lwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiBOemM2tuoEIiZ_yNy5hw.png" /></figure><h3>Conclusion</h3><p>Elastic APM solution is quite suitable and can be easily adopted due to already implemented APM Agents with all sort of “magic” inside that minimize required service developer sefforts. Also this solution removes unnecessary steps to add additional resources for visualization if Kibana is already in place.</p><p>Useful links:</p><ul><li><a href="https://www.elastic.co/products/apm">https://www.elastic.co/products/apm</a></li><li><a href="https://www.elastic.co/guide/en/apm/get-started/current/index.html">https://www.elastic.co/guide/en/apm/get-started/current/index.html</a></li><li><a href="https://www.elastic.co/guide/en/apm/agent/nodejs/index.html">https://www.elastic.co/guide/en/apm/agent/nodejs/index.html</a></li><li><a href="https://www.npmjs.com/package/elastic-apm-node">https://www.npmjs.com/package/elastic-apm-node</a></li><li><a href="https://nodejs.org/api/async_hooks.html">https://nodejs.org/api/async_hooks.html</a></li><li><a href="https://medium.com/autodesk-tlv/async-hooks-a-whole-new-world-of-opportunities-a1a6daf1990a">https://medium.com/autodesk-tlv/async-hooks-a-whole-new-world-of-opportunities-a1a6daf1990a</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=610c9f07b4b4" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/distributed-tracing-in-your-kibana-with-nodejs-610c9f07b4b4">Distributed Tracing in your Kibana with Node.JS</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Correlation ID in Node.JS Applications]]></title>
            <link>https://medium.com/@evgeni.kisel/add-correlation-id-in-node-js-applications-fde759eed5e3?source=rss-47afec25e351------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde759eed5e3</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Evgeni Kisel]]></dc:creator>
            <pubDate>Mon, 03 Jun 2019 10:22:21 GMT</pubDate>
            <atom:updated>2019-06-09T05:44:13.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Add Correlation ID in NodeJS Koa and Express Applications</h3><p>Correlation ID is a pattern with a goal of linking log records, requests, responses and events together through out different services during operation processing and also between different execution contexts.</p><p>Why do we actually need it? The answer is obvious — to simplify troubleshooting and monitoring our applications. Let’s take a look at example. There is an application that contains bunch of services (Gateway, Articles, Price calculations, Tax and Discounts).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*JxafrjCUlZvOg715Hmyfeg.png" /></figure><p>Let’s imagine that user wants to get a price of some article. User sends a request to the system and the request should go through all of these services to make a valid calculations but something goes wrong and user receives an error. The person who is responsible for troubleshooting can easily find that error log record even without any correlation IDs. But to have a clear picture why it happens that way it is often important to understand a whole flow of request starting from gateway and now correlation ID starts to shine because it works like a glue between log records.</p><h4>Implement Own Application</h4><p>In this article I am going to implement two services those works together (link on github repository with code available at the end of the article). One service is <a href="https://www.npmjs.com/package/express">express</a> based and the second one is <a href="https://www.npmjs.com/package/koa">koa</a> based. Each of them use following libraries:</p><ul><li><a href="https://www.npmjs.com/package/winston">winston</a> — logging library</li><li><a href="https://www.npmjs.com/package/cls-hooked">cls-hooked</a> — async hooks wrapper</li><li><a href="https://www.npmjs.com/package/morgan">morgan</a> — http request logger middleware</li></ul><p>Express based service will provide an article with a base price but final price will be calculated by the second service.</p><h4>Correlation ID Storage</h4><p>Before creating our services I am going to create common things. The first common thing is correlation ID storage. Actually correlation ID storage is not a problem for server with request per thread model because such model supports ThreadLocal variable out-of-the-box that usually is used for storing such data. But NodeJS has another model with single working thread and event loop.</p><p>There are two approaches for storing correlation ID in Node.JS:</p><ol><li>Create an instance of logger for each request with specified correlation ID and pass this logger for each function during execution flow. Personally I don’t like such approach for logging because it’s required a lot of explicit actions from developer, also if it’s required to inject in existing code then amount of changes will be enormous.</li><li>Use async hooks. It’s kind of ThreadLocal variable for NodeJS. The disadvantage of this approach is that async hooks is not stable functionality and your correlation ID can be lost (personally we have a rare cases of losing correlation IDs in our product). Here is a nice article that describes how async hooks work <a href="https://medium.com/the-node-js-collection/async-hooks-in-node-js-illustrated-b7ce1344111f">https://medium.com/the-node-js-collection/async-hooks-in-node-js-illustrated-b7ce1344111f</a></li></ol><p>In this article async hooks based approach is going to be implemented.</p><p>So let’s create an abstraction for correlation ID</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17cd2ffbf75f64fc05b2b5fef5c92096/href">https://medium.com/media/17cd2ffbf75f64fc05b2b5fef5c92096/href</a></iframe><p>The abstraction exposes following function those will be required later:</p><ul><li>withId — executes specified function with correlation ID. If ID is missing then new ID is generated</li><li>getId — provides current correlation ID.</li><li>bindEmitter — binds an EventEmitterto the correlation ID namespace. <a href="https://www.npmjs.com/package/cls-hooked#namespacebindemitteremitter">More details</a>. By the way the most popular reason of loosing correlation ID is that event emitters are not bound context.</li><li>bind — binds a function to the correlation ID namespace. <a href="https://www.npmjs.com/package/cls-hooked#namespacebindcallback-context">More details</a>.</li></ul><h4>Logger</h4><p>Logging is implemented via winston library. The only thing that should be done here is to add appropriate formatters to add and print correlation ID.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fb7af1232e424bef49e6343121437c7/href">https://medium.com/media/7fb7af1232e424bef49e6343121437c7/href</a></iframe><p>I want to highlight importance of usage noCorrelationIdValue variable because as I mentioned earlier async hooks unstable yet so your correlation ID can be lost. This value will help you to find log records without correlation ID and fix it later on if needed.</p><p>The real case scenario. We had a correlation ID lost for requests those were aborted by Node.JS server due to timeout. The records were found during log inspection with filtering by nocorrelation correlation ID value.</p><h4>Koa Application — Price Calculation Service</h4><p>Let’s implement our first app that is responsible for price calculation. It takes base price and country and increase price by applying tax rates (there is no goal to build an e-commerce app so examples just to show how correlation id works).</p><p>To make correlation ID works approriate middleware should be added. The middleware responsibilities are:</p><ul><li>It should bind request, response and socket event emitters to correlation ID context so any triggered events will be assosiated within current correlation ID context.</li><li>It should executes request flow within correlation ID value.</li><li>In addition to that that it’s required to rebind __onFinished function. Koa uses __onFinished <a href="https://github.com/koajs/koa/blob/23f7f545abfe1fb6499cd61cc8ff41fd86cef4a0/lib/application.js#L150">under the hood</a> when it starts processing request and morgan links to it later on. If we skip rebinding then response log record will be without correlation ID.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a33799399db2bea1b830fea76c08a6c5/href">https://medium.com/media/a33799399db2bea1b830fea76c08a6c5/href</a></iframe><p>Now we are ready to implement our service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28f0c74c1fd3ee3fce857155561b5a4e/href">https://medium.com/media/28f0c74c1fd3ee3fce857155561b5a4e/href</a></iframe><h4>Express Application — Articles Service</h4><p>It’s time to create articles service. The service takes a request and randomly selects country to build a price for. There are two things that should be done from correlation ID standpoint:</p><ol><li>introduce express middleware to run request processing within correlation ID context</li><li>provide a scalable way for calling another services with current correlation ID</li></ol><p>Express middleware looks similar to Koa one but without rebinding __onFinished because it’s not used by express internals.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e7d1f7b99509e0e384068e56267025/href">https://medium.com/media/61e7d1f7b99509e0e384068e56267025/href</a></iframe><p>It’s time to create a code to pass correlation ID during call to another services. There are two approaches:</p><ol><li>Naive one. In this case we can add additional header during each API invocation</li><li>Decorate existing object that is responsible for sending requests. Most of libraries have such possiblities. Currently I’m going to use request-promise library and it supports <a href="https://www.npmjs.com/package/request#requestdefaultsoptions">defaults</a> function which creates new instance of request-promise using my default values. Also keep in mind when defining default header for correlation ID is that it’s required to use getter function instead of just string for a value . Because it’s required to send actual value during each call. If pure string is used then all requests will have the same correlation ID.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a45f728e1973f63a2568f5c5dd3c5b30/href">https://medium.com/media/a45f728e1973f63a2568f5c5dd3c5b30/href</a></iframe><p>Now we are ready to implement our service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/780ddc7ff7b624c0d9859a709ad6d306/href">https://medium.com/media/780ddc7ff7b624c0d9859a709ad6d306/href</a></iframe><h4>Result</h4><p>Here you can find a log example of single request processing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FHfXtjO2tAnBG_KikUD1A.png" /></figure><p>Also I have run thousands of requests with different delays. Result of such execution is log where it’s possible to figure out sequence of request processing. Moreover if you use such tool like Kibana it gives you increadible power by tool filtering possibilities. You can find a log sample below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbxgHsjhYMDWrjIHOg1paQ.png" /></figure><p>Source code is available on GitHub <a href="https://github.com/evgeni-k/correlation-id-sample">https://github.com/evgeni-k/correlation-id-sample</a>.</p><p>We are developing data visualization platform. You may try our platform at <a href="https://vizydrop.com/">https://vizydrop.com</a> or <a href="https://trello.vizydrop.com/">https://trello.vizydrop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde759eed5e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troubleshoot NodeJS: application silently rejects requests without any logs]]></title>
            <link>https://medium.com/@evgeni.kisel/troubleshoot-nodejs-application-silently-rejects-requests-without-any-logs-c09c9111656a?source=rss-47afec25e351------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09c9111656a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Evgeni Kisel]]></dc:creator>
            <pubDate>Fri, 10 May 2019 06:45:28 GMT</pubDate>
            <atom:updated>2019-05-10T06:45:28.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIKWl6O-Af7LPjBm1YVB_w.png" /></figure><p>The issue is rather hard to debug and one of the possible cause is that http header size limit limit exceeded. Node.js has significantly <a href="https://www.nearform.com/blog/protecting-node-js-from-uncontrolled-resource-consumption-headers-attacks/">reduced max http header size</a> since versions v6.15.0, v8.14.0, v10.14.0, v11.3.0 (from 80KB to 8KB).</p><p>The possible use cases when issue may appear with your application are following:</p><ul><li>application has a lot of integrations those add additional headers (e.g. google analytics and etc)</li><li>use of JWT token that may takes KBs</li><li>heavy usage of custom headers</li><li>heavy usage of cookies</li></ul><p>Actually we did faced with that limitation as a part of our integration flow. The toughest thing is that max header size error appeared from time to time with no any logs. No logs means that there were no even log record about incoming request.</p><p>The first clue that we had is that request was actually send to an appropriate service and the service terminated connection (thanks to nginx logs). After that we started makes different experiments with requests and figured out that an issue with amount of headers and run app with <a href="https://nodejs.org/dist/latest-v10.x/docs/api/cli.html#cli_max_http_header_size_size"><em>max-http-header-size</em></a> option.</p><pre># Setting up max header size via node js parameters<br>node --max-http-header-size=16384 server.js</pre><pre># Setting up max header size via pm2<br>pm2 start server.js --node-args=&quot;--max-http-header-size=16384&quot;</pre><p>As of that moment we fixed that issue but it was required to find out a way to log such sort of errors to avoid similar issues in future. The error can be caught and logged via listening to <a href="https://nodejs.org/docs/latest-v10.x/api/http.html#http_event_clienterror"><em>clientError </em></a>event on http server instance.</p><pre>const server = createApp()<br>    .listen(config.port, () =&gt; {<br>        log.info(`application is started on port ${config.port}`);<br>    })<br>    .on(&#39;clientError&#39;, (err, socket) =&gt; {<br>         log.error(err);<br>         socket.end(&#39;HTTP/1.1 400 Bad Request\r\n\r\n&#39;);    <br>    });</pre><p>I’ve created a sample app which you can use to reproduce the issue. Please find it by the link below <a href="https://github.com/evgeni-k/max-http-header-size-issue">https://github.com/evgeni-k/max-http-header-size-issue</a></p><p>We are developing data visualization platform. You may try our platform at <a href="https://vizydrop.com/">https://vizydrop.com</a> or <a href="https://trello.vizydrop.com/">https://trello.vizydrop.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09c9111656a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>