<?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 Vadzim Tashlikovich on Medium]]></title>
        <description><![CDATA[Stories by Vadzim Tashlikovich on Medium]]></description>
        <link>https://medium.com/@vtashlikovich?source=rss-bc34d9c46bd1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*i7g6PErUuowIIaW077wTnw.jpeg</url>
            <title>Stories by Vadzim Tashlikovich on Medium</title>
            <link>https://medium.com/@vtashlikovich?source=rss-bc34d9c46bd1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:11:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vtashlikovich/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[A 2024 look back  from a tech guy]]></title>
            <link>https://medium.com/@vtashlikovich/a-2024-tech-look-back-from-a-tech-guy-0c7f19a16de5?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c7f19a16de5</guid>
            <category><![CDATA[future]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[2024]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 12:35:42 GMT</pubDate>
            <atom:updated>2024-12-30T13:43:08.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*UYsO9fzGMbZhf9_GJc_r2A.jpeg" /></figure><p>Here is my personal review of hot topics during the fading year.</p><h3>✳️ Hardware</h3><ul><li>Ongoing bloom of ARM-based processors, x2 stock prices for Arm Holdings this year.</li><li>Mind-blowing growth of Nvidia.</li><li>And mind-blowing decay of Intel 😮</li></ul><h3>✳️ Security</h3><ul><li>npm/pip dependency managers can ruin your robust security in a blink of an eye. No trust to your dependencies. This year proved this one more time. Open-source is good and evil at the same time.</li><li>Blockchain boom made hackers go crazy creative on stealing your cyberwallets. Shell companies, mimicking potential customers, fake interviews — they do everything to get your Metamask wallets and .env files.</li></ul><h3>✳️ Tech cancel culture</h3><ul><li>Agile cancellation✖️</li><li>Microservices cancellation✖️</li><li>Cloud hosting cancellation✖️</li><li>2024 — year of cancellation!</li></ul><h3>✳️ Misc</h3><ul><li>Suddenly Google controversially starts to decrease rank of web-pages that were generated by LLM. Hire back your copywriters!</li><li>Apple proved again — VR is still a dead-end in this universe.</li><li>Apple is a new Microsoft (except AI). Now for sure 😀</li></ul><h3>✳️ Books</h3><ul><li>Software Architecture: The Hard Parts (Neal Ford, Mark Richards, Pramod Sadalage) still rocks! 💪</li><li>Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (Aurélien Géron) — magnificent all-in-one book for ML/DNN.</li></ul><p>Oh, I missed AI! 😄</p><h3>✳️ AI/LLM</h3><ul><li>Claude Sonnet, Opus — such great models! Anthropic — what a great team, what a great secure, steady and safe approach in AI development. Kudos to these guys! 🙌</li><li>LLama 3.x, Qwen 2.x — this what gives us a hope as simple humans vs corporate monsters. Thank you, Mark.</li><li>KlingAI — best image to video service. Just magic.</li><li>A brutal war of copilots: Copilot/GPT 4o versus Cursor IDE/Claude. The winner takes it all. Who will be the companion of future Senior-only development? (whispers: Claude wins so far…)</li><li>Bootstrapping web applications is easy now. Coding with AI brings more joy. But not for complex, already developed projects by now.</li><li>AI-generated content. We are still not ready for such a brutal human content distillation that is ahead.</li><li>Releases of Devin, o3. Math and science human levels are basically achieved. Arc-AGI is beaten in exchange to a lot of 💵. But it’s a matter of time till it will cost a 🍪 to reason as human.</li><li>LCM — Large Concept Models is the future. This is where the world should be headed to gain AGI, the right way. Yann LeCun rulez 🎯</li></ul><p>🔮 So what’s next? My humble opinion:</p><ul><li>AGI will <strong>not</strong> be yet rolled out in 2025.</li><li>The whole year humanity will be thinking what to do with science now. Probably we will see several big inventions in medicine, chemistry and physics thanks to AI.</li><li>A battle of thousands of new startups made basically in weeks.</li><li>We will start to gain an immunity to AI-generated content.</li><li>Rise of new agentic, test-time compute models from Anthropic, Meta, Mistral, Google. New approaches to create reasoning models using weak GPU. New approaches are needed because there is no new data to train anymore. Big bet on LCM from Meta. 🤞</li><li>The rise of multi-modals (text, video and audio) will require gathering lots of data from human daily routines. It’s needed for training new kinds of models that will start to automate jobs other than software developers (not in 2025 though).</li><li>It will get even more vivid that complex human activity can be automated up to 95%, maybe only 97%.</li><li>Nvidia and other hardware companies will do everything to speedup o3. OpenAI again will get billions and will save itself from sinking for one more year.</li></ul><p>🎆 <strong>Have a great start of a new year! Let 2025 bring joy and happiness!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c7f19a16de5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-time language translation in 5 minutes. Using Python, AssemblyAI, DeepL and OpenAI]]></title>
            <link>https://medium.com/@vtashlikovich/real-time-language-translation-in-5-minutes-using-python-assemblyai-deepl-and-openai-beb845d0ddbd?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/beb845d0ddbd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[translation]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Thu, 02 May 2024 15:15:10 GMT</pubDate>
            <atom:updated>2024-05-03T17:46:37.361Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-time speech translation in 5 minutes. Using Python, AssemblyAI, DeepL and OpenAI</h3><p>Here is a quick tutorial how to create a real-time language translation code from English to basically any popular language. Lots of integrations but still a single file code. You can skip directly to the <a href="https://github.com/vtashlikovich/stream_translator">code here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-C6EwqJJBu7j3VPd0FCGQ.png" /></figure><h3>📘 How it works</h3><p>My goal was to build a real-time solution that translates from Egnlish to Polish language. Ideally a speech as the result. After some investigation I found out that there are several ML/AI services that do the job near perfect and pretty fast:</p><ul><li><a href="https://www.assemblyai.com/">AssemblyAI</a> for real-time text-to-speech conversion;</li><li><a href="https://www.deepl.com/">DeepL</a> for a quality text translation;</li><li><a href="https://openai.com/">OpenAI</a> for an expert speech-to-text.</li></ul><p>Solution in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*4n_t9DtzOjQRf8xr1seVWw.gif" /><figcaption>Translation in action</figcaption></figure><p>What‘s going on inside:</p><ol><li>The Python code grabs speech via mic and sends to AssemblyAI.</li><li>Once chunk of text is formed it’s then sent to DeepL for a translation.</li><li>Once translated text is ready, OpenAI service is asked to form an mp3 file.</li><li>And finally, mp3 file is played in speakers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*05bA2bxm2M-z8l3CPMZ-7A.jpeg" /></figure><h3>👨‍💻 The code</h3><p>It will take more time to register accounts in all 3 services and generate API keys than write code actually. Here down below I presume that you have your keys in hands already.</p><h4>Setup routine</h4><p>Download and install Python if you do not have one: <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>. Probably it’s already delivered by your OS already. Check what’s the current version in console:</p><pre>python --version</pre><p>It should be at least 3.10. The code below was written in 3.11.</p><p>Setup a dedicated virtual environment for the project, for all dependencies to be installed locally.</p><pre>python -m venv env<br>source env/bin/activate</pre><p>Now let’s install all dependencies for the project. You can find <em>requirements.txt</em> <a href="https://github.com/vtashlikovich/stream_translator/blob/dev/requirements.txt">in here</a>.</p><pre>pip i -r requirements.txt</pre><p>Write all API key values in the following format in <em>.env</em> file. It will store secret credentials independently from the code:</p><pre>OPENAI_API_KEY=your_value<br>DEEPL_API_KEY=your_value<br>ASSEMBLY_API_KEY=your_value</pre><h4><strong>Main application</strong></h4><p>It’s located in <em>main.py</em> — the default starting point for apps in Python. At first, import all necessary libs:</p><pre># OpenAI SDK<br>import openai<br># OS lib for reading secret keys fron environment<br>import os<br># lib for reading secret keys from .env and saving in environment<br>from dotenv import load_dotenv<br># AssemblyAI SDK<br>import assemblyai as aai<br># DeepL SDK<br>import deepl<br># libraries needed to play mp3 locally<br>from pydub import AudioSegment<br>from pydub.playback import play<br># inbuilt package to measure time<br>import time</pre><p>At second, initialise secret values (store as environment variables), init API keys and OpenAI client:</p><pre>load_dotenv()<br><br>translator = deepl.Translator(os.environ[&quot;DEEPL_API_KEY&quot;])<br>aai.settings.api_key = os.environ[&quot;ASSEMBLY_API_KEY&quot;]<br>openai.api_key = os.environ[&quot;OPENAI_API_KEY&quot;]<br>client = openai.OpenAI()</pre><p>Write standalone functions. For generation of a mp3 file by connecting to OpenAI. Please note, here we use voice “nova” and standard quality “tts-1”. When audio is done we can see how much seconds it took to generate:</p><pre>def gen_speech_file(speech_file_path, text):<br>    st = time.time()<br>    response = client.audio.speech.create(<br>        model=&quot;tts-1&quot;,<br>        voice=&quot;nova&quot;,<br>        input=text<br>    )<br>    response.stream_to_file(speech_file_path)<br>    print(&#39;to speech for:&#39;, (time.time() - st), &#39;sec&#39;)<br>    return speech_file_path</pre><p>Function for playing any mp3 file using speakers:</p><pre>def play_audio(speech_file_path):<br>    audio_clip = AudioSegment.from_mp3(speech_file_path)<br>    play(audio_clip)</pre><p>Now it’s time for the main logic. It’s located in a single function. It’s called in case when AssemblyAI is ready with the full phrase just pronounced or a part of it. We don’t want to react on each new word but start acting only AssemblyAI is finalised the phrase conversion:</p><pre>def on_data(transcript: aai.RealtimeTranscript):<br><br>    if not transcript.text:<br>        return<br><br>    # if the sentence is final, let&#39;s act<br>    if isinstance(transcript, aai.RealtimeFinalTranscript):<br>        # ask DeepL to bring the translation to Polish language<br>        result = translator.translate_text(transcript.text, target_lang=&quot;PL&quot;)<br>        print(transcript.text, end=&quot;\r\n&quot;)<br>        print(&quot;PL: &quot; + result.text)<br><br>        # call function to generate and audio file<br>        gen_speech_file(&quot;speech.mp3&quot;, result.text)<br>        # play it in speakers<br>        play_audio(&quot;speech.mp3&quot;)<br>    else:<br>        print(transcript.text, end=&quot;\r&quot;)py</pre><p>Since AssemblyAI SDK is an event reacting system, we need to define several utility methods:</p><pre>def on_open(session_opened: aai.RealtimeSessionOpened):<br>    print(&quot;Session ID:&quot;, session_opened.session_id)<br><br>def on_close():<br>    print(&quot;Closing Session&quot;)<br><br>def on_error(error: aai.RealtimeError):<br>    print(&quot;An error occured:&quot;, error)</pre><p><em>on_open/on_close</em> are called to wrap the translation session. <em>on_error</em> is called when smth unexpected happens.</p><p>And now, it’s time to define main AssemblyAI transcription object and run it:</p><pre># init the main object<br>transcriber = aai.RealtimeTranscriber(<br>    on_data=on_data,<br>    on_error=on_error,<br>    sample_rate=44_100,<br>    on_open=on_open,<br>    on_close=on_close<br>)<br><br># connect to AssemblyAI servers<br>transcriber.connect()<br><br># open a stream for mic<br>microphone_stream = aai.extras.MicrophoneStream()<br><br># stream the audio into the main object<br>transcriber.stream(microphone_stream)<br>transcriber.close()</pre><p>Again, the full code can be found in <a href="https://github.com/vtashlikovich/stream_translator">this repository</a>.</p><p>🏁 Now it’s time to run and enjoy your personal real-time translator!</p><pre>python3 main.py</pre><h3>🤗 Results</h3><p>Transcription from speech to text and automatic translation works very quickly. Modern neural models have great accuracy. And it operates really like a human interpreter — AssemblyAI returns text portions once it’s sure the sentence is complete and well understood. And thanks to the great speed of both services (AssemblyAI + DeepL) the translation appears in a wink of an eye.</p><p>But text-to-speech is a bit laggy. It works pretty good when a speaker makes pauses between words, sentences. But when pronunciation speed is higher than some threshold, the sound starts lagging. And I can understand that — it’s a tough task. And for the time of the article — only OpenAI is supporting this wide variety of output languages.</p><p>💰 <strong>The cost:</strong></p><ul><li><strong>$0.47</strong> for 1 hour of real-time recognition by AssemblyAI;</li><li>500k characters <strong>free</strong> p/month for DeepL and then <strong>$25</strong> for 1M characters more;</li><li><strong>$15</strong> for 1M characters when generating a voice by OpenAI.</li></ul><p>Example: the non-stop <strong>1 hour</strong> speech will cost <strong>$1.64 </strong>below first 500k. And <strong>$3.2</strong> plus <strong>$5</strong> monthly fee for text &gt; 500k.</p><p>This level of automation wasn’t possible a year or two ago. But thanks to fast AI services and the ease of use of Python you now can build your own customised online translators literally in minutes 🥳</p><p>Photo by <a href="https://unsplash.com/@jannerboy62?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Nick Fewings</a> on <a href="https://unsplash.com/photos/multi-colored-paper-on-brown-cardboard-box-BAZejJdZ57w?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beb845d0ddbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-budget Banking service using Amazon Cloud: architecture, performance & cost]]></title>
            <link>https://medium.com/@vtashlikovich/low-budget-banking-service-using-amazon-cloud-architecture-performance-cost-1bd31dba25a4?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd31dba25a4</guid>
            <category><![CDATA[low-budget]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[experiment]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 13:48:42 GMT</pubDate>
            <atom:updated>2023-03-23T07:45:26.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8MIg7txTLgsVtjRVlPqmg.jpeg" /></figure><p>The success of any banking application depends on how efficiently its backend can handle the user traffic. With the rise of cloud technology, businesses can leverage the benefits of scalability, flexibility, and cost-effectiveness. In this article, I will explore the performance of a banking application backend hosted in the AWS cloud.</p><p>My tests revealed that the system with a low-budget cloud environment setup was able to handle <strong>200 heavy create transaction requests</strong> per second (RPS), around 890 rps at peak. Operating on <strong>30M</strong> records set. Moreover, I will delve into the infrastructure cost of hosting such a system in the cloud. My findings suggest that the cost is surprisingly low, at just <strong>$673 per month </strong>(actual on 15 Mar 2023). Join as we dive deeper into the performance and cost aspects of running a banking application backend in the AWS cloud.</p><p><strong>Article bonus</strong>: benchmark of the test solution implementation using Java and Node.Js with a public codebase.</p><p>In the article below you will find answers to the following questions:</p><ul><li>What components does a good banking architecture consist of?</li><li>What operations should a transaction go through to be processed?</li><li>How much does a banking platform cost in the cloud?</li><li>Is Java still a good choice for online services with a complex processing logic?</li><li>What income can such a low-budget system generate?</li></ul><h3>Table of contents:</h3><p><a href="#3ace">What is a low-budget setup?</a><br><a href="#85d2">Measurement criteria</a><br><a href="#bb28">How to do it wrong, a straightforward/monolithic setup</a><br><a href="#db33">Banking application challenges</a><br><a href="#1aba">How to do it right</a><br><a href="#8810">Benefits of such architecture</a><br><a href="#b7c8">Tech stack for the performance tests</a><br><a href="#c581">Results for Node.js</a><br><a href="#7905">Results for Java</a><br><a href="#5589">The cost of the production system</a><br><a href="#922e">Resolution</a><br><a href="#5c99">What income could such a system generate?</a></p><h3><strong>What is a low-budget setup?</strong></h3><p>For my experiment I used only low-budget components from the AWS price list. The goal was to get the cheapest components that do the job. Example prices (on 15 Mar 2023 for US East region, Ohio):</p><ul><li>PostgreSQL as a database; setup: <strong>db.r5.large</strong> (the 2nd cheapest one with 2 CPU’s) x2 CPU and 16GB memory costs $171 per month (US East Ohio);</li><li>Rabbit MQ: mq.m3.micro, 1 node setup;</li><li>EC2 with 2 CPU and 2GB memory costs only $14 per month;</li><li>Simple ALB Load balancer for routing of user requests, standard minimal price;</li><li>Route 53 for DNS management, standard minimal price;</li><li>CloudFront for serving of static files, standard minimal price;</li><li>NAT for working with dedicated fixed IP, standard minimal price;</li><li>SES for working with notifications, standard minimal price.</li></ul><p>This is a minimum technological component setup you need for a banking system. Why do we need all these components and what they actually do? I will cover it all sections through the whole article.</p><h3><strong>Measurement criteria</strong></h3><p>To measure the performance of the system, I focused on the most critical component, which is the transaction creation process. This means that the requests per second (rps) figures that I obtained only apply to create/write operations. In reality, a banking application involves more read/GET operations, with a ratio of about 20/80%.</p><p>Although the application I tested is a real banking application that involves a range of other functions besides transaction creation and updates, the infrastructure I used has the potential to support account management, KYC, and other features.</p><p>My main focus was to determine how many transactions a banking application can create per second in a cloud setup. To achieve this, I utilized Artillery (<a href="https://www.artillery.io/">https://www.artillery.io/</a>), a tool for load testing. The test scenario was simple, calling a transaction-create endpoint. I conducted a warm-up session of 10 seconds and then a high-load session of 60 seconds, and for the final setups, I used longer sessions of 5 minutes.</p><p>It’s worth noting that the test scenario involved only 500 accounts. This approach allowed me to simulate high activity among a small group of users and a situation where there are many transactions per account in a short amount of time, such as a partner system communicating with ours via a REST API.</p><p><a href="https://medium.com/@vtashlikovich/how-fast-can-one-create-records-in-a-low-budget-amazon-cloud-postgresql-b3f7ac79eeb8">You can read here</a> about the PostgreSQL records insertion speed using the cheapest AWS DB.</p><h3><strong>How to do it wrong, a straightforward/monolithic setup</strong></h3><p>Basically one may think that a simple monolithic setup would be a good solution to serve all user requests for a banking application. By the monolithic approach here I mean a single service scaled horizontally as on the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdvKQlYl6xLSKWlhqxXqLA.jpeg" /><figcaption>Classic straightforward approach architecture approach</figcaption></figure><p>In this diagram a single-purpose API service does everything:</p><ul><li>user and operator authentication;</li><li>user onboarding, accounts &amp; payments management;</li><li>all operator operations regarding reporting and back office management;</li><li>user notifications;</li><li>integration with a partner bank.</li></ul><p>This setup can indeed have its place in the real world. But only for demonstration purposes, as a Proof Of Concept.</p><p>Though the cost of this infrastructure is very attractive, it has a lot of critical flaws: lack of security, low processing speed, conceptual mistakes while processing several transactions in parallel for 1 banking account, instability, lack of compliance.</p><h3><strong>Banking application challenges</strong></h3><p>Before “doing it right” let’s have a look at the basic requirements a banking application should fall under:</p><ul><li>high-availability (HA), always be able to tell customer what happens with his banking account and his payments, 24/7, even under high load;</li><li>be secure and compliant with several standards and banking regulatory requirements;</li><li>be able to interact with several partner banks;</li><li>be able to correctly process accounts’ balances in parallel.</li></ul><p>In terms of transaction creation, let’s have a look to a basic set of what should be done to successfully process a transaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrXpgr91MnAzkwEsx2KbRA.png" /><figcaption>What should be done to create and process a transaction</figcaption></figure><p>So to create a transaction, the following list of actions should be done:</p><ul><li>check account balance;</li><li>check user/account limits;</li><li>calculate a fee;</li><li>calculate exchange rate (optional);</li><li>check blacklists;</li><li>check beneficiaries;</li><li>check on fraud;</li><li>reserve balance;</li><li>store the transaction;</li><li>deal with a partner system.</li></ul><p>Some of these actions need to be done within 1 database session, which takes a lot of time. Some of the operations are of an asynchronous nature — we cannot block the customer for a long time, making her wait for an answer.</p><p>And evidently this cannot be done in a monolithic app:</p><ul><li>What happens to the customer if the partner system does not respond now?</li><li>What if there are several incoming/outgoing transactions for 1 banking account that require a balance correction, when the account is blocked by another operation?</li><li>How can we scale?</li></ul><h3><strong>How to do it right</strong></h3><p>The answer to solve the majority of the issues is moving to promises<strong>.</strong> So the system does not make all actions at once but performs only the critical checks fast and promises to accomplish the rest later. This way an asynchronicity comes.</p><p>At first, the application performs the most critical operations like checking the available balance, daily/monthly limits, calculating a fee, etc. And then the system leaves the user with a promise that the transaction would not be forgotten and would be processed for 100% somewhere in the future. So we need queues.</p><p>Second, the concurrency over a single banking account should be eliminated. That means for a single account we need to process transactions one by one. If we make a transaction processing service work in such a way with all accounts, we will stick to the performance of each update/create operation. If a transaction takes 50ms to accomplish, then we have a throughput of only 20 transactions per second.</p><p>To scale the system, we should route all requests to the appropriate current account-related dedicated service by hashing the requests. This approach results in a set of working services, each processing transactions for a single account one by one, which can multiply the system’s productivity. More account-related groups lead to more services and greater productivity.</p><p>Finally the design looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYv7ASDtgc9EIy1q8FSbTw.jpeg" /><figcaption>“The right” approach</figcaption></figure><p><strong>Warning</strong>: this is the least a low budget setup that can guarantee for scaling, correct transaction processing, correct communication with banking partners and HA. But it’s missing yet:</p><ul><li>separate authentication service;</li><li>separate notification service;</li><li>a fraud detection service;</li><li>onboarding service;</li><li>dead-letter queues and appropriate processors to become more fault-tolerant.</li></ul><p>The list can be continued according to the budget and the wish to reach higher marks in security/availability/resilience/observability fields.</p><h3><strong>Benefits of such architecture</strong></h3><p>Let’s overview a sample transaction lifecycle path:</p><ol><li>Browser sends transaction details to the API service;</li><li>Stateless API service performs the following operations: calculates fee, checks available balance, checks user/account limits, returns user an error if something went wrong;</li><li>If everything is fine API service creates a new transaction message in the appropriate queue after hashing;</li><li>When a Processing service gets to the message in the queue, it performs all other operations and: silently processes transaction, passes it to the partner bank OR notifies user via a notification channel if something went wrong;</li><li>When a partner bank confirms the transaction completion, it notifies our system connector;</li><li>Partner connector puts the transaction status change message to the queue for a processing service after hashing;</li><li>Processing service finalizes transaction processing.</li></ol><p>Benefits here:</p><ul><li>user does not wait, we promise to process her transaction;</li><li>system load is well-distributed;</li><li>system has enough time to process a transaction and to correctly communicate with partner systems;</li><li>we can wait for partner response for hours and days, not milliseconds or seconds;</li><li>the correct order of transactions is followed, account balance is always updated correctly;</li><li>system is open for CQRS improvements, because the API services only read and does not write; it’s only the Processing service that writes.</li></ul><h3><strong>Tech stack for the performance tests</strong></h3><p>I tried two technical approaches in my experiment to reveal how fast such a banking system can be. Backend was created using Node.js and Java. Cloud components with the same characteristics (CPU, Memory) were used, of course. AWS PostgreSQL RDS (db.r5.large, 2xCPU, 16Gb Memory) was used as a database.</p><p>If interested, you can find sources of the experiment <a href="https://github.com/vtashlikovich/hlbank">in the repository</a>.</p><p><strong>Node.js stack — straightforward/monolithic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*-rUEXfUXPVuckNZjY4EvOg.png" /></figure><p>For the first, monolithic architecture, when 1 service does all the operations at once:</p><p>Here REST-API service was run in a cluster using PM2 capabilities. So in total one Node.js service per each core for x2 CPU. Used components versions:</p><ul><li>Node.js version: 16.15;</li><li>NestJs framework, version: 8.x</li><li>Sequelize framework, version: 6.18.x</li><li>Database: PostgreSQL, version: 13.2.</li></ul><p>In the experiment the following list of actions was implemented before the transaction creation:</p><ul><li>generating transaction ID (UUID);</li><li>creating a signature (for idempotency check);</li><li>simple fee calculation based on transaction amount;</li><li>signature lookup;</li><li>checking if customer and account are enabled (not blocked);</li><li>check user monthly limit;</li><li>check beneficiary party in the blacklist;</li><li>check if balance allows to perform the operation;</li><li>initiate a DB transaction with a specific record LOCK time;</li><li>in a single DB transaction: getting account, marking select for update; inserting a new transaction record; updating account balances (available and reserved); updating user monthly limit.</li></ul><p><strong>Node.js stack — the right one</strong></p><p>The setup to test the “right” approach looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*4YARCxhhYVVWjyq1SsOxaQ.png" /></figure><p>RabbitMQ version 3.8 was used here.</p><p>In this setup REST service was doing only these operations:</p><ul><li>signature creation (for idempotency check);</li><li>calculating a fee;</li><li>signature lookup;</li><li>checking if customer and account are enabled (not blocked);</li><li>check user monthly limit;</li><li>check if balance allows to perform the operation;</li><li>generating transaction ID (UUID);</li><li>hashing for selecting a message queue;</li><li>sending a message to the appropriate queue.</li></ul><p>And the Processing service (qwriter) was doing this:</p><ul><li>generating transaction ID (UUID) (optional);</li><li>creating a signature (for idempotency check);</li><li>simple fee calculation based on transaction amount;</li><li>signature lookup;</li><li>checking if customer and account are enabled (not blocked);</li><li>check user monthly limit;</li><li>check beneficiary party in the blacklist;</li><li>check if balance allows to perform the operation;</li><li>getting account before balance correction;</li><li>inserting a new transaction record;</li><li>updating account balances (available and reserved);</li><li>updating user monthly limit.</li></ul><p>So REST service in this setup was doing much less operations.</p><p><strong>Java stack — straightforward/monolithic</strong></p><p>As for Java, these are the tech specifications:</p><ul><li>Java JDK 11, default heap size: 512 MB;</li><li>Spring Boot 2.7.* framework was used.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Mz37eFRwNyaOyBscTZ17HA.png" /></figure><p><strong>Java stack — the right one</strong></p><p>The “right” setup was checked as well. Where a Processing service (qwriter) is a single Java service and 8 Node.js services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*-lkjsUJcs_MYu0L2HWeJXw.png" /></figure><p>Alas, the setup with 8 Java dedicated threads for each queue was not checked. Instead I focused on how fast Node.js can be as a consumer service.</p><p>It’s worth mentioning that for transaction storing in PostgreSQL a table partitioning was applied for a “created” column of “timestamp” type. This allows you to decrease the load on the main table using a monthly granularity (this frequency can be changed on your needs).</p><h3><strong>Results for Node.js</strong></h3><p>Around 100 test sessions were made to make sure the results are stable and do not deviate. But at first, it was necessary to understand what is the maximum number of POST requests that could be transferred and served by the server if it does nothing. This setup was used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*k2i37eDu3PTcWVZgcccshQ.png" /></figure><p>The number is: <strong>650</strong> dummy rps for a single Node.js process.</p><p>The first result — numbers for a straightforward/monolithic setup for Node.js when working with 1/15/30 millions of transaction records in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6vusCPWRgLh3xNzckkuT8Q.png" /><figcaption>RPS for different volumes of data for a classic approach</figcaption></figure><p>Explanation and details:</p><ul><li><strong>75 rps</strong> means that it took around 13ms to execute 1 transaction for 1Mln data set;</li><li><strong>35 rps</strong> means that it took around 29ms to execute 1 transaction for 30Mln data set;</li><li>with each new 15mln records SQL select queries are getting slower, giving less time for a single service to process 1 POST request;</li><li>beyond that number (80 rps for 1Mln records, 50 for 15Mln, 40 for 30Mln) the system hit the deadlock which led to total collapse.</li></ul><p>The numbers for the “right” setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*8pxWUM4-ZnGv7fcYeeRajA.png" /><figcaption>RPS for different volumes of data for “the right” approach</figcaption></figure><p>Explanation and details:</p><ul><li>exploratory analysis has shown that using this infrastructure setup, 6 is an ideal number of Node.js processing services; higher number didn’t give any significant performance boost;</li><li>6 processing services allow to process and create transactions with a rate of <strong>168 rps</strong>, even on <strong>30Mln</strong> data sets;</li><li>since we are using an asynchronous approach, the REST API service can take much more requests than 170; I got boosts for up to <strong>400 rps</strong>.</li></ul><p>Significant difference from the monolithic approach here is that the system is now much more performant and much more stable. Even beyond 400 rps the test stand is working fine but response latencies are starting to grow up to 1 sec. Of course this cannot be counted for a good UX, but still the system is responsive.</p><p>Here is how P99 percentile latency (ms) grow within increasing load using the optimal setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*pxpTPscBzEfY5ONbv_xJug.png" /><figcaption>P99 latency per rps</figcaption></figure><p><strong>Important note</strong> here — boosts over 200 rps do not come for a good price. The greater speed of incoming requests — the longer it takes to process them all, because the processing units still can work only with 200 create-transactions per second. So if the system experiences 400 rps for 1 minute, that means that last user transactions would be processed only 1 minute later. It’s not acceptable. Users should get a response with a successful message in a maximum of 3 seconds. It brings us approximate allowed spike bursts of 400rps per 3 seconds, not more.</p><p>Example of increasing queue load for a big incoming request rate of 400 rps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gNnvlz62IaTx-ekwIgwGvw.png" /><figcaption>Message queue state over time for a burst load</figcaption></figure><p>Example of good and bad incoming request rate spikes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*gQixf3UUZKNZg89IkU_-vg.png" /><figcaption>Different spikes for good and bad UX</figcaption></figure><p>Here users in blue spike await for a transaction success status message (a promise) for max 3 seconds. Users from the green diagram can wait up to 10 seconds.</p><h3><strong>Results for Java</strong></h3><p>According to my experience, pure CPU-bound tasks are completed about x3 times faster using Java compared to Node.js. That is for the fundamental benefit: bytecode compilation.</p><p>A banking/payment application contains a mixture of operations. There is a great portion of I/O tasks. The most important issue in our case: the faster code — the less time a database connection is blocked. And this is crucial.</p><p>For a straightforward/monolithic setup Java service managed to work stable up to <strong>100 rps</strong> before the deadlock. P99 percentile latency was pretty attractive — <strong>96,6ms</strong> average.</p><p>But for the “right” setup Java was used only for REST API in my tests. On the processing side I managed to run 8 processing Node.js services which gave a stable <strong>200</strong> operations per second even on a big amount of transactions in DB. Java REST API service demonstrated an incredible boost up to <strong>890 rps</strong>! And it seems it is not the limit.</p><p>Latencies during an increasing load:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*7XVCM9QOSqwqRePviwuf8g.png" /><figcaption>P99 latency per rps for Java setup</figcaption></figure><p>As you see, latency is almost always the same. It is practically not increasing with an upcoming load. During the tests I could not get higher rps but evidentially the system can hold more.</p><p>Probably the traffic capacity for my AWS dedicated internal network was hit. Anyway, Java REST API is at least <strong>x2.2 faster</strong> compared to Node.js solution for this sample banking functionality. I assume that after some tuning Java could hit the 1000rps mark easily.</p><h3><strong>The cost of the production system</strong></h3><p>Here is the production system costs calculation. Banking regulations affect the system architecture, software complexity and the final cost of the infrastructure. The most crucial factor is high availability (HA) compliance requirements. Basically, it means that the system should be replicated and survive in case of point failures or burst load. Compute nodes for services are the ones that were used for tests. They have enough resources to hold much more complicated logic compared to the one it was used for performance measurements.</p><p>Components and their cost in AWS cloud:</p><ul><li>routing, Route53, 1 zone, 50Mln queries per month, $20</li><li>AWS shield standard, $0</li><li>Cloudfront, 50Mln requests, $50</li><li>S3 standard, 100Gb, $3</li><li>Load balancer, $46</li><li>Secrets manager, $5</li><li>NAT, $33</li><li>SES, $60</li><li>x4 EC2, t4g.small (2 vCPU, 2GB memory, 20Gb disk) for authentication, REST API, processing and backoffice services — 4 x $14 = $56</li><li>RabbitMQ 1 node (mq.m3.micro), $30</li><li>x2 PostgreSQL; db.r5.large, 2 CPU, 16GB memory, 20GB of general purpose SSD (gp2), 2 x $171 = $342</li><li>x1 Monitoring instance for Prometheus and Grafana, $14</li><li>x1 EC2 for each external connector/integration = $14</li></ul><p>The total monthly infrastructure cost: <strong>$673</strong>.</p><p>Cost of a Database component is the most expensive one. Since the system needs to have 2 instances (1 active, 1 passive failover replica) we need x2 to the price of a single database instance: $171. Could the cheaper DB be used? Yes, <strong>db.m6g.large</strong> (2vCPU, 8GiB memory, $120) could be used. But with lesser memory a big set of transactions will cause rps to drop down to 100, if not lower. A database will not be able to flush data fast from memory to SSD disks. So cheaper DB is possible when there are less transactions. But we want to earn more on more transactions, right? 😀</p><p>A note about Kubernetes. Setup where nodes are managed by Kubernetes is a very good option. It can give more speed in terms of infrastructure operations, monitoring. It can decrease costs on maintenance. What would be the cost of the production system based on Kubernetes? It’s right here:</p><ul><li>Routing, Route53, 1 zone, 50Mln queries per month, $20</li><li>AWS shield standard, $0</li><li>Cloudfront, 50Mln requests, $50</li><li>S3 standard, 100Gb, $3</li><li>Secrets manager, $5</li><li>NAT, $33</li><li>SES, $60</li><li>RabbitMQ 1 node (mq.m3.micro), $30</li><li>x2 PostgreSQL; db.r5.large, 2 CPU, 16GB memory 2 x $171 = $342</li><li>x1 Monitoring instance for Prometheus and Grafana, $14</li><li>Kubernetes EKS cluster cost: $74</li><li>x2 EC2, a1.xlarge (4 vCPU, 8GB memory, 50Gb disk) as multi-purpose Kubernetes nodes — 2 x $79 = $158</li></ul><p>The total monthly K8s-based infrastructure cost: <strong>$789</strong>.</p><h3><strong>Resolution</strong></h3><p>In this article you discovered a banking application stand that is very close to the real one:</p><ul><li>a more or less exact list of operations performed for each transaction creation;</li><li>infrastructure capable to interact with a any number of integrations;</li><li>system capable of processing pretty good amount of daily active users;</li><li>system is tuned to be HA and compatible with PCI-DSS and banking regulations.</li></ul><p>Such a system is capable of creating 200 new transactions per second. It can hold load spikes up to 890 create requests per second.</p><p>When keeping read/write requests ratio of 80%/20% in mind, we can expect this performance:</p><ul><li>~650 rps of mixed read/write operations in normal mode;</li><li>~2800 rps in high peaks.</li></ul><p>Such a performant system, compliant and HA ready, costs $673 per month in AWS.</p><p>And Java still proves that it’s a highly performant language for a backend.</p><h3><strong>What income could such a system generate?</strong></h3><p>Some fantasies on what income can such a system generate.</p><p>Let’s assume that mainly users are active through the daytime, 16 hours out of 24. The average rate of new transactions per second is 16. This rate will generate 30Mln new records per month. The average transaction fee is $0,50.</p><p>So it’s $15Mln 💵. Hm, not bad for a $673 cost system!</p><p>If you have any questions, comments, improvements — do not hesitate to contact.</p><p>Link to the <a href="https://github.com/vtashlikovich/hlbank">experiment codebase</a>.</p><p>Icons by:<a href="https://olkeen.com/portfolio/vector-illustrations/"> https://olkeen.com/portfolio/vector-illustrations/</a>.</p><p>Photo by<a href="https://unsplash.com/@frrn?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Ferran Fusalba Roselló</a> on<a href="https://unsplash.com/s/photos/bank?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"> Unsplash</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd31dba25a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple rule to start getting in time]]></title>
            <link>https://medium.com/@vtashlikovich/a-simple-rule-to-start-getting-in-time-8f4cd0407686?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f4cd0407686</guid>
            <category><![CDATA[rules]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Sat, 25 Jun 2022 09:39:32 GMT</pubDate>
            <atom:updated>2022-06-25T09:39:32.660Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8XtimoOsLKsAf67jjr47w.png" /></figure><p>If you have a small personal project, or don’t see a good reason to introduce Agile methodology into a particular corporate project, you can use this simple rule to measure the progress. It’s called “50% rule”:</p><blockquote>Once you’ve reached 50% of the project’s timeline, check whether 50% of work has been done at this point.</blockquote><p>It works perfectly with the <strong>deadlines</strong>, when you know what date you should have the result to. If there is no deadline but a <strong>fixed budget</strong> instead, you can evaluate efforts needed for the completion of the project, at least roughly.</p><p>This brings another constraint: you need to be able to somehow <strong>measure</strong> the work. If you cannot measure, the chance of getting in time lands to zero.</p><p>Here is an example. Let’s say, your budget is around 1 month of a full time worker,i.e. 21–22 working days. And you need to paint 300 square meters of wall. Once you reach day 10, you need to check whether 150 square meters were already painted or not. If not, you need to speed up your work.</p><p>50% of the time mark is always not “too late”. So evaluate, measure, succeed.</p><p>It’s the simplest rule to control progress. If you would like to be more precise, meet Agile methodologies in all their glory!</p><p>Photo by <a href="https://unsplash.com/@jon_chng?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jonathan Chng</a> on <a href="https://unsplash.com/s/photos/runner?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f4cd0407686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How fast can one create records in a low-budget Amazon Cloud PostgreSQL?]]></title>
            <link>https://medium.com/@vtashlikovich/how-fast-can-one-create-records-in-a-low-budget-amazon-cloud-postgresql-b3f7ac79eeb8?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3f7ac79eeb8</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Fri, 17 Jun 2022 08:06:26 GMT</pubDate>
            <atom:updated>2022-09-16T12:08:14.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1GGEMWLPVxCpQj7dXns42w.png" /></figure><p>In short, it’s really fast. <strong>AWS PostgreSQL</strong> for $110 per month can create around <strong>370</strong> records per second in a heavy-indexed table suitable for storing banking transactions. In a simple, almost no-indexed table, the speed is <strong>490</strong> rps.</p><p>In this article I will share the details of my experiment. I will show you what test stand I used and the exact table configuration I created for the tests. Also, you will know how quickly DB queries were executed on 15M+ data sets. Hope, you are already excited!</p><h3>What is low-budget?</h3><p>Amazon cloud proposals start from <strong>x2 vCPU</strong> and <strong>8GB</strong> memory installations, and that’s the minimum you can get. I focused on the initial setup, the one marked as <strong>db.t3.large</strong>. It’s <strong>$110</strong> (Sep 22) per month for 30GB disk storage and 80% CPU usage (US region).</p><h3>The test stand</h3><p>Below is the test stand I used in my experiment. The Loader app is the one that connects to a PostgreSQL instance over the local network and executes “insert” statements directly. I used a simple EC2 instance: <strong>t4g.micro</strong> — that’s x2 CPU and 1GB memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*5DczdAv9tX2u-03uVWo77g.jpeg" /><figcaption>Test stand component diagram</figcaption></figure><p>For the software service implementation, I used <a href="https://nodejs.org/">Node.js</a> (v16.15) + <a href="https://sequelize.org/">Sequalize</a>.</p><p>Dummy data was generated using <a href="https://www.npmjs.com/package/@withshepherd/faker">withshepherd/faker</a> library. The loader can generate up to 3.8k rps locally, without connection to a database. The average ping between the application and the database is <em>~0.151ms</em>.</p><p>I tested Two PostgreSQL services provided by AWS:</p><ul><li>RDS for PostgreSQL</li><li>Aurora PostgreSQL</li></ul><p>In my tests I used the default DB configuration. I’m sure the total resulting numbers I got during my experiments could be even higher after some tuning.</p><h3>Tables</h3><p>When filling test tables with data, I used the Fintech industry as the subject area. So my experiment project operates records in two key tables named <strong>Account</strong> and <strong>Transaction</strong>. You can find the structure of tables (create scripts) in <a href="https://github.com/vtashlikovich/db_benchmark">the repository of this project</a>.</p><p>It’s important to mention the overall size of each table record and indexes involved, which are:</p><ul><li><strong>Account</strong> record <em>~ 964 bytes</em>. 1 index, size: <em>19 bytes</em>.</li><li><strong>Transaction</strong> record <em>~ 1097 bytes</em>. 4 indexes: <em>33 bytes</em>, <em>8 bytes</em>, <em>29 bytes</em>, <em>45 bytes</em> (the bold one).</li></ul><p><strong>Account</strong> table will be used as an example that uses a minimum of indexes. <strong>Transaction</strong> table is a complex and heavy one and will get all the heat.</p><h3>1M transactions</h3><p>So how fast records would be inserted when the big table contains 1M records?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*KUXN-zjRgigOC5vwp5ys4w.png" /><figcaption>Records insertion speed per 1 second</figcaption></figure><p>🚀 It runs fast! The storage is almost empty, 1M records is nothing for a database now.</p><p>And here goes a surprise. RDS installation dominates. Why? I tried different configurations and found out that the difference is in … disks. Aurora services just do not let you choose the type of the disk. No any SSD/HDD switch. So you can only guess what’s used there.</p><p>But for RDS it’s all clear — you can select the type of the disk: from General purpose SSD to Provisioned IOPS SSD (io1). And for 1M records the insertion rate varies from <strong>383</strong> to <strong>396</strong> for <strong>Transactions</strong> table (a complex one).</p><p>In my tests Provisioned IOPS SSD is only <strong>3% faster</strong> but a lot more expensive, at least <strong>$100 more</strong>. So just a simple General purpose SSD in RDS is already a brilliant choice.</p><p>Now, let me show you how select queries were working with 1M records. When checking the performance using the standard <em>psql</em> tool, it stated:</p><ul><li>Accounts’ select for 30 records: <em>~5ms</em></li><li>Transactions’ count(*): <em>~140ms</em></li><li>Transactions’ select for 30 records with filters: <em>~1,5ms</em></li><li>Transactions’ grouping by account: <em>~1,6ms</em></li></ul><p>The difference here between RDS and Aurora was not so noticable.</p><h3>15M transactions</h3><p>The charts below show what happened when the number of records was increased to 15M.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*whxC697OkezsP88VC--yPw.png" /><figcaption>Records creation speed per second</figcaption></figure><p>The speed of record insertion into the simple <strong>Account</strong> table stayed the same. But for <strong>Transaction</strong> table it got a bit lower, down to 370 rps. Aurora tried to go upper but no chances, it’s already lost the battle 🏁.</p><p>With 15M records, queries started working significantly slower, around <em>x11</em> times. Grouping operations were a bit better, but it seems the database’s caching worked well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*72hGZfZhuV7kmWcMUnTgVQ.png" /><figcaption>Queries execution speed (ms)</figcaption></figure><p>As you can see, in these tests Aurora worked almost the same as RDS. However, I stopped checking Aurora on higher data sets and further statistics are for RDS only.</p><h3>30M transactions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*2nAtAWyufh9mBv5Iihx7dQ.png" /><figcaption>Insert rate per second vs data amounts</figcaption></figure><p>With 30M of records in a table, insert rate decreased to <strong>348</strong> rps. That’s <strong>12% lower</strong> than for 1M records. But anyway it’s quite impressive.</p><p>Interesting fact: when being on around <strong>22M records</strong>, the insertion rate dropped to <strong>99</strong> rps suddenly. When resumed after a 15 minute pause, it returned back to normal. I’ve done a separate experiment without the boldest index (45 bytes), and the insertion speed was constant all the time. So the database couldn’t quickly handle such a big index very fast and some restructuring efforts were needed.</p><p>What about queries? Doubled data required 50% more time for select queries execution. It’s not bad. Alas, grouping queries execution time increased x5 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PtKFRyrPehW2GhV9RdWt3A.png" /></figure><h3>Does table size affect creation speed?</h3><p>Yes, but not so significantly on the 30M records scale. It’s only 12% decrease but still fast: 348 rps.</p><p>The same experiment was performed for a bigger setup: x4 CPU, 16GB memory. The insertion speed didn’t change. What really affected — the application of a SSD disk. So when selecting your next database setup, you should mind the storage access speed.</p><h3>Summary</h3><p>My experiments have shown that even the minimal Amazon Cloud’s PostgreSQL setup can bring you a great insertion speed. However, usage of the SSD disk is strongly recommended.</p><p>Trying both RDS and Aurora services, I found out that only RDS service allows you to select a disk for your needs. For this reason, Aurora is not recommended for software systems on high load.</p><p>Size of tables’ indexes really matter when designing your database structure. Heavier, bolder indexes will require more resources of PostgreSQL leading to an insertion speed decrease.</p><p>If you are aware of the data amounts bigger than 30M records, start using <a href="https://www.postgresql.org/docs/current/ddl-partitioning.html">PostgreSQL’s partitions</a>. It will help you to segregate load over some criteria. But that’s up to the business model of your application.</p><p><strong>P.S.</strong> If you are interested, the tests took around 48 hours to execute. It’s hard to believe but it was boring (filling up tables with millions of records) and exciting at the same time :)</p><p><a href="https://icons8.com/icon/12995/speed">Speed</a> icon by <a href="https://icons8.com/">Icons8</a>. <a href="https://github.com/vtashlikovich/db_benchmark">Repository</a> of the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3f7ac79eeb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Сhecklist for your next IT integration]]></title>
            <link>https://medium.com/@vtashlikovich/%D1%81hecklist-for-your-next-it-integration-ec2159d4c978?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec2159d4c978</guid>
            <category><![CDATA[checklist]]></category>
            <category><![CDATA[slo]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[sla]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Wed, 18 May 2022 19:10:33 GMT</pubDate>
            <atom:updated>2022-05-18T19:10:33.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wnEu3IR1YSLwBJbaFT8Sg.jpeg" /></figure><p>Whether you are an Enterprise, a Bank, a Fintech start-up, you are <strong>expecting</strong> to make your next API integration with a 3rd-party provider <strong>Fast</strong>, <strong>Stable</strong>, <strong>Predictable</strong>, <strong>Secure</strong>, <strong>Inexpensive</strong>. Just follow the checklist below, ask your partner company to answer all the questions, state it in the contract and be sure — you got everything under control.</p><h3>1. Communication</h3><ul><li>Who is the contact person from the 3rd party side? Who is responsible for the integration or just the one you can get information from.</li><li>What is the suitable communication channel? It can be Email, Slack, Whatsapp, Help desk system, Phone, etc.</li><li>🎁 Bonus: Set up how often you would communicate with the contact. Note: it’s important not to overflood the counter-party with tons of messages during the progress. Your communication then can be broken very soon.</li></ul><h3>2. Connectivity</h3><ul><li>What a connection type with the provider would be? Synchronous or asynchronous? Will the response come immediately or will it be available over some time?</li><li>What is the technical type of the connection? REST, SOAP, Pub/Sub, any other?</li><li>What is the IP/hostname of the prover’s main server?</li><li>How would the security of the connection be provided? TLS/SSL, closed channel, etc.?</li><li>How will your system be notified about the change of the remote objects’ statuses/states? Is it webhooks or a polling technique?</li><li>If the provider initiates connection from their side, what IP address would it be coming from? So you can whitelist it from your side.</li><li>🎁 Bonus: Will your external IP be whitelisted on the provider’s platform? Or is it a public server? Make sure your partner company stands devoted to security as well.</li></ul><blockquote><strong>Service level agreement (SLA)</strong> is an agreement in the contract in terms of technical guarantees the 3rd party is ready to provide. <strong>Service level objective (SLO)</strong> is each technical metric provider has a guarantee for.</blockquote><blockquote>If you are a math fan: SLA = SLO 1 + … + SLO N.</blockquote><h3>3. Common SLA</h3><p>Common SLO’s will be listed here. You will find other SLO’s down below in the text.</p><ul><li>What’s the general availability of the partner system? 99,9/99,99/99,999? How many “nines”?</li><li>API rate limit — what maximum number of requests per second is guaranteed to be held by the partner server?</li><li>What is the maximum latency (ms) for each request guaranteed?</li><li>🎁 Bonus: What is average latency? What latencies are for percentiles: P95, P99?</li><li>For webhooks. What is the normal delivery rate per second of the requests coming from the partner server? What is the peak number?</li><li>For webhooks. What policy does the partner have for cases when your listening server is not responding? What will provider do, how it guarantees the delivering of events? In what time period?</li></ul><h3>4. Data</h3><ul><li>Is there any size limitation for each request message?</li><li>What portions of your data the partner company will be storing? How is this data protected?</li><li>🔔 SLO. For how long the partner is intending to store data from you? For how long logs will be stored?</li><li>🔔 SLO. How many business objects can your partner company hold? For example, how many banking accounts can be created? How many transactions can be created per day/month?</li><li>Does the partner perform idempotent checks of the incoming requests?</li><li>🎁 Bonus: When creating new business objects, does partner ask for your related internal ID’s? Are there any format restrictions?</li><li>Should request messages be encrypted? If yes, which algorithm would it be?</li><li>🎁 Bonus: If encryption is used, will partner provide any SDK/library/example of messages encryption/decryption?</li><li>🎁 Bonus: If encryption is used, how signing key would be transferred? How a signature would be delivered along with the request message?</li></ul><h3>5. Authentication</h3><ul><li>What is the type of authentication? API key, user/password pair, any other?</li><li>For how long are the credentials valid?</li><li>What is the procedure of changing credentials? Is downtime needed for that?</li></ul><h3>6. Documentation</h3><ul><li>Is API documentation available? What is a portal address/credentials?</li><li>🎁 Bonus: When was the documentation changed the last time?</li><li>🎁 Bonus: Does partner have a blog containing description of updates, new upcoming features, releases?</li></ul><h3>7. Support</h3><ul><li>🔔 SLO. For how long will the current API be supported? The guaranteed amount of time.</li><li>What is the lifecycle of the API version usually?</li><li>What is the procedure of switching to the new version?</li><li>What type of support is available?</li><li>🔔 SLO. For how long the support is available?</li><li>🔔 SLO. How many hours of support per month are guaranteed?</li><li>🔔 SLO. What is the response time of the support team?</li><li>🎁 Bonus 🔔 SLO. What is the average solution delivery time of the support team?</li><li>What are the maintenance windows? You have to deal your best windows for yourself.</li><li>🔔 SLO. How often and for how long the planned maintenance is done?</li><li>🔔 SLO. How would you be notified about the planned/urgent maintenance? What are the communication channels? Who will be notified?</li></ul><h3>8. Testing</h3><ul><li>Is there any sandbox environment?</li><li>🔔 SLO. What functionality scope the sandbox environment will guarantee?</li><li>For sandbox: if interaction from the partnering side is necessary? Is it automated or manual?</li><li>🔔 SLO. When working with the sandbox and the interaction from the partner is needed — what is the contact and what is guaranteed time of the response?</li></ul><h3>9. Launch</h3><ul><li>Is there any acceptance phase before the launch?</li><li>What does the acceptance phase consist of? What is a testing plan, test cases?</li><li>🔔 SLO. What is the general timeline for an acceptance?</li><li>What is the procedure of starting the production usage?</li><li>What is production IP address/hostname, credentials?</li><li>🔔 SLO. When you request the production environment, what time is guaranteed for it to be ready?</li></ul><h3>10. Deal the price</h3><ul><li>What support plans are available?</li><li>What is the cost of upgrading the support plan?</li><li>What is the cost of additional support beyond the contracted support plan?</li><li>What is the cost of any additional features?</li><li>What are any additional costs that can popup during the testing and the production system exploitation?</li></ul><p>🏁 That’s it. Now you are strongly equipped with every important integration detail. Feel free to raise your <strong>concern level</strong> if the partner company cannot answer any of the questions above.</p><p>It’s time to<strong><em> Start!</em></strong> Have a nice integration 🖥</p><p>P.S. Did I miss something? Please let me know in comments section.</p><p><em>Photo by Volodymyr </em><a href="https://unsplash.com/@lunarts"><em>Hryshchenko</em></a><em> on </em><a href="https://unsplash.com/"><em>Unsplash</em></a><em>. Modified by the article author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec2159d4c978" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NHL API: what data is exposed and how to analyse it with Python]]></title>
            <link>https://medium.com/@vtashlikovich/nhl-api-what-data-is-exposed-and-how-to-analyse-it-with-python-745fcd6838c2?source=rss-bc34d9c46bd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/745fcd6838c2</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[nhl]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Vadzim Tashlikovich]]></dc:creator>
            <pubDate>Fri, 07 Jan 2022 16:04:14 GMT</pubDate>
            <atom:updated>2024-11-13T10:28:24.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ar1WTat9zlLKDG-HjP978g.jpeg" /><figcaption>Photo combination based on material by Klim Musalimov on Unsplash.com</figcaption></figure><p><strong>💡</strong> <strong>New NHL API version came out in 2023. </strong>This article describes exactly the <strong>LATEST</strong> API version.</p><p>NHL is a commercial organisation and it’s pretty centric by nature. As online consumers we get a $30/month streaming package, that’s probably a minus. But as a plus — we have a <strong>free</strong> API!</p><p>NHL released the latest version around 1 year ago (~2023). And it’s not just awesome, it’s <strong>epic</strong> 🔥. You can search for games long back in the history. Personally, I checked that game schedule for <strong>1918.01.02</strong> is still served. 106 years back! 👵</p><p>Let’s dive into what data league is sharing with us and how it can be used.</p><h3>Service endpoints</h3><p>General URL of API: <a href="https://api-web.nhle.com/v1/">https://api-web.nhle.com/v1/</a>.</p><p>There are lots of endpoints available to get information about: divisions, conferences, seasons, tournaments, standings, prospects, awards, etc. The whole list can be found here: <a href="https://github.com/Zmalski/NHL-API-Reference">https://github.com/Zmalski/NHL-API-Reference</a>.</p><p>I will focus on the three main ones:</p><ul><li><strong>player/ID/landing, player/ID/game-log/SEASON/2</strong>, — general information about each person/player. Or extended statistics by season;</li><li><strong>schedule</strong> — a list of games scheduled for the given period;</li><li><strong>gamecenter/ID/play-by-play</strong> — complete game log by ID.</li></ul><h3>Player statistics</h3><p>Using <em>/player/ID/landing</em> gives some general information about the player (name, age, physical parameters), the more interesting is to check gameplays stats. This can be done by creating the following GET request with parameters (Ovechkin as example):</p><p><a href="https://api-web.nhle.com/v1/player/8471214/game-log/20242025/2">https://api-web.nhle.com/v1/player/8471214/game-log/20242025/2</a></p><p><strong>Note</strong>: you can find player ID by checking game statistics (roster)described further below.</p><p>It will bring game by game stats for the specified season: <strong>2024/2025</strong>.</p><p>🍓 <strong>Action.</strong> Let’s write code that fetches data for a single player.</p><p>At first, “requests” library should be installed to be able to import it inside the program. It helps to connect to NHL remote server. Up to this moment you should know what “<a href="https://www.google.com/search?q=pip+python"><strong>pip</strong></a>” is.</p><pre>pip install requests</pre><p>How we can use it and fetch player stats in JSON format:</p><pre># Note: Python 3.9+ code compatibility<br># import HTTP fetching library<br>import requests<br><br># declare API URL as constant<br>API_URL = &quot;https://api-web.nhle.com/v1/&quot;<br><br># fetch player stats for Ovechkin, ask server to serve in<br># JSON format<br>response = requests.get(API_URL + &quot;player/8471214/game-log/20242025/2&quot;, params={&quot;Content-Type&quot;: &quot;application/json&quot;})<br>data = response.json()</pre><p>Let’s analyse data we got and find some metrics. I recommend to use a command utility “<a href="https://www.google.com/search?q=curl+utility"><strong>curl</strong></a><strong>”</strong> for checking responses from servers. It brings a good structured piece of data:</p><pre>curl https://api-web.nhle.com/v1/player/8471214/game-log/20242025/2 &gt; ovechkin.json</pre><p>Or you can grab JSON right in the console and format it using your IDE.</p><blockquote>For example: use “Format document” in VSCode or plug-in “Pretty JSON” in Sublime text.</blockquote><p>To output data to terminal simply hit in the code:</p><pre>print(data)</pre><p>Server brings the following player stats:</p><ul><li><strong>careerTotals</strong> — stats group by categories: regularSeason and playoffs.</li><li><strong>last5Games</strong> — last games;</li><li><strong>seasonTotals</strong> — stats by all seasons;</li><li><strong>awards</strong> — all trophies earned.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*ouUTzrp16SrjwZFmmZ4nkQ.png" /></figure><p><strong>🍓 Action. </strong>Let’s loop through and find which games Ovechkin had with points &gt; 1 and output ratio of goals and shots for each one.</p><pre>...<br># loop and filter games by points<br>games =[x for x in data[&quot;gameLog&quot;] if x[&quot;points&quot;] &gt; 1]<br>for game in games or []:<br>    # initial ratio value<br>    ratio = &#39;N/A&#39;<br><br>    # let&#39;s find the ratio and format it.<br>    # there is a condition because we do not want to catch<br>    # Zero devision problem :)<br>    if game[&quot;goals&quot;] &gt; 0:<br>        ratio = &quot;{0:.2f}&quot;.format(game[&#39;shots&#39;] / game[&#39;goals&#39;])<br><br>    # let&#39;s print it into the 1 line<br>    print(f&quot;Game: {game[&#39;gameId&#39;]}, points={game[&#39;points&#39;]}, goals={game[&#39;goals&#39;]}, shots={game[&#39;shots&#39;]}, ratio={ratio}&quot;)</pre><p>Here what we can get like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNyCmzeiucy3yZ3Fho-7-w.png" /></figure><p>The less ratio is better. Some games show ratio=1, that means that Ovi required only 1 shot to score 😄</p><p><strong>🍓 Action. </strong>Let’s analyse how many games player participated in, how many goals he scored, points earned and what are ratios in total.</p><p>Python is great because the result can be reached in many ways. I will do it like this:</p><pre>...<br># take all season games where Ovi participated.<br>all_games = data[&quot;gameLog&quot;] or []<br><br># we will use comprehensions to filter games with points and goals<br>points_list = [x[&quot;points&quot;] for x in all_games if x[&quot;points&quot;] &gt; 0]<br>goals_list = [x[&quot;goals&quot;] for x in all_games if x[&quot;goals&quot;] &gt; 0]<br><br># games count, it&#39;s a length of games list obviously<br>total_games = len(all_games)<br><br># sum points<br>total_points = sum(points_list)<br><br># sum goals<br>total_goals = sum(goals_list    )<br><br># print out information and calculate ratios<br>print(&quot;Total games:&quot;, total_games)<br>print(&quot;Total goals:&quot;, total_goals)<br>print(&quot;Points ratio:&quot;, &quot;{0:.2f}&quot;.format(total_points/total_games))<br>print(&quot;Goals ratio:&quot;, &quot;{0:.2f}&quot;.format(total_goals/total_games))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*_D8O6kyzdjHpjuqdPPKW7A.png" /></figure><p>So it’s <strong>1.29</strong> points and <strong>0.71</strong> goals per 1 game. Impressive…</p><p>🤔 Ovi is almost like Python.</p><h3>Games schedule</h3><p>Now let’s play with games schedule and see what interesting we can filter out of it. Main endpoint: <strong>/schedule/</strong></p><p>There should be a date parameter. When set up — the schedule for the appropriate whole week is listed. Both finished games and the ones to be played yet. If you put “now” instead of date (<em>/schedule/now</em>) — the current game weeh would be served. All games are grouped by days in gameWeek.games structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*rDIGWXeBc34x5e_T3Nu5Nw.png" /></figure><p>If you would like to get weekly schedule for the specific team, use this URL:<br><em>/v1/club-schedule/{team}/week/{date}</em></p><p>Here <strong>team</strong> is a short code of the team. <strong>Date</strong> — YYYY-MM-DD format.</p><p>Example — weekly games for Florida Panthers:</p><pre>curl -L -X GET &quot;https://api-web.nhle.com/v1/club-schedule/FLA/week/2024-11-10&quot;</pre><p>What game statistics we can get using this URL? Let’s check it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmVH9dHzeaGR_bqEGjhJ6w.png" /></figure><ul><li><em>id</em> — this is a universal game ID;</li><li><em>gameState</em> — actual status of the game. Values: FUT — future, OFF — finished;</li><li><em>awayTeam</em> — short stats on away team and scoring;</li><li><em>homeTeam</em> — the same information about the home team;</li><li><em>venue</em> — arena game took place on.</li></ul><p>🍓 <strong>Action.</strong> Let’s print out the list of games with teams and scores.</p><blockquote><strong>Note:</strong> I’ll put .ovi extension to a program file . He deserved it.</blockquote><pre>import requests<br>API_URL = &quot;https://api-web.nhle.com/v1/&quot;<br><br># fetch game list<br>response = requests.get(API_URL + &quot;schedule/2024-11-10&quot;, params={&quot;Content-Type&quot;: &quot;application/json&quot;})<br>data = response.json()<br><br># loop through dates<br>for date in data[&quot;gameWeek&quot;]:<br>    print(&quot;--- Date:&quot;, date[&quot;date&quot;])<br><br>    # and now through games<br>    for game in date[&quot;games&quot;]:<br>        print(&quot;.&quot;, game[&quot;awayTeam&quot;][&quot;placeName&quot;][&quot;default&quot;], &quot;﹒&quot;,<br>        game[&quot;homeTeam&quot;][&quot;placeName&quot;][&quot;default&quot;], &quot;/&quot;,(<br>        f&quot;{game[&#39;awayTeam&#39;][&#39;score&#39;] if &#39;score&#39; in game[&#39;awayTeam&#39;] else &#39;&#39;}&quot;<br>        f&quot;:&quot;<br>        f&quot;{game[&#39;homeTeam&#39;][&#39;score&#39;] if &#39;score&#39; in game[&#39;homeTeam&#39;] else &#39;&#39;}&quot;<br>        ), &quot;/&quot;, game[&quot;gameState&quot;])</pre><p>You should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ckgG_TpN_H3TrH3ev4hwVg.png" /></figure><p>So there are games that are finished already, one is in the progress and a bunch of planned.</p><p>Now let’s dive deeper for more 🍓🍓🍓</p><h3>Game statistics</h3><p>Game log by NHL API is incredible. It contains every action of the game and detailed, pre-calculated statistics. The main endpoint: <em>/v1/gamecenter/GAME-ID/play-by-play</em>. Player stats sit here: <em>gamecenter/GAME-ID/boxscore</em>. Example:</p><p><a href="https://api-web.nhle.com/v1/gamecenter/2024020240/play-by-play">https://api-web.nhle.com/v1/gamecenter/2024020240/play-by-play</a> — this one has pretty interesting game play.</p><blockquote>Live game stats can be quite big. From my experience — from ~2<em>00KB</em> to ~<em>800KB</em>.</blockquote><p>What NHL delivers inside?</p><ul><li><em>periodDescriptor</em> — information about the current period;</li><li><em>clock</em> — info about time left and current pauses;</li><li><em>rosterSpots</em> — team rosters for the match;</li><li><em>plays</em> — all events of the match.</li></ul><p>Results of <em>gamecenter/GAME-ID/boxscore</em> contain stats per each player grouped by team and player types: forwards, defence, goalies. For example, you can loop through all forwards in the game and check their points:</p><pre>API_URL = &quot;https://api-web.nhle.com/v1/&quot;<br><br>response = requests.get(API_URL + &quot;gamecenter/2024020240/boxscore&quot;, params={&quot;Content-Type&quot;: &quot;application/json&quot;})<br>data = response.json()<br><br>for player in data[&quot;playerByGameStats&quot;][&quot;awayTeam&quot;][&quot;forwards&quot;]:<br>    print(f&#39;{player[&quot;sweaterNumber&quot;]} - {player[&quot;points&quot;]}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*6A5czxmWwLjJvUEotorrLw.png" /></figure><p>Actually statistics is quite complete. It does contain both live data and summarised statistics on top of it right in the same JSON file. I’d like to show how to gather custom game statistics by processing <em>plays</em> structure.</p><p>🍓 <strong>Action.</strong> Let’s output the number of goals scored into the empty net in the 3rd period.</p><p>Our goal is to loop through all game events (<em>plays</em>) and analyze data for each of them. Event data consists of the following sections:</p><ul><li><em>typeCode</em>— actual event type code. typeDescKey contains textual reference. Examples: goal, faceoff, shot-on-goal, etc.</li><li><em>timeInPeriod</em>— time list in the period;</li><li><em>periodDescriptor</em> — period information;</li><li><em>details.xCoord/yCoord</em>— where action took place. Not sure about coordinate units but seems these are US feets, optional.</li></ul><pre>API_URL = &quot;https://api-web.nhle.com/v1/&quot;<br><br># fetch game data<br>response = requests.get(<br>    API_URL + &quot;gamecenter/2021020570/play-by-play&quot;,<br>    params={&quot;Content-Type&quot;: &quot;application/json&quot;},<br>)<br>data = response.json()<br><br># filter events, search for empty net goals in the 3rd period<br>empty_net_goals = [<br>    x<br>    for x in data[&quot;plays&quot;]<br>    if x[&quot;periodDescriptor&quot;][&quot;periodType&quot;] == &quot;REG&quot;<br>    and x[&quot;periodDescriptor&quot;][&quot;number&quot;] == 3<br>    and x[&quot;typeDescKey&quot;] == &quot;goal&quot;<br>    and not &quot;goalieInNetId&quot; in x[&quot;details&quot;]<br>]<br><br>print(&quot;Empty net goals:&quot;, len(empty_net_goals))</pre><p>Here we go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*WkDHwKLbdy0CAn20sixb3A.png" /></figure><p>To be fare 1 empty net goal is not rare. 2 goals — is a 💎. Carolina Hurricanes vs Columbus Blue Jackets<strong>, </strong>7:4, 2022–01–01.</p><p>🍓 <strong>Action.</strong> Let’s calculate how many seconds left till the end of the 3rd period after the last goal was scored. And fire alert if the goal was scored during the last minute, 20 or 6 seconds of the 3rd.</p><p>Fetching data for the game ID = <em>2021020577</em>:</p><pre>import requests<br><br>response = requests.get(API_URL + &quot;/game/2021020577/feed/live&quot;, params={&quot;Content-Type&quot;: &quot;application/json&quot;})<br>data = response.json()</pre><p>Filter out all goals for the 3rd period:</p><pre>all_goals = filter(<br>    lambda x: x[&quot;about&quot;][&quot;periodType&quot;] == &quot;REGULAR&quot;<br>    and x[&quot;about&quot;][&quot;ordinalNum&quot;] == &quot;3rd&quot;<br>    and x[&quot;result&quot;][&quot;eventTypeId&quot;] == &quot;GOAL&quot;,<br>    data[&quot;liveData&quot;][&quot;plays&quot;][&quot;allPlays&quot;]<br>)</pre><p>Now let’s gather list of all times left for each goal:</p><pre>time_left = [x[&quot;timeRemaining&quot;] for x in all_goals]<br>last_goal_time = 999999</pre><p>Let’s take the last goal left time and process it:</p><pre>if len(time_left) &gt; 0:<br>    # convert MM:SS into seconds<br>    last_goal_time = time_left[-1].split(&quot;:&quot;)<br>    if len(last_goal_time) == 2:<br>        last_goal_time = int(last_goal_time[0]) * 60 + int(last_goal_time[1])<br>    print(&quot;Last goal time:&quot;, last_goal_time)<br><br>    if last_goal_time &lt; 6:<br>        print(&quot;Goal scored at the last 5 seconds!&quot;)<br>    elif (last_goal_time &lt; 21):<br>        print(&quot;Goal scored at the last 20 seconds!&quot;)<br>    elif (last_goal_time &lt; 61):<br>        print(&quot;Goal scored in the last minute!&quot;)<br>else:<br>    print(&quot;No goals scored in the 3rd&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*b9rZFVFDG2RpU4iDmg5HWA.png" /></figure><p>So only 11 seconds of the game left when the last goal was scored. Nice! I guess the game was 🌶. San Jose Sharks vs Pittsburgh Penguins, 5:8, 2022–01–02.</p><p>🍓 <strong>One more action.</strong> Let’s calculate how many times there was a tie game, example: 1:1, 2:2, 3:3, etc.</p><p>Let’s fetch data for game ID = 2021020582:</p><pre>API_URL = &quot;https://api-web.nhle.com/v1/&quot;<br><br># fetch game data<br>response = requests.get(<br>    API_URL + &quot;gamecenter/2021020582/play-by-play&quot;,<br>    params={&quot;Content-Type&quot;: &quot;application/json&quot;},<br>)<br>data = response.json()</pre><p>Find all regular goals and store it in <em>all_regular_goals</em> list.</p><pre>all_regular_goals = [<br>    x<br>    for x in data[&quot;plays&quot;]<br>    if x[&quot;periodDescriptor&quot;][&quot;periodType&quot;] == &quot;REG&quot;<br>    and x[&quot;typeDescKey&quot;] == &quot;goal&quot;<br>]</pre><p>Now collect scores of tie game moments and print them out.</p><pre>equal_score = []<br>for item in all_regular_goals:<br>    if item[&quot;details&quot;][&quot;homeScore&quot;] == item[&quot;details&quot;][&quot;awayScore&quot;]:<br>        equal_score.append(item[&quot;details&quot;][&quot;homeScore&quot;])<br>print(&quot;Equal score found:&quot;, len(equal_score))<br><br>for score in equal_score:<br>    print(&quot;-&quot;, f&#39;{score}:{score}&#39;)</pre><p>For this particular game we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*UkmelmNSW3Q4QF8EuUkXVg.png" /></figure><p>Oh, this is a 🔥 game! Winnipeg Jets vs Vegas Golden Knights, 5:4 OT, 2022–01–02.</p><h3>Usage scenarios</h3><p>I hope this article helps to dive into the API that NHL generously shares with us. And this material will help to start creating something exciting with a help of Python.</p><p>Personally I see application of this knowledge in real-time analysis, in post-game analysis, findings statistics anomalies, filtering out new records.</p><p>As for forecasting, machine learning — not sure this is quite applicable here. Because, at first, game patterns change a lot. Each 10 years game and players characteristics change quite significant. At second, data produced each year is not big one. It’s about 1300 games per season, which is not generous. So computerised models would have low success rate. Of course, I may be wrong.</p><p>But anyway good luck with your projects. Hockey is a great fun.</p><h3>⭐️ Bonus</h3><ul><li><a href="https://github.com/vtashlikovich/nhl-game-hotness">https://github.com/vtashlikovich/nhl-game-hotness</a> — my repository for a service that makes analysis of games’ hotness based on lots of metrics. Uses latest NHL API (2023+).</li><li><a href="https://github.com/Zmalski/NHL-API-Reference">https://github.com/Zmalski/NHL-API-Reference</a> — good documentation on NHL API by Zach M.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XMEH8h4NBGAyh7cdjJrsgg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745fcd6838c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>