<?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 Alexandr Kazachenko on Medium]]></title>
        <description><![CDATA[Stories by Alexandr Kazachenko on Medium]]></description>
        <link>https://medium.com/@shoom3301?source=rss-e7d2191ab755------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mA8TBLjTJqbcbsyZ</url>
            <title>Stories by Alexandr Kazachenko on Medium</title>
            <link>https://medium.com/@shoom3301?source=rss-e7d2191ab755------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:01:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shoom3301/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 can we define web application performance?]]></title>
            <link>https://medium.com/its-tinkoff/how-can-we-define-web-application-performance-30fd1377e31c?source=rss-e7d2191ab755------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fd1377e31c</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[lighthouse]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-chrome]]></category>
            <dc:creator><![CDATA[Alexandr Kazachenko]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 10:10:34 GMT</pubDate>
            <atom:updated>2020-08-05T10:11:43.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*80fVjyhN2-Qp9jtz.png" /></figure><p>Some applications are loaded quickly, some are slow, but why? Is page load speed the only indicator of application performance?</p><p>Answering these and many other questions in one article would be very difficult. So, I have collected a directory of links and categorized them. But for a start — a bit of theory about what performance is and when to think about it.</p><h3>When performance problems begin</h3><p>You can develop web applications for years and hardly face any application performance problems.</p><p>But most likely, problems occur in the following situations:</p><ol><li>Big data appears (you need to render large lists or hundreds of thousands of points on the map).</li><li>The application becomes big (hundreds of custom scripts, dozens of screens, forms, etc.).</li><li>A large number of clients from different regions (for example, 300,000+ clients per day from all over the world).</li><li>High competition in the market (for sure, a user will prefer your competitor’s application if it works faster).</li><li>You need a mobile version (browsers on mobile devices still suffer from performance problems).</li></ol><h3>What does the performance consist of</h3><p>Globally, performance problems with web applications can be divided into two categories: data transfer and runtime.</p><ul><li>By data transfer we mean downloading any resources required for the application to run.</li><li>Under runtime — application operation, rendering and processing of user input.</li></ul><p>Each of these categories contains a lot of nuances, which we often do not think about, but which distinguish high-quality applications from low-quality ones.</p><p>These are the most popular performance metrics for web applications (all should be minimal):</p><h3>Page Loading</h3><ul><li>TTFB — Time To First Byte.</li><li>FCP — First Contentful Paint.</li><li>FMP — Time To First Meaningful Paint.</li><li>TTI — Time To Interactive (time until the page can react to user input).</li></ul><h3>Runtime</h3><ul><li>Response time to user input.</li><li>Time of interface redrawing.</li></ul><p>Although TTFB and TTI are both page load performance metrics, they can be affected by runtime related issues.</p><h3>How to search and analyze performance issues</h3><p>The main set of tools in the developer’s arsenal is <a href="https://developers.google.com/web/tools/chrome-devtools">Chrome DevTools</a> or similar tools such as <a href="https://getfirebug.com/">Firebug/Firefox developer tools</a>.</p><p><a href="https://developers.google.com/web/tools/chrome-devtools/network/reference">Network</a> — allows you to analyze in detail what resources are loaded on the page, from what resources, at what speed and so on. This tool is often used for manual analysis of the page load speed.</p><p><a href="https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/reference">Performance</a> — in this tab you can enable recording of code execution calls, I/O operations and others. In addition, the record can be made with network and CPU throttling emulation. For example, you can check the application’s performance on weak devices.</p><p><a href="https://developers.google.com/web/fundamentals/performance/get-started/measuringperf-2">Lighthouse</a> — a tool built into Chrome DevTools that launches page loading, records metrics, analyzes them and even gives recommendations on performance improvement.</p><h3>How to measure and monitor performance</h3><p>Web application performance monitoring tools can be divided into two categories: those that perform synthetic measurements and those that record performance data from real users.</p><ul><li>Synthetic monitoring tools include <a href="https://developers.google.com/web/fundamentals/performance/get-started/measuringperf-2">Lighthouse</a> and <a href="https://www.webpagetest.org/">Webpagetest</a>.</li><li>For real user monitoring (RUM — real user monitoring) <a href="https://developer.akamai.com/akamai-mpulse-real-user-monitoring-solution">mPulse</a> and <a href="https://sematext.com/">Sematext</a> will be suitable.</li></ul><p>Besides there are tools like <a href="https://github.com/webpack-contrib/webpack-bundle-analyzer">Webpack-bundle-analyzer</a> which cannot be attributed to these two categories. But with their help it is possible to measure some parameters which influence productivity, for example the size of a bandle.</p><h3>Data transfering</h3><p><a href="https://medium.com/better-programming/understanding-browser-networking-and-how-to-optimize-the-requests-for-http-1-1-and-http-2-f6371f0af650">TCP connection, DNS lookup</a> — you can speed up page loading even by properly configuring server connections. In particular, if you use DNS pre-fetching or even IP addresses instead of domain names.</p><p><a href="https://web.dev/time-to-first-byte/">TTFB (Time to First Byte)</a>. Time to First Byte is an important metric. To accelerate it, you should try to implement as little logic as possible on the server before issuing index.html.</p><p><a href="https://medium.com/@factoryhr/http-2-the-difference-between-http-1-1-benefits-and-how-to-use-it-38094fa0e95b">HTTP1 vs HTTP2</a> — HTTP2 can greatly speed up page loading by multiplexing or compressing headers. Besides, the new (relatively) protocol opens up a lot of possibilities, for example, server push.</p><p><a href="https://developer.mozilla.org/ru/docs/Web/HTTP/Connection_management_in_HTTP_1.x#%D0%94%D0%BE%D0%BC%D0%B5%D0%BD%D0%BD%D0%BE%D0%B5_%D1%80%D0%B0%D0%B7%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_(Domain_sharding)">Domain sharding</a>. If you need to pass a lot of HTTP headers for API requests, but not for static requests, it is better to divide them by different domains.</p><p><a href="https://imagekit.io/blog/content-delivery-network-improve-website-performance/">CDN (Content Delivery Network)</a> will help speed up loading for geographically distributed clients.</p><p><a href="https://developers.google.com/web/fundamentals/performance/resource-prioritization">Resource prioritization (preload, prefetch, preconnect)</a> is a page loading speed-up due to the correct resource loading strategy. Browsers allow you to set priorities for different types of resources and to load earlier what is important for the first rendering.</p><p><a href="https://medium.com/@suneetbansal/brotli-vs-gzip-compression-surprising-compression-result-8de14e0574a">Static compression: GZIP and Brotli</a>. Brotli is a compression algorithm that will reduce the weight of static and thus increase loading speed. And here’s a <a href="https://habr.com/ru/company/tinkoff/blog/474632/">great solution</a> from my colleague.</p><p><a href="https://web.dev/serve-images-webp/">Webp vs Png &amp; Jpg</a>. Webp is a great alternative to Png. In addition to the lower weight of images, Webp is not inferior in quality. Now this format <a href="https://caniuse.com/#search=webp">supports about 78% of browsers</a>. But even if you need 100% support, you can implement flyback on Png using the tag picture.</p><h3>Runtime</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide">Tasks, Microtasks</a>. With proper prioritization of code deploying, you can get rid of “friezes” and speed up response to user input.</p><p><a href="https://developers.google.com/web/updates/2015/08/using-requestidlecallback">requestIdleCallback</a> is a useful feature that allows code to be deployed in your spare time at the end of a frame (frame/tick) or when the user is inactive. It will help to get rid of all the same lags and “friezes”.</p><p><a href="https://developer.mozilla.org/ru/docs/DOM/window.requestAnimationFrame">requestAnimationFrame</a> allows you to schedule your animation correctly and maximize your chances of rendering 60 frames per second.</p><p><a href="https://v8.dev/blog/high-performance-es2015">ES2015 vs ES5</a>. The ES2015 provides many features that are more powerful than ES5.</p><p><a href="https://dev.to/grandemayta/javascript-dom-manipulation-to-improve-performance-459a">DOM manipulation</a>. DOM manipulations are expensive and need to be done carefully and sensibly. For example, do not call querySelector() in a loop if you can do it with one call.</p><p><a href="https://web.dev/render-blocking-resources/">Render blocking resource</a>. Loading some resources may block rendering. To avoid this, you should use attributes defer, async, preload.</p><p><a href="https://habr.com/ru/post/204238/">60 FPS by pointer-events</a>: none is a great hack that can be used to achieve 60 FPS when scrolling a page. It works very simply: all mouse event handlers are disabled while scrolling.</p><p><a href="https://developers.google.com/web/tools/lighthouse/audits/passive-event-listeners?hl=ru">Passive event listener</a> is a way to make smooth page scrolling on touch screens. In short, the browser has an imperfect flow of event handlers for touch events. If you set the passive parameter when creating the event handler, the browser will clearly understand that the handler will not cancel scrolling and render without waiting for its completion.</p><p><a href="https://dev.to/adamklein/build-your-own-virtual-scroll-part-i-11ib">Virtual scroll</a> is a smart way not to render large lists, but to generate them while scrolling. It consumes less memory and makes scrolling lists easier.</p><p><a href="https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing">Avoid large Complex Layouts and Layout Thrashing</a>. Layout/reflow are expensive operations that perform many recalculations of rendering parameters. To avoid calling them frequently, you need to build the layout and manipulate DOM correctly.</p><p><a href="https://gist.github.com/paulirish/5d52fb081b3570c81e3a">What forces layout/reflow</a> is a cheat sheet where you can find a list of functions and parameters that layout/reflow calls on.</p><h3>Building</h3><p><a href="https://medium.com/@netxm/what-is-tree-shaking-de7c6be5cadd">Tree shaking</a> — remove unused code from the bandit and speed up page loading.</p><p><a href="https://developers.google.com/web/fundamentals/performance/optimizing-javascript/code-splitting">Code splitting</a> — by splitting the code into chunks, you can optimize the first download and open the possibility to download parts of the code “lazy”.</p><p><a href="https://obfuscator.io/">Obfuscation</a> can reduce the size of the bandit and even a little help to hide your code from other people’s eyes.</p><h3>Architecture</h3><p><a href="https://medium.com/@baphemot/whats-server-side-rendering-and-do-i-need-it-cb42dc059b38">Server side rendering</a> is probably the best known way to make sure that the SPA is rendered immediately on first boot. This is an important requirement for some search engines (and not only).</p><p><a href="https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video">Lazy loading images and video</a> (<a href="https://css-tricks.com/native-lazy-loading/">+native</a>) — a native solution designed to improve the metrics of the first rendering by “lazy” loading images and video.</p><p><a href="https://web.dev/route-level-code-splitting-in-angular/">Lazy loading modules/routes</a> — a tool that is available in all popular frameworks and libraries. It allows “lazy” loading of pieces of application functionality.</p><p><a href="https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker">Caching files with Service workers</a> allows you to cache the files in your browser and not to download them every time from the server. Perhaps the only way to make offline mode in a browser application.</p><p><a href="https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching">HTTP Caching</a> — with the help of some HTTP headers you can greatly improve the speed of page loading and reduce the load on the server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fd1377e31c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/its-tinkoff/how-can-we-define-web-application-performance-30fd1377e31c">How can we define web application performance?</a> was originally published in <a href="https://medium.com/its-tinkoff">IT-компании Тинькофф</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Camunda external tasks — a powerful tool for creating applications with a fault-tolerant and…]]></title>
            <link>https://medium.com/its-tinkoff/camunda-external-tasks-a-powerful-tool-for-creating-applications-with-a-fault-tolerant-and-329b5ac3e1a6?source=rss-e7d2191ab755------2</link>
            <guid isPermaLink="false">https://medium.com/p/329b5ac3e1a6</guid>
            <dc:creator><![CDATA[Alexandr Kazachenko]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:16:49 GMT</pubDate>
            <atom:updated>2020-08-05T08:31:40.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>Camunda external tasks — a powerful tool for creating applications with a fault-tolerant and scalable architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AWEkWcTHvDTKpbeZKA6ZQ.png" /></figure><p>In Tinkoff we use the <strong>Camunda + Spring framework</strong> for the development of business process automation systems. We visualize them in the form of flowcharts by <strong>BPMN </strong>(Business Process Management Notation).</p><p>The most frequently used element on our schemes is <strong>service tasks</strong> (rectangle with a gear). Camunda supports two ways to perform service tasks:</p><ol><li>With the help of a synchronous Java code.</li><li>With the creation of external task.</li></ol><p>The second way allows you to perform tasks with the help of external systems. For example, if you need to call one <strong>camunda application</strong> from another or even delegate work to some external system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boT728hK9lvaiL7GB2qTeQ.png" /><figcaption>Example of BPMN scheme</figcaption></figure><p>This is useful when you are going to reuse logic in multiple applications. Or when you want to stick to the microservice architecture. For example, by separating services that do business processes from services that perform technical tasks such as report generation or mailing out.</p><p>Along with this capability, external task provides a scalable, fault-tolerant architecture. To understand what this is all about, you first need to understand how the external task works at the BPMN and application levels.</p><h3>External task in BPMN</h3><p>External task involves creating a task that can be performed by an external handler. The essence of the external task pattern is that:</p><ol><li>The process that “orders” the task execution simply adds its “order” to the database.</li><li>Some abstract handler asks Camunda for the task to be processed, at the same time assigning the task to himself so that another handler could not execute it.</li><li>After execution of the task the handler tells camunda the result of execution (successful or unsuccessful).</li></ol><p>In the diagram above, I described a fictitious process where we want to get a list of users, send them ads and count the number of requests after 2 hours of marketing. And if there are more than 10 requests, increase the sample for the next mailing list.</p><p>I want my application on camunda to be responsible only for business processes, and any other application will be responsible for email distribution. In that case, the external task pattern fits me perfectly. In my process, I’ll just create an email task and wait for some external handler to perform it.</p><p>In order to create an external task in the schema, it is necessary:</p><ol><li>Create a regular task.</li><li>Change its type to a service task.</li><li>Set implementation to external.</li><li>Specify the value of the Topic field.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/0*9-STbdHl7Pvv_YTI" /></figure><p><strong>Topic</strong> is the name of the queue, in which tasks of the same type will be added and to which the external handler will subscribe.</p><p>Now that there is an external task in the process, you can run it, but it will not run because no one is processing it.</p><h3>External tasks worker</h3><p>The external task pattern is good because it allows you to implement the processing of tasks in any language, with any tools that can perform <strong>HTTP requests</strong>.</p><p>Below is an example from <a href="https://blog.camunda.com/post/2015/11/external-tasks/">the camunda blog</a>. The example implements an external <strong>Javascript</strong> handler that asks camunda every 20 seconds for a list of tasks to be processed. If there are tasks, it mails them and notifies camunda when the task is finished.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/341a5fd4f94cbecdaa5929f36a8fd4db/href">https://medium.com/media/341a5fd4f94cbecdaa5929f36a8fd4db/href</a></iframe><p>As you see from the code above, <strong>fetchAndLock</strong> and <strong>complete</strong> are the key methods for handling external tasks. The first method requests a list of tasks and commits their execution to itself, while the second method informs you when the task is finished. There are other methods besides these two, <a href="https://docs.camunda.org/manual/7.7/reference/rest/external-task/">you can read about them in the documentation</a>.</p><h3>Camunda external task client</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*mrq_tuViBi4iaNsv" /></figure><p>To implement external tasks processing, camunda provided clients in <a href="https://github.com/camunda/camunda-external-task-client-js">Javascript</a> and <a href="https://github.com/camunda/camunda-external-task-client-java">Java</a>, which allow you to create external task handlers literally in a few lines. There is also a <a href="https://docs.camunda.org/manual/7.9/user-guide/ext-client/">detailed guide</a> that describes the basic principles of external task processing, again with examples in <a href="https://github.com/camunda/camunda-external-task-client-js/tree/master/examples">Javascript</a> and <a href="https://github.com/camunda/camunda-external-task-client-java/tree/master/examples">Java</a>.</p><p>An example of an external handler implementation using the <strong>ExternalTaskClient</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c6e90b8e4c2cd14a6569fe7839e323c/href">https://medium.com/media/4c6e90b8e4c2cd14a6569fe7839e323c/href</a></iframe><p>If your task requires you to run an entire process rather than just perform some synchronous action, you may do it, for example, by running the process through <strong>RuntimeService</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/139f474d1b943ab2b13be8c254cc48aa/href">https://medium.com/media/139f474d1b943ab2b13be8c254cc48aa/href</a></iframe><p>In this example, the external tasks handler (<strong>EmailWorker</strong>) runs the <strong>SendEmailProcess</strong> process when a task is received.</p><p>Let’s assume that this process performs some actions necessary to send a mailing list and finally calls <strong>EmailResultDelegate</strong>, which in turn completes the <strong>external task</strong>.</p><h3>Architectural advantages of an external task</h3><p>It should be noted that there is a way to start the process in another camunda application in a simpler way: <em>POST: /rest/process-definition/key/${id}/start</em>.</p><p>When you use <strong>REST</strong>, you have no transactional guarantees. But with an external task we also work with <strong>REST</strong>, what is the difference then?</p><p>The difference is that we don’t call the external service directly, we just publish tasks that can be processed. Let’s look at an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/0*_J2pSfqhV800acS0" /></figure><p>Some external handler picks up a task that is now assigned to him, but when a response is received, the connection is dropped. The camunda side now has a blocked task that will not be processed because the external handler has not received a response. But that’s okay: in camunda, for external tasks, there is a timeout at which the task will return to the queue again and someone else will be able to process it.</p><p>Now let’s look at the case when the external handler received the task, executed it, and called the <strong>complete method</strong>, which ended up with an error due to network problems. You will now be unable to figure out whether or not the task was successfully completed in camunda. You can try again, but there is a chance that network problems will continue.</p><p>In that case, the best solution is to ignore the problem. If the task was successful after all, then everything is fine. If not, then at the end of the timeout the task will be available for processing again. But this means that your external handler must be independent or contain logic for deduplication of the task.</p><p>A similar problem may occur when starting a new process, so you should check your existing instances with the same data, such as <strong>businessKey</strong>.</p><p>Besides high fault tolerance, external tasks allow you to easily scale external handlers and implement them in any programming language. In this case, the pattern helps to implement microservices so that they affect each other as little as possible, thus increasing their stability.</p><p>You can read more about the <strong>external task</strong> here:</p><ul><li><a href="https://docs.camunda.org/manual/latest/user-guide/process-engine/external-tasks/">https://docs.camunda.org/manual/latest/user-guide/process-engine/external-tasks/</a></li><li><a href="https://docs.camunda.org/manual/latest/reference/rest/external-task/">https://docs.camunda.org/manual/latest/reference/rest/external-task/</a></li><li><a href="https://docs.camunda.org/manual/latest/user-guide/ext-client/">https://docs.camunda.org/manual/latest/user-guide/ext-client/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329b5ac3e1a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/its-tinkoff/camunda-external-tasks-a-powerful-tool-for-creating-applications-with-a-fault-tolerant-and-329b5ac3e1a6">Camunda external tasks — a powerful tool for creating applications with a fault-tolerant and…</a> was originally published in <a href="https://medium.com/its-tinkoff">IT-компании Тинькофф</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSEGWSW: Server-Sent Events Gateway by Service Workers]]></title>
            <link>https://medium.com/its-tinkoff/ssegwsw-server-sent-events-gateway-by-service-workers-6212c1c55184?source=rss-e7d2191ab755------2</link>
            <guid isPermaLink="false">https://medium.com/p/6212c1c55184</guid>
            <category><![CDATA[sse]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stream-api]]></category>
            <category><![CDATA[service-worker]]></category>
            <dc:creator><![CDATA[Alexandr Kazachenko]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 13:22:08 GMT</pubDate>
            <atom:updated>2020-03-27T13:34:08.460Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello!</p><p>My name is Alexandr and I work as an architect at Tinkoff Business.</p><p>In this article, I want to talk about how to overcome the restriction of browsers on the number of open long-lived HTTP connections within the same domain using a service worker.</p><p>If you want, feel free to skip the backstory, description of the problem, search for a solution. Just immediately proceed to the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tzqVmUI-rjmgZfM5" /></figure><h3>Backstory</h3><p>Once upon a time, there was a chat in Tinkoff Business that worked on <a href="https://developer.mozilla.org/ru/docs/Web/API/WebSocket">WebSocket</a>.</p><p>It ceased to fit into the design of the account dashboard after some time, and in general, it needed a rewrite from angular 1.6 to angular 2+. I decided that it was time to start updating it. The backend colleague found out that the chat front-end will change and he suggested at the same time redoing the API, in particular — changing the transport from WebSocket to <a href="https://javascript.info/server-sent-events">SSE (server-sent events)</a>. He suggested this because all connections were broken when updating the NGINX config. And restoring them is difficult.</p><p>We discussed the architecture of the new solution and came to the conclusion that we will receive and send data using ordinary HTTP requests. For example, to send a <em>POST: /api/send-message</em> message, to get a list of dialogs <em>GET: /api/conversations-list</em>, and so on. And asynchronous events like “a new message from the interlocutor” will be sent via SSE. So we will increase the fault tolerance of the application: if the SSE connection will fall off, the chat still works, only it doesn’t receive realtime notifications.</p><p>Besides chat, we also used a WebSocket for the “thin notifications” component. This component allows you to send various notifications to the user’s personal account. For example that the import of accounts (which mays take several minutes) has been completed successfully. We moved this component to a separate SSE connection to completely abandon WebSocket.</p><h3>Problem</h3><p>When you open one browser tab, two SSE connections are created: one for a chat and one for thin notifications. Ok, let them be created. Do we feel greedy? We are not greedy, but browsers are greedy! They have a <a href="https://docs.pushtechnology.com/cloud/latest/manual/html/designguide/solution/support/connection_limitations.html">limit on the number of concurrent persistent connections for a domain</a>. Guess how much is in Chrome? Right, six! I opened three tabs — I filled the entire connection pool and I can no longer make HTTP requests. This is true for the HTTP / 1.x protocol. In HTTP / 2 there is no such problem due to multiplexing.</p><p>There are a few ways to solve this problem at the infrastructure level:</p><ol><li><a href="https://developer.mozilla.org/ru/docs/Web/HTTP/Connection_management_in_HTTP_1.x#%D0%94%D0%BE%D0%BC%D0%B5%D0%BD%D0%BD%D0%BE%D0%B5_%D1%80%D0%B0%D0%B7%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5_(Domain_sharding)">Domain sharding</a>.</li><li><a href="https://developers.google.com/web/fundamentals/performance/http2#request_and_response_multiplexing">HTTP/2</a>.</li></ol><p>Both of these methods seemed expensive since a lot of infrastructures would have to be affected.</p><p>So first we tried to solve the problem on the browser side. The first idea was to make some kind of transport between the tabs, for example, through the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API">LocalStorage</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API">Broadcast Channel API</a>.</p><p>The meaning is this: we open SSE connections in only one tab and send the data to the rest. This solution also did not look optimal, since it would require the release of all 50 SPA, which make up the Tinkoff Business personal account. Releasing 50 applications is also expensive, so I continued to look for other ways.</p><h3>Solution</h3><p>I recently worked with service workers and thought: is it possible to apply them in this situation?</p><p>To answer this question, you first need to understand what service workers can do in general. They can proxy requests, it looks something like this:</p><pre>self.addEventListener(<strong>&#39;fetch&#39;</strong>, event =&gt; {<br>    <strong>const </strong>response = self.caches.open(<strong>&#39;example&#39;</strong>)<br>    .then(caches =&gt; caches.match(event.request))<br>    .then(response =&gt; response || fetch(event.request));<br><br>    event.respondWith(response);<br>});</pre><p>We listen to events for HTTP requests and we respond as we like. In this case, we are trying to respond from the cache, and if it does not work out, then we make a request to the server.</p><p>Ok, let’s try to intercept the SSE connection and answer it:</p><pre>self.addEventListener(<strong>&#39;fetch&#39;</strong>, event =&gt; {<br>    <strong>const </strong>{headers} = event.request;<br>    <strong>const </strong>isSSERequest = headers.get(<strong>&#39;Accept&#39;</strong>) === <strong>&#39;text/event-stream&#39;</strong>;<br><br>    <strong>if </strong>(!isSSERequest) {<br>    <strong>return</strong>;<br>    }<br><br>    event.respondWith(<strong>new </strong>Response(<strong>&#39;Hello!&#39;</strong>));<br>});</pre><p>In-network requests we see this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_GLKQLW6udpyXo9K" /></figure><p>And in the console this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2_6QCK4_9HagcJbg" /></figure><p>Already not bad. The request was intercepted, but the SSE does not want a response in the form of <em>text/plain</em> but wants <em>text/event-stream</em>. How to create a stream now? Maybe I can respond with a stream from a service worker? Well let’s see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VCo2AhQXK6p4NbbK" /></figure><p>Excellent! The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response">Response</a> class takes <a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream">ReadableStream</a> as a body. After reading the <a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream">documentation</a>, you can find out that <em>ReadableStream</em> has a <em>controller</em> that has an <em>enqueue()</em> method — with its help you can stream data. Suitable, I take it!</p><pre>self.addEventListener(<strong>&#39;fetch&#39;</strong>, event =&gt; {<br>    <strong>const </strong>{headers} = event.request;<br>    <strong>const </strong>isSSERequest = headers.get(<strong>&#39;Accept&#39;</strong>) === <strong>&#39;text/event-stream&#39;</strong>;<br><br>    <strong>if </strong>(!isSSERequest) {<br>    <strong>return</strong>;<br>    }<br><br>    <strong>const </strong>responseText = <strong>&#39;Hello!&#39;</strong>;<br>    <strong>const </strong>responseData = Uint8Array.from(responseText, x =&gt; x.charCodeAt(0));<br>    <strong>const </strong>stream = <strong>new </strong>ReadableStream({start: controller =&gt; controller.enqueue(responseData)});<br>    <strong>const </strong>response = <strong>new </strong>Response(stream);<br><br>    event.respondWith(response);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*21Mf78mjXW_dsZyz" /></figure><p>There is no error, the connection hangs in pending status and data does not arrive on the client-side. Comparing my request with a real server request, I realized that the cause is in the headers of the answer. Those headers must be specified for SSE requests:</p><pre><strong>const </strong>sseHeaders = {<br>    <strong>&#39;content-type&#39;</strong>: <strong>&#39;text/event-stream&#39;</strong>,<br>    <strong>&#39;Transfer-Encoding&#39;</strong>: <strong>&#39;chunked&#39;</strong>,<br>    <strong>&#39;Connection&#39;</strong>: <strong>&#39;keep-alive&#39;</strong>,<br>};</pre><p>When you will add these headers, the connection opens successfully, but the data is not received on the client-side. This is obvious because you can’t just send a random text — there must be some format.</p><p>You need to send data from the server with a specific data format, and it is <a href="https://javascript.info/server-sent-events">explained well</a> at javascript.info. It can be easily described with one function:</p><pre><strong>const </strong>sseChunkData = (data: string, event?: string, retry?: number, id?: number): string =&gt;<br>    Object.entries({event, id, data, retry})<br>    .filter(([, value]) =&gt; ![undefined, <strong>null</strong>].includes(value))<br>    .map(([key, value]) =&gt; `${key}: ${value}`)<br>    .join(<strong>&#39;\n&#39;</strong>) + <strong>&#39;\n\n&#39;</strong>;</pre><p>The server must send messages separated by a double line break <em>\n\n</em> to comply with the SSE format.</p><p>The message includes these fields:</p><ul><li><strong>data</strong> — message body, several data in a row are interpreted as one message, separated by line breaks \n;</li><li><strong>id</strong> — updates the lastEventId property that is sent in the Last-Event-ID header when reconnecting;</li><li><strong>retry</strong> — the recommended delay before reconnecting in milliseconds, cannot be set using JavaScript;</li><li><strong>event</strong> — the name of the user event, indicated before data.</li></ul><p>Let’s add the necessary headers, change the answer to the desired format and see what happens:</p><pre>self.addEventListener(<strong>&#39;fetch&#39;</strong>, event =&gt; {<br>    <strong>const </strong>{headers} = event.request;<br>    <strong>const </strong>isSSERequest = headers.get(<strong>&#39;Accept&#39;</strong>) === <strong>&#39;text/event-stream&#39;</strong>;<br><br>    <strong>if </strong>(!isSSERequest) {<br>    <strong>return</strong>;<br>    }<br><br>    <strong>const </strong>sseChunkData = (data, event, retry, id) =&gt;<br>    Object.entries({event, id, data, retry})<br>    .filter(([, value]) =&gt; ![undefined, <strong>null</strong>].includes(value))<br>    .map(([key, value]) =&gt; `${key}: ${value}`)<br>    .join(<strong>&#39;\n&#39;</strong>) + <strong>&#39;\n\n&#39;</strong>;<br><br>    <strong>const </strong>sseHeaders = {<br>    <strong>&#39;content-type&#39;</strong>: <strong>&#39;text/event-stream&#39;</strong>,<br>    <strong>&#39;Transfer-Encoding&#39;</strong>: <strong>&#39;chunked&#39;</strong>,<br>    <strong>&#39;Connection&#39;</strong>: <strong>&#39;keep-alive&#39;</strong>,<br>    };<br><br>    <strong>const </strong>responseText = sseChunkData(<strong>&#39;Hello!&#39;</strong>);<br>    <strong>const </strong>responseData = Uint8Array.from(responseText, x =&gt; x.charCodeAt(0));<br>    <strong>const </strong>stream = <strong>new </strong>ReadableStream({start: controller =&gt; controller.enqueue(responseData)});<br>    <strong>const </strong>response = <strong>new </strong>Response(stream, {headers: sseHeaders});<br><br>    event.respondWith(response);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M6f19Z1Xhsu945VH" /></figure><p>Oh, my Glob! Yes, I made an SSE connection without a server!</p><h3>Result</h3><p>Now we can successfully intercept the SSE request and respond to it without going beyond the browser.</p><p>Initially, the idea was to establish a connection with the server, but only one, and to send data to tabs from it. Let’s do it!</p><pre>self.addEventListener(<strong>&#39;fetch&#39;</strong>, event =&gt; {<br>    <strong>const </strong>{headers, url} = event.request;<br>    <strong>const </strong>isSSERequest = headers.get(<strong>&#39;Accept&#39;</strong>) === <strong>&#39;text/event-stream&#39;</strong>;<br><br>    <em>// We process only SSE connections<br>    </em><strong>if </strong>(!isSSERequest) {<br>    <strong>return</strong>;<br>    }<br><br>    <em>// Response Headers for SSE<br>    </em><strong>const </strong>sseHeaders = {<br>    <strong>&#39;content-type&#39;</strong>: <strong>&#39;text/event-stream&#39;</strong>,<br>    <strong>&#39;Transfer-Encoding&#39;</strong>: <strong>&#39;chunked&#39;</strong>,<br>    <strong>&#39;Connection&#39;</strong>: <strong>&#39;keep-alive&#39;</strong>,<br>    };<br>    <em>// Function formatting data for SSE<br>    </em><strong>const </strong>sseChunkData = (data, event, retry, id) =&gt;<br>    Object.entries({event, id, data, retry})<br>    .filter(([, value]) =&gt; ![undefined, <strong>null</strong>].includes(value))<br>    .map(([key, value]) =&gt; `${key}: ${value}`)<br>    .join(<strong>&#39;\n&#39;</strong>) + <strong>&#39;\n\n&#39;</strong>;<br>    <em>// Table with server connections, where key is url, value is EventSource<br>    </em><strong>const </strong>serverConnections = {};<br>    <em>// For each url, we open only one connection to the server and use it for subsequent requests<br>    </em><strong>const </strong>getServerConnection = url =&gt; {<br>    <strong>if </strong>(!serverConnections[url]) serverConnections[url] = <strong>new </strong>EventSource(url);<br><br>    <strong>return </strong>serverConnections[url];<br>    };<br>    <em>// When we receive a message from the server, we forward it to the browser<br>    </em><strong>const </strong>onServerMessage = (controller, {data, type, retry, lastEventId}) =&gt; {<br>    <strong>const </strong>responseText = sseChunkData(data, type, retry, lastEventId);<br>    <strong>const </strong>responseData = Uint8Array.from(responseText, x =&gt; x.charCodeAt(0));<br>    controller.enqueue(responseData);<br>    };<br>    <strong>const </strong>stream = <strong>new </strong>ReadableStream({<br>    start: controller =&gt; getServerConnection(url).onmessage = onServerMessage.bind(<strong>null</strong>, controller)<br>    });<br>    <strong>const </strong>response = <strong>new </strong>Response(stream, {headers: sseHeaders});<br><br>    event.respondWith(response);<br>});</pre><p><a href="https://github.com/shoom3301/ssegwsw">The same code on GitHub.</a></p><p>I got a pretty simple solution for a not-so-trivial task. But, of course, there are still many nuances. For example, you need to close the connection to the server when closing all the tabs, fully support the SSE protocol, and so on.</p><p>We have successfully solved all this. I’m sure it will not be difficult for you too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6212c1c55184" width="1" height="1" alt=""><hr><p><a href="https://medium.com/its-tinkoff/ssegwsw-server-sent-events-gateway-by-service-workers-6212c1c55184">SSEGWSW: Server-Sent Events Gateway by Service Workers</a> was originally published in <a href="https://medium.com/its-tinkoff">IT-компании Тинькофф</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>