<?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 Pejman Nik on Medium]]></title>
        <description><![CDATA[Stories by Pejman Nik on Medium]]></description>
        <link>https://medium.com/@pejmanNik?source=rss-fbaf2dc8ac01------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aXAMon_6NlRxeNXVkkZSvw.jpeg</url>
            <title>Stories by Pejman Nik on Medium</title>
            <link>https://medium.com/@pejmanNik?source=rss-fbaf2dc8ac01------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:34:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pejmanNik/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[AI Is Making Our Conversations Longer]]></title>
            <link>https://medium.com/@pejmanNik/ai-is-making-our-conversations-longer-838394e99eb8?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/838394e99eb8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[conversations]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Sun, 03 May 2026 10:59:53 GMT</pubDate>
            <atom:updated>2026-05-03T10:59:53.804Z</atom:updated>
            <content:encoded><![CDATA[<p>More words, less clarity, and the growing tax on human attention.</p><p>AI is a genuinely useful tool. It can handle the most boring parts of the job, speed up time consuming tasks, and help avoid embarrassing typos or grammar mistakes. Used well, it can significantly improve productivity.</p><p>I believe opinions are expensive. They’re high maintenance, low-value, and far too easy to acquire, so I try to keep as few of them as possible. Recently, though, I had to add a new one: <strong>I hate AI-generated conversations</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*bwbQS0Y3sVVVq5NI34kKJQ.gif" /></figure><p>Even in my mother tongue, I make plenty of typos. AI is incredibly useful here: I can write as fast as I think, without worrying about spelling or grammar, and let it polish the result afterward.</p><p>But if you put the AI in the pilot seat and you act as the editor, it can turn a short Slack conversation into a full blog post. Given the amount of extra adjectives, preposition and formatting, probably a thesis.</p><p>“Can we postpone the meeting until tomorrow?”, is professional, realistic, and grammatically correct. But when you give it to AI, it turns into a paragraph of unnecessary words. Every time, I have to spend more and more time reading the exact same sentence, just wrapped in 100 extra words. That means more time, less attention, and sometimes I end up skipping lines because AI tends to repeat itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qF3_T3dREs2TlzKhCZjAOA.png" /><figcaption>AI generated image of slack message</figcaption></figure><p>This gets even worse when someone moves a technical conversation to an LLM. Besides the wall of unnecessary text, the response loses all meaning. I’m trying to make a point and reach a mutual understanding, while the LLM is determined to “win” the debate. Meanwhile, the other person is just copy/pasting messages from our chat into an LLM and pasting it back.</p><p>Honestly, I sometimes wish Slack had Twitter-style character limits: 160 characters, and that’s it. I’m not that young to suffer from a short attention span, but if you can make a point in five words, why use a hundred?</p><p><em>Originally published at </em><a href="https://pejmannik.dev/blog/ai_is_making_our_conversations_longer/"><em>https://pejmannik.dev</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838394e99eb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UUID v7 for SQL Server Indexes: Still a Bad Idea]]></title>
            <link>https://medium.com/@pejmanNik/uuid-v7-for-sql-server-indexes-still-a-bad-idea-pejmannik-79d215a10434?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d215a10434</guid>
            <category><![CDATA[mssql]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[uuid]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Fri, 01 May 2026 00:00:48 GMT</pubDate>
            <atom:updated>2026-05-01T17:05:55.584Z</atom:updated>
            <content:encoded><![CDATA[<p>Explore why UUID v7 fails as a index key in SQL Server, how uniqueidentifier sorting works, and why it causes massive index fragmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2ysBcM3sFoj_H6Gh2XHdQ.png" /></figure><p><em>Originally published at </em><a href="https://pejmannik.dev/blog/uuid_v7_for_sql_server_indexes_still_a_bad_idea/"><em>https://pejmannik.dev</em></a></p><p>With the release of .NET 9, we finally got native UUID v7 support via <a href="https://learn.microsoft.com/en-us/dotnet/api/system.guid.createversion7">Guid.CreateVersion7()</a>. My first thought was: Great, this should finally make GUIDs sane for indexes in SQL Server. Well...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*o9A0uxGBzLbOM5zk2U14Aw.gif" /></figure><h3>What is the problem with GUIDs?</h3><p>Generally, using random GUIDs (UUID v4) as clustered (or nonclustered) indexes in SQL Server is a terrible idea. SQL Server stores indexes as a sorted B-trees. When your key is completely random, every insert lands somewhere random too.</p><p>That means page splits, fragmentation, and plenty of extra I/O. Databases are fast, but once your table grows large and your insert rate climbs, this randomness quickly converts into a real performance problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5S7W9WDKKLqTjrlcyhvZA.png" /></figure><p>The general solution is straightforward: use sequentially generated GUIDs. Entity Framework has shipped <a href="https://github.com/dotnet/efcore/blob/main/src/EFCore/ValueGeneration/SequentialGuidValueGenerator.cs">SequentialGuidValueGenerator</a> for years. It generates GUIDs that are still random, while ensuring each new value sorts after the previous one (at least on the local machine).</p><p>SQL Server also provides <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql">NEWSEQUENTIALID()</a>, but its algorithm differs slightly.</p><ul><li><a href="https://btree.app/">How a B-tree Search Works</a></li><li><a href="https://www.sqlservercentral.com/articles/understanding-the-internals-of-a-data-page">What is Page?</a></li><li><a href="https://www.geeksforgeeks.org/sql/clustered-and-non-clustered-indexing/">Sql Server clustered and nonclustered index</a></li><li>During the research for this post, I found out that PostgreSQL <a href="https://www.dbrnd.com/2016/12/postgresql-cluster-improve-index-performance-no-default-cluster-index-explicit-lock-physical-order-data/">doesn’t have clustered indexes</a>.</li></ul><h3>UUID v7 is (practically) sequential</h3><p>Based on the UUID specification, the text format is as follows where v is the version and w is the variant:</p><pre>xxxxxxxx-xxxx-vxxx-wxxx-xxxxxxxxxxxx</pre><p>Unlike UUID v4, where every x is random, UUID v7 stores the Unix timestamp (in milliseconds) in the first 12 x as hexadecimal digits. The remaining x are random. For example:</p><pre>019ddfb1-8527-7b7e-93ea-6cefea2c3b90<br>019ddfb1-8527-7c34-b4fb-189eb2249446<br>019ddfb1-8527-7a5c-8627-af24f40e4b0f<br>019ddfb1-8527-79b4-ac9a-1be6cf8f58ef</pre><p>Compared to UUID v4:</p><pre>9836356a-2a23-4dd7-bdd3-7665633d1a4a<br>b85d8546-bcb0-4974-8239-d592b25af77c<br>dd2e0dbd-4f60-41ee-a102-c025e908afde<br>d4a45075-782f-4dd1-8a16-ec9fcd154153</pre><p>At first glance, UUID v7 looks like exactly what we want. Sequential and standardized.</p><h3>SQL Server sorting is… special</h3><p>Let’s look at how EF Core’s SequentialGuidValueGenerator works. If we check the code carefully, It only replaces the last 8 bytes of the GUID with sequential data.</p><pre>...<br>var guidBytes = MemoryMarshal.AsBytes(new Span&lt;Guid&gt;(ref guid));<br><br>guidBytes[09] = counterBytes[0];<br>guidBytes[08] = counterBytes[1];<br>guidBytes[10] = counterBytes[7];<br>guidBytes[11] = counterBytes[6];<br>guidBytes[12] = counterBytes[5];<br>guidBytes[13] = counterBytes[4];<br>guidBytes[14] = counterBytes[3];<br>guidBytes[15] = counterBytes[2];<br>...</pre><p>In other words, only the last 16 x change:</p><pre>ea53f1f2-398b-40a7-7656-08dea6e9ba6d<br>7389f15d-d6fd-4d73-7657-08dea6e9ba6d<br>eb341e7a-e01a-4271-7658-08dea6e9ba6d<br>21ea3533-9194-41c9-7659-08dea6e9ba6d<br>04702e13-abe5-401d-765a-08dea6e9ba6d</pre><p>This looks almost backwards compared to UUID v7. That is because of how the SQL Server sort algorithm works for uniqueidentifier columns.</p><p>SQL Server sorts uniqueidentifier values differently than pretty much everyone else. Instead of starting from the first byte, it gives highest priority to the last bytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*LGPtThQCCHNFFCbSswpEQA.gif" /></figure><p>Based on. <a href="https://web.archive.org/web/20120628234912/http://blogs.msdn.com/b/sqlprogrammability/archive/2006/11/06/how-are-guids-compared-in-sql-server-2005.aspx">Ordering of uniqueidentifier in sql server</a>:</p><blockquote><em>we look at bytes {10 to 15} first, then {8–9}, then {6–7}, then {4–5}, and lastly {0 to 3}.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDEHdREw15MhkfRGRhK_YA.png" /></figure><p>That is due to some historical reason and tied to RFC 4122, In the UUID v1 the last 6 bytes are node id, and the node id was based on a machine’s MAC address so probably the sorting was designed to be most sensitive to the parts of the GUID that changed the least frequently or likely to group GUIDs by originating machine.</p><ul><li><a href="https://devblogs.microsoft.com/oldnewthing/20190426-00/?p=102450">How many ways are there to sort GUIDs?</a></li></ul><h3>Why UUID v7 is a poor index key in SQL Server</h3><p>UUID v7 places its sequential timestamp in the first six bytes. Because of how SQL Server sorts uniqueidentifier values, UUID v7 behaves almost like UUID v4 in a SQL Server index. You still end up with random inserts, page splits, and fragmentation.</p><p>In our case, this simple change turned a production insert operation from 20 minutes into hours and created a fun afternoon for a colleague, who got to replace every CreateVersion7() call in the codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d215a10434" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My 5-Year Journey Solving Web-to-PDF Pagination]]></title>
            <link>https://medium.com/@pejmanNik/my-5-year-journey-solving-web-to-pdf-pagination-7b05390e718c?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b05390e718c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[report]]></category>
            <category><![CDATA[html-to-pdf]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 00:00:26 GMT</pubDate>
            <atom:updated>2025-11-30T18:20:40.111Z</atom:updated>
            <content:encoded><![CDATA[<p>Paprize: Effortless Report library</p><p>Five years ago, I faced a problem. My web app needed a simple report featuring a header and footer on every page, and a long table spanning multiple pages.</p><p>It seemed straightforward enough. To get headers and footers, my application produced an HTML file and used <a href="https://wkhtmltopdf.org/">wkhtmltopdf</a> to convert it to PDF. However, the library relied on an outdated WebKit engine, limiting the web features I could use. It had limited capabilities regarding headers and footers, and the library was eventually archived.</p><h3>The First Attempt: A Puppeteer Hack</h3><p>I found a hack to solve my issues. I used standard Puppeteer and Chrome’s toPDF method. To gain full control over headers, footers, and pagination, my algorithm created two sets of PDFs and merged them using <a href="https://github.com/Hopding/pdf-lib">pdf-lib</a>.</p><ol><li><strong>Set 1:</strong> Contained the actual report content, but with top and bottom margins calculated to leave empty space for the header and footer.</li><li><strong>Set 2:</strong> Contained empty pages (based on the page count of Set 1), where the algorithm manually generated the headers and footers with page numbers.</li></ol><p>The algorithm then merged these two together to create the final report. The result was the <a href="https://github.com/PejmanNik/puppeteer-report"><strong>Puppeteer-report</strong></a> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lulzGw7IGJtGjVVg.png" /></figure><p>This was elegant, but very limited. <em>pdf-lib</em> was eventually abandoned, and merging PDFs broke certain features like hyperlinks. My main issue, however, was that I needed more control over pagination, something like MS Word. I wanted to create sections, have complete control over design and spacing, and make tables look elegant. Specifically, when a table split across multiple pages, I needed the table header to repeat automatically, and I needed a table footer (e.g., to show a sum of orders) at the bottom of the page. Extending this library to support that was impossible.</p><h3>The Second Attempt: Jikji &amp; React Fiber</h3><p>The following year, I created <a href="https://github.com/PejmanNik/jikji"><strong>Jikji</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRr9gwlhKn12S47l_IM3hw.png" /></figure><p>This solution was based on React. It allowed me to design reports using React components and provide a custom layout engine instead of relying on the browser to handle pagination. It was even possible to preview the paginated report directly in the web app, allowing users to print it directly or save it as a PDF. It solved my design problems and made creating component based reports easy.</p><p>To convert the React App into a report, Jikji hooked into the <strong>React Fiber tree</strong>. It rearranged components based on page size, injected header and footer components, and recreated the component tree with the new layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhxHlVxIeWgcPp1JtitwNg.png" /></figure><p>However, handling pagination required complex calculations. Because of the massive feature set of CSS (like flexbox or floats), the calculation logic was fragile and easy to break. Eventually, with the release of <strong>React 19</strong>, using the internal React Fiber API became impossible. Furthermore, from a library perspective, it forced users to use React, which was over engineering for simple use cases.</p><h3>The Solution: Paprize</h3><p>Eventually, three years later, <a href="https://paprize.page/"><strong>Paprize</strong></a> was born.</p><p>I decided to merge the simple HTML basis of <em>Puppeteer-report</em> with the advanced features of <em>Jikji</em> to find a better solution for handling spacing without complex calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqaGHOL0GpHaFHPoiBhVlg.png" /></figure><p>Paprize provides the same idea of component based reports but uses native HTML elements. Instead of complex pre calculations, it uses a very simple algorithm: <strong>Tentative Placement</strong>.</p><p>The engine checks if an element’s dimensions fit into the remaining space on the page. It adds the element <em>tentatively</em>. If an overflow occurs, the layout engine rolls back and tries to apply the same logic to the child nodes of that element to split it gracefully.</p><p>This gives the algorithm full control over pagination and allows for the customization of any layout behavior. Combined with the plugin system, it provides a clean way to decouple the core logic from the specific customization needed for different elements.</p><p>The layout engine is much more feature rich and complex, but the core idea remains as I explained: simple, native, and controllable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*OOgWm9y9ampFM2KFVOeCQA.png" /></figure><p>For instance, the <strong>TablePlugin</strong> can repeat the table header on each page and avoid semantically wrong breaks, such as putting a table header at the very end of a page without any rows beneath it.</p><p>Since Paprize is based on native HTML, adding a React wrapper to it was straightforward, and it can easily support other frontend libraries and frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TvjIeloGxGRBuGIGHOj1A.png" /></figure><p>I would be happy to suggest <a href="https://paprize.page/"><strong>Paprize</strong></a> next time you need to create astonishing reports for your application.</p><p><em>Originally published at </em><a href="https://pejmannik.dev/blog/my_5-year_journey_solving_web-to-pdf_pagination/"><em>https://pejmannik.dev</em></a><em> on November 30, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b05390e718c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Durable Azure functions to ASP .Net Core]]></title>
            <link>https://medium.com/@pejmanNik/migrating-durable-azure-functions-to-asp-net-core-feca5176968e?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/feca5176968e</guid>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[durable-functions]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[azur]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 21:36:06 GMT</pubDate>
            <atom:updated>2025-01-05T21:36:06.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>Migrating Durable Azure functions to ASP .Net Core</h3><p>running distributed durable tasks in ASP .Net Core</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3O5XIs5DUqePh9O0l-XsA.png" /></figure><p>My original post: <a href="https://pejmannik.dev/blog/distributed_lock_with_azure_table_storage/">https://pejmannik.dev/blog/distributed_lock_with_azure_table_storage</a></p><blockquote><em>TLDR</em></blockquote><blockquote><em>check the repository : </em><a href="https://github.com/PejmanNik/durabletask-dotnet-aspnet"><em>https://github.com/PejmanNik/durabletask-dotnet-aspnet</em></a></blockquote><blockquote><em>or use NuGet package </em><a href="https://www.nuget.org/packages/Sisu.DurableTask.AspNetCore/"><em>Sisu.DurableTask.AspNetCore</em></a></blockquote><p>We recently migrated a large Azure Function app to ASP.NET Core. One of the biggest challenges we faced was handling durable functions, which were heavily used in the original application.</p><p>My initial idea was to replace durable functions with <a href="https://masstransit.io/">MassTransit</a> Sagas. However, after migrating one orchestration, I realized this was a naive approach. A few lines of code in a durable function ballooned into hundreds of lines of code in MassTransit. The MassTransit code also required additional explanation to be understandable, making it more complex and less readable. Additionally, we lost the excellent traceability and visibility features built into durable functions, such as the <a href="https://marketplace.visualstudio.com/items?itemName=DurableFunctionsMonitor.durablefunctionsmonitor">Durable Functions Monitor</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-ngMXnxWbER_WN5mNEhVw.png" /><figcaption><em>Durable Functions Monitor VSCode extension</em></figcaption></figure><p>While MassTransit is a powerful tool and widely used in the community, it can be challenging to learn. It’s almost not documented (requiring users to watch hours of videos), complicated, has a strong opinionated style and requires a lot of boilerplate code and explicit programming.</p><p>In essence, I was trying to fit a square peg into a round hole. While choreography and orchestration are both valuable patterns, they serve different purposes. Replacing our orchestration pattern with a choreography approach using MassTransit goes beyond simply changing frameworks. It requires a fundamental rethink of the code flow and architecture.</p><p>For our distributed data processor, the orchestration pattern was a better fit. I decided to keep the original design (for processes that can still benefit from orchestration, as Durable Functions are sometimes used to overcome Azure Functions’ limited execution time). This meant I needed to somehow integrate Durable Functions into our ASP.NET Core application.</p><p>Durable Functions are built upon the foundation of the <a href="https://github.com/Azure/durabletask">Durable Task Framework</a>. However, the library lacks native support for crucial features to host it a ASP.NET Core application, like dependency injection and background services.</p><p>I found out that Azure Functions doesn’t actually use the Durable Task Framework directly. Instead, it relies on a wrapper library called <a href="https://github.com/microsoft/durabletask-dotnet">DurableTask-Dotnet</a> which provides the necessary features. However, DurableTask-Dotnet is designed to work with Azure Functions and the <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/sidecar">sidecar pattern</a>:</p><blockquote>The Durable Task .NET Client SDK is a .NET Standard 2.0 library for implementing Durable Task orchestrations and activities. It’s specifically designed to connect to a “sidecar” process, such as the Azure Functions .NET Isolated host, a special purpose sidecar container, or potentially even Dapr.</blockquote><p>DurableTask-Dotnet acts as both a client and a worker for the orchestrator running in the sidecar (Azure Functions host). As a client, it schedules orchestrations in the orchestrator, and as a worker, it pulls tasks from the orchestrator and processes them. However, the actual orchestrator resides in the sidecar process. This means that using this package directly in an ASP.NET Core application won’t work because it lacks the orchestrator component.</p><p>After checking out DurableTask-Dotnet source code, I realized that it forwards requests from the client to the orchestrator using gRPC and retrieves queued tasks from the orchestrator via a background service through gRPC messages. My goal, however, was to create a new client and worker communicator that wouldn’t rely on forwarding calls to the sidecar but would instead handle everything internally.</p><p>The Durable Task Framework already includes the orchestrator’s code. All I needed to do was create a shim wrapper around it and integrate it with DurableTask-Dotnet. Thanks to the well-abstracted design of library, The result was surprisingly simple and straightforward. You can check the <a href="https://github.com/PejmanNik/durabletask-dotnet-aspnet">source code</a> or NuGet package <a href="https://www.nuget.org/packages/Sisu.DurableTask.AspNetCore/">Sisu.DurableTask.AspNetCore</a>.</p><p>Simply this is all you need to add to your application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06xVQTK3UNNBJFKDlTw5DQ.png" /></figure><p>It’s important to note that keeping both the worker and client in the same application is generally not recommended. The load and scaling requirements for workers are typically different from those of clients. However, depending on the specific use case (As a true developer, I’ve learned that starting every answer with ‘Well, it depends…’ is the ultimate cheat code 😁 it’s impossible to be wrong!), it may be reasonable to run both components in the same application.</p><p>Finally, it’s worth mentioning the <a href="https://temporal.io/">Temporal</a> project, which I discovered during my research. Temporal offers a durable execution platform with advanced features and supports major programming languages with excellent documentation. Unlike the Durable Task Framework, it doesn’t lock you into a specific cloud vendor. However, Temporal’s hosting requirements are quite complex, making setup more involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BXtDEVT3SwPGZuHYis7ag.png" /><figcaption><em>Temporal UI</em></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feca5176968e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Debounce with Azure Service Bus]]></title>
            <link>https://medium.com/@pejmanNik/distributed-debounce-with-azure-service-bus-f10d61c665bf?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/f10d61c665bf</guid>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[debounce]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 17:10:34 GMT</pubDate>
            <atom:updated>2024-09-01T17:10:34.357Z</atom:updated>
            <content:encoded><![CDATA[<p>simple implementation of a distributed debounce with Azure Service Bus and Table Storage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOE1fX-Bn5SDThjsyDQAHg.jpeg" /></figure><p>My original post: <a href="https://pejmannik.dev/blog/distributed_lock_with_azure_table_storage/">https://pejmannik.dev/blog/distributed_lock_with_azure_table_storage/</a></p><h3>What is debounce?</h3><p>In electronics when you press a mechanical switch, the contact may not settle immediately; it often makes and breaks contact several times within a few milliseconds. This is known as “bouncing”, The bounce can cause multiple signals to be sent when only one was intended. For instance, pressing a button once might register as multiple presses due to the bouncing.</p><p>Debouncing refers to the process of removing noise or bounce that occur when a mechanical switch, such as a button, is pressed or released <a href="https://www.analog.com/en/resources/glossary/debounce.html">ref</a>.</p><p>In software, we don’t have bouncy switches (Thanks to hardware engineers 😅), and debouncing refers to discarding inputs or events that occurred too close together.</p><p>A simple use case for debouncing is in a search bar on a website. As a user types, each keystroke could trigger a search request. This could lead to many unnecessary requests being sent rapidly, which can overwhelm the server.</p><p>Debouncing the search request ensures that it is only sent after the user stops typing for a short period, resulting in a single request to the server. This approach improves performance and provides a smoother user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*UeQmAbLCOi1O9h11UzKHQA.png" /></figure><h3>What is distributed debounce?</h3><p>When multiple nodes or services are involved, distributed debounce ensures that only one action is taken even if multiple nodes receive similar requests or signals within a short timeframe.</p><p>Even if your service is not distributed and only one instance is running, you shouldn’t rely on an in-memory or local debouncing function. There’s a good chance that the service could be restarted or redeployed, leading to the loss of the debouncing state.</p><p>For instance, imagine we have a service that receives a message from a database change feed whenever a user makes a change. This service gets triggered and needs to run another service that performs complex and heavy analysis over the entire data of the user’s company and stores it somewhere. Without using debouncing, we could end up calling the analysis service repeatedly, even before the previous request has finished.</p><p>If I haven’t convinced you that you need distributed debounce in your fancy architecture, just picture this: everything’s running smoothly, but you’re itching to overengineer something. Voilà! Here’s the perfect excuse to turn a simple problem into a glorious, overcomplicated mess.</p><h3>Distributed debounce with Azure Service Bus and Table Storage</h3><p>If you don’t want to introduce a polling mechanism, especially if you’re already using Azure Service Bus and want to avoid adding new stacks and dependencies to the project, you can implement a simple distributed debounce using Azure Service Bus and Azure Table Storage.</p><p>Basically, debouncing involves four parts:</p><ol><li>Delaying the operation (to gather more requests)</li><li>Capturing requests</li><li>Running the operation</li><li>Discarding all captured requests</li></ol><h4>1. Delaying the operation</h4><p>When the service receives a request, it will create a scheduled message at a future time in an Azure Service Bus Queue debounced-queue and store the corresponding information in Azure Table Storage debounced-table.</p><p>If the operation fails after sending the message to the Azure Service Bus Queue but before storing it in Azure Table Storage, the algorithm will ignore this failure, as described in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*5I_lY0JaPf-jeWIkT858tQ.png" /></figure><h4>2. Capturing requests</h4><p>When the first scheduled message is consumed from the debounced-queue, the service checks the debounced-table. If there are any active records, it will mark all of them as pending using a distributed locking mechanism to avoid concurrent execution.</p><h4>3. Running the operation &amp; 4 Discarding all captured requests</h4><p>The service then runs the operation, and upon completion, deletes all the pending rows.</p><p>If the operation fails during execution, the lock mechanism should release the locked rows in the debounced-table, and it is the caller’s responsibility to handle the exception and retry. For example, you can configure Azure Service Bus to retry automatically or use <a href="https://www.thepollyproject.org/">Polly</a> to add resiliency.</p><h4>4. Discarding all captured requests — Part 2</h4><p>If the debounced-table is empty, it means another message already processed all the requests and this one can be ignored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*e8gAqGcnxqS2_1NlIwqbBg.png" /></figure><h3>Table Schema</h3><p>For the PartitionKey, we can use a static value to represent the operation key (e.g. Analysis_{CustomerId}) to ensure data distribution and keep all related data within the same logical partition. The RowKey must be unique for each request. A timestamp with the correct resolution (seconds or milliseconds) could already help reduce some noise.</p><h3>Locking Mechanism</h3><p>Azure Table Storage supports optimistic concurrency, which can be used to implement a simple version of a distributed lock to satisfy our requirements.</p><p>By adding new columns to the debounced-table to store the Azure Service Bus message ID as the lock holder and the current time as the locking time, we can identify the state of the row.</p><h4>Reading</h4><p>To query related rows from the table, we can read all rows that meet either of the following conditions:</p><ol><li>They are locked by the current message (have the same lock holder).<br>If the process is terminated due to an exception or service restart, it should be able to access the rows it previously locked.</li><li>The sum of the lock time and the operation time is less than the current time.<br>If the process fails to complete for any reason, the rows need to be unlocked and made available again.</li></ol><p>If the operation time exceeds a minute, a message could remain stuck in a locked state for an extended period without an active holder. To prevent this, you should use a short periodic timer to renew the lock consecutively. With this approach, if the operation is aborted, the next message can access the rows, ensuring that recovery time stays within a matter of minutes.</p><h4>Locking</h4><p>First, we query the table to read all unlocked rows. Then, we attempt to update all rows with the lock holder and lock time if the ETag matches. If the operation completes successfully, it means we have locked the rows and can continue.</p><p>If the operation fails, we need to repeat the process, as another process has already made changes to the rows.</p><h3>Conclusion</h3><p>In summary, implementing distributed debounce with Azure Service Bus and Azure Table Storage is a practical way to handle high-frequency operations without overloading your system. This setup keeps things smooth and efficient, ensuring that only one operation runs at a time, even in a distributed environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f10d61c665bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From JSON to Protobuf]]></title>
            <link>https://medium.com/@pejmanNik/from-json-to-protobuf-c5de181513e2?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5de181513e2</guid>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 15:43:11 GMT</pubDate>
            <atom:updated>2024-08-23T07:16:09.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjZnDjYYbYFegD37abPJrg.jpeg" /></figure><p>My original post: <a href="https://pejmannik.dev/blog/from_json_to_protobuf/">https://pejmannik.dev/blog/from_json_to_protobuf/</a></p><p>In <a href="https://sievo.com/">Sievo</a>, one of the first requirements in our software architecture is considering the volume of data, as we process vast datasets from various sources for each customer.</p><p>Sievo grants full technical authority to the teams. Historically, my team has used JSON to serialize these large datasets in asynchronous communication between our services.</p><p>For instance in asynchronous communication, Service A writes the request data in JSON format to a file in our object storage and sends a message to Service B. Service B reads the input file, processes it, and creates a new JSON file for the response. Once completed, it sends a message back to Service A.</p><h3>🤦‍♂️Drawbacks</h3><h4>Type Safety</h4><p>One caveat in this design is type safety. JSON is a loosely typed format, This flexibility can lead to common pitfalls with runtime errors and data corruption.</p><p>Even when you are using the same language across services and sharing the domain model, bugs can still crash the party uninvited. For instance, we had an incident where a property was null due to a bug in the calculation. This caused a failure in the consumer service, which couldn’t handle the null value, and the root cause was hidden behind the deserialization exception.</p><p>As there is no schema validation, you could serialize some properties with decimaltype but JSON will convert it to a standard number, This conversion can go unnoticed, potentially leading to incorrect values in your data.</p><h4>Compatibility</h4><p>The second issue is compatibility. You have to carefully manage changes in the data schema, as Service A might be using schema V2 for serialization while Service B is still using schema V1 for deserialization.</p><p>JSON, by its nature, lacks inherent forward or backward compatibility. Compatibility largely depends on the tools you use. However, due to JSON’s dynamic structure, adding, removing, or modifying a field can easily result in deserialization errors.</p><h4>Performance</h4><p>Because of JSON&#39;s text-based nature and the need for parsing and serialization. When processing large volumes of data, the time it takes to convert JSON strings to native data structures and vice versa can become significant.</p><p>JSON is a verbose format, where even simple data structures can result in large text files, adds to the processing time and increases the amount of data that needs to be transmitted.</p><p>lack of support for more complex data types and binary data in JSON can require additional encoding and decoding steps, further slowing down the process.</p><p>In certain critical areas of our system, we had to implement a custom JSON serializer for specific data types to enhance performance. While this approach did improve efficiency, it made the codebase more complex and difficult to maintain.</p><p>Additionally, to reduce file sizes, we resorted to using custom, shortened names for properties, often replacing them with 2–3 letter synonyms. This might seem extreme, but when dealing with large volumes of data, even small optimizations like these can have a noticeable impact on overall performance.</p><h3>🚀 Moving On from JSON</h3><p>Recently, we had to implement a new service. Based on my experience with our data schema and JSON, I decided to try binary formats. Certainly, there are several alternatives to JSON, and the decision should be made by considering various aspects of your requirements.</p><h4>Why Protobuf?</h4><p>.NET has a built-in binary format, but due to several security issues, it has been deprecated and will soon be removed. “At Microsoft, many teams have transitioned from BinaryFormatter to ProtoBuf“ [<a href="https://github.com/dotnet/announcements/issues/293">ref</a>].</p><p>Protocol Buffers, or Protobuf, is an open-source binary format created by Google that supports most common programming languages.</p><p>It has been widely adopted by the community, actively maintained [<a href="https://github.com/protocolbuffers/protobuf/commits/main/">ref</a>], and used in many projects within Google [<a href="https://protobuf.dev/history/">ref</a>], Reducing the likelihood that the project will be abandoned in a few years. compared to other alternatives like FlatBuffers and Cap’n Proto which offer better performance and lower memory usage.</p><p>Protobuf is strongly typed, backward and forward compatible, and offers promising performance along with very low memory allocation. [<a href="https://blog.devgenius.io/serialization-performance-in-net-json-bson-protobuf-avro-a25e8207d9de">ref</a>]. Also at least to my taste, Protobuf is more developer-friendly.</p><h4>Type Safety</h4><p>In Protobuf, type safety is a fundamental feature, ensured by the strongly-typed nature of the schema. You pay the upfront cost of defining the Protobuf schema, and then the compiler generates code that enforces these types at both compile-time and run-time.</p><p>In the case of missing or null values, the deserialized object’s property will be set to the default value.</p><p>Due to Protobuf’s cross-language compatibility, type safety is guaranteed in any consumer service, regardless of the programming language.</p><h4>Compatibility</h4><p>Protobuf is backward and forward compatible. The compatibility rules are very simple and straightforward, allowing you to <a href="https://protobuf.dev/programming-guides/dos-donts/">almost freely</a> rename, add, or remove fields.</p><p>During deserialization, Protobuf provides unknown fields, which contain fields that the parser does not recognize. These can be beneficial tools for handling breaking changes and eliminating service release dependencies, as you can safely handle changes in the model from the consumer service before releasing the provider service.</p><p>Like everything good in life, it often fades just when we start to enjoy it. the oneof fields can cause complications in compatibility [<a href="https://yokota.blog/2021/08/26/understanding-protobuf-compatibility/">ref</a>].</p><h4>Performance</h4><p>Performance is not just a secondary concern; it is a critical aspect of system design, though it is not the only aspect. I generally disagree with the notion that “You shouldn’t pay for performance until you actually need it.”</p><blockquote>Performance is a feature. If your software doesn’t perform well, it doesn’t matter how many other features it has.<br> — Casey Muratori</blockquote><p>I created a benchmark using .Net 8 and <a href="https://github.com/dotnet/BenchmarkDotNet">BenchmarkDotNet </a>to test how performance changes with varying data amounts and schema similar to what we will use in production.</p><p>The table below shows the results of serializing/deserializing 500,000 objects with nested properties and storing them in a local file. For JSON, I used new line, and for Protobuf, I used the <a href="https://github.com/protocolbuffers/protobuf/issues/10229">length-delimited</a> method as the separator.</p><pre>| Method                |     Mean |    Error |   StdDev | Total Allocations | Total Size (Bytes) | File Size |<br>| --------------------- | -------: | -------: | -------: | ----------------: | -----------------: | --------: |<br>| SerializeJson         |  4.499 s | 0.0839 s | 0.0744 s |         1,501,447 |        464,272,900 |   1.80 GB |<br>| SerializeJsonWithSG   |  3.682 s | 0.0709 s | 0.0947 s |               416 |            221.224 |   1.80 GB |<br>| SerializeProtobuf     |  2.320 s | 0.0451 s | 0.0617 s |           699,293 |        226,949,420 |   1.43 GB |<br>| DeserializeJson       | 10.437 s | 0.2080 s | 0.2395 s |        22,401,401 |      2,846,206,172 |           |<br>| DeserializeJsonWithSG | 10.656 s | 0.2107 s | 0.2342 s |         28,812260 |      3,658,236,620 |           |<br>| DeserializeProtobuf   |  2.146 s | 0.0232 s | 0.0206 s |         1,507,590 |        262,965,604 |           |</pre><p>The allocation report from BenchmarkDotNet didn’t make sense, so I used the Visual Studio Performance Profiler instead.</p><p>The SerializeJsonWithSG and DeserializeJsonWithSG methods use the new <a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation?pivots=dotnet-8-0">source generator for System.Text.Json</a> which enhances performance and memory allocation. This feature was introduced in the .Net 6 and C# 9.</p><p>The results show that by switching from JSON (with source generator context) to Protobuf, we can improve the processing time by 69% and reduce memory allocation by 86.6%.</p><h4>Soft Challenges</h4><p>Introducing a new technology to a project isn’t just a matter of technicality, it’s also about selling the idea to your colleagues. Sometimes, it’s not as straightforward as comparing benchmarks, and the conversation starts with the classic “I don’t like it” and goes downhill from there!</p><p>Being open and maintaining clear communication can help find common ground. Ultimately, every design decision boils down to weighing cost versus benefit, and there’s no such thing as a one-size-fits-all ‘best’ option.</p><p>One notable point that emerged during these conversations is that it can make the service harder to debug and inspect, as the generated files are no longer human-readable.</p><h4>Protobuf is not Human Readability</h4><p>Each time we need to inspect a file, we’ll have to spend additional time converting the Protobuf data file to a readable text format using the protoc CLI or other tooling.</p><p>It is a significant challenge and a serious reason to avoid using binary formats, but everything has a downside, like finding out the ‘perfect’ job comes with a boss who thinks ‘fun’ means mandatory karaoke <em>(not my boss 😁).</em></p><p>As a true engineer, after inventing the problem, I set out to solve it. We needed a tool that could decode large encoded files (even in the gigabyte range) based on Protobuf definitions, handle imports and well-known types from Google, and enable searching within these files.</p><blockquote>Software engineers creating their own problems and solving them just to stay employed!</blockquote><p>My simplest and fastest solution was to create a fully client-side web app. This app wouldn’t require any installation, and with the new File API, I could maintain access to the proto definitions files, eliminating the need to upload them every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CFFAGxvjJgx7YDDh_bKuA.gif" /><figcaption><a href="https://github.com/PejmanNik/protolens">protolens</a></figcaption></figure><p>The result was quite satisfactory and has already helped us debug several issues in the project. I have published the source code on GitHub:</p><p><a href="https://github.com/PejmanNik/protolens">https://github.com/PejmanNik/protolens</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5de181513e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Service Bus Simulator]]></title>
            <link>https://medium.com/@pejmanNik/azure-service-bus-simulator-aa5724fb8bb1?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa5724fb8bb1</guid>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[simulator]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 11:27:11 GMT</pubDate>
            <atom:updated>2024-01-06T11:27:11.357Z</atom:updated>
            <content:encoded><![CDATA[<p>Lazvard Message: A Lightweight AMQP Server Simulator for Azure Service Bus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSSOsemW9mYvKsXv15hv7Q.png" /></figure><p>TL;DR? check the repository:<br><a href="https://github.com/PejmanNik/lazvard-message">https://github.com/PejmanNik/lazvard-message</a></p><p>In the intricate world of software development and testing, simulating server environments is not just a luxury, it’s a necessity. This is particularly true for those integrating Azure Service Bus into their tech stacks. The frustration is real for anyone searching “Azure Service Bus Simulator,” due to the lack of viable, straightforward solutions.</p><p>The challenge intensifies when debugging applications locally. The standard approach is to set up a Service Bus instance in Azure. This is fine for solo projects, but with enterprise-level applications, the complexity multiplies. Each developer needing a separate instance isn’t just cumbersome, it’s a nightmare.</p><p>In my typical fashion, I thought, “Why not build a simulator 🤔” This seemed simple, but I was in for a surprise 🫣.</p><p>Delving into this project, I quickly realized that Azure Service Bus is more than just an AMQP protocol message broker. It involves custom behaviors and logic, requiring meticulous reverse engineering, including inspecting Azure Service Bus responses and exploring client test suites.</p><p>But there’s more to it than simulating the message broker behavior., Azure Service Bus relies on secure communication, so the simulator had to function over HTTPS. After several attempts, I ended up Copy/Pasting 🧑‍💻dotnet dev-certs tools (From Microsoft ASP.NET Core) source code into the project, which efficiently generates a self-signed certificate and adds it to the operating system’s trusted certificates list.</p><p>However, this approach works flawlessly on macOS and Windows, but Linux users face challenges in trusting certificates, requiring manual addition of the trusted certificate, which is inconvenient 😶‍🌫️.</p><p>Navigating these challenges, my quest to create a lightweight Azure Service Bus simulator was a rollercoaster of disappointment and regret. Finally, “Lazvard Message” was born 🐣. It adeptly mirrors Azure Service Bus, but it is possible to encounter varying behaviors between the simulator and the actual Service Bus. If you spot any quirky behaviors, please create an issue in the GitHub repository.</p><p><a href="https://github.com/PejmanNik/lazvard-message">https://github.com/PejmanNik/lazvard-message</a></p><p>Lazvard Message is a compact CLI tool designed for simplicity. To use it, you only need to add your queue, topic, and subscription to the configuration and then run the CLI. It doesn’t yet offer all the features of Azure Service Bus, with aspects like Message Sessions and Transactions still under development.</p><p>The name ‘Lazvard’ (LAZH-vard) is derived from an alternative Persian pronunciation of ‘lazuli’, referring to a vivid blue mineral from which the color Azure derives its name.</p><p><a href="https://en.wikipedia.org/wiki/Azure_(color)">Wikipedia</a>:</p><blockquote><em>The color azure ultimately takes its name from the intense blue mineral lapis lazuli. Lapis is the Latin word for “stone” and lāzulī is the genitive form of the Medieval Latin lāzulum, which is taken from the Arabic لازورد lāzaward, itself from the Persian لاژورد lāžaward, which is the name of the stone in Persian and also of a place where lapis lazuli was mined</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*PX4CYzmAtbHz9EpOuExcVA.jpeg" /><figcaption>Crystals of lazurite, source:<a href="https://en.wikipedia.org/wiki/Lapis_lazuli#/media/File:Lazurite.jpg">https://en.wikipedia.org/wiki/Lapis_lazuli#/media/File:Lazurite.jpg</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa5724fb8bb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANOTHER way to call restful API in Redux]]></title>
            <link>https://medium.com/hackernoon/another-way-to-call-restful-api-in-redux-d8dd991d0779?source=rss-fbaf2dc8ac01------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8dd991d0779</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[restful]]></category>
            <dc:creator><![CDATA[Pejman Nik]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 18:06:02 GMT</pubDate>
            <atom:updated>2019-02-26T18:06:02.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>ANOTHER way to call restFul API in Redux</h3><h4>Announcing a general way to make developer life easier for calling API in React-Redux.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYGU_MEBZaJfWw4HnQtvcg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ymf4_9Y9S_A?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Randy Fath</a> on <a href="https://unsplash.com/search/photos/hard-working?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Recently, I’ve switched from backend development to the frontend side. in first sight, I found API call is truly tough.</p><p>Why we need to make a type + action + take action (redux-saga)+ handler function 😐 for each API call?? and again a type + action + reducer to store the result. I keep asking my self.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stv_a1LpjcQlRiuPHA2ffg.png" /></figure><p>I do a lot of research and all sample and document are the same way more and less. like this example:</p><p><a href="https://hackernoon.com/moving-api-requests-to-redux-saga-21780f49cbc8">Moving API requests to Redux-Saga</a></p><p>So I think to the other way, something more functional.</p><h3>API Client</h3><p>API client is a structure to handle the most API call in one place without duplicate codes (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>). I’ll explain this structure using redux middleware but you can implement it in your way. Even in another middleware library like Tunk or Saga. As you can see the explanation is so simple and straightforward. I try to make it easy to understand</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGSmrOpvIxlcick6CmQ37g.png" /></figure><h4>Implementation</h4><p>API Request is our base API class. you can define it like this:</p><blockquote>I use <a href="https://carbon.now.sh/">Carbon</a> to generate this images for code snips. you can see full implementation in my GitHub.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5l2nN_nCp6lWTIocqPCmw.png" /></figure><p>Whenever you want to call an API you need just create an instance of this class and dispatch this action to redux.</p><p>We can create an action function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxIUOd0UTd2gwDv97MaB9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MazwglnS9sBGEbmySxj1hg.png" /></figure><p>By using this function we can also use call API directly in a Promise (if it needed).</p><p>For the response, we can define APIResponse class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGGJlHStqLr267zSDxyk6g.png" /></figure><p>Now we need to handle the request and complete the puzzle. <strong>The redux middleware</strong> (I use <a href="https://github.com/axios">Axios</a> to sending the request):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jK8kYBWtslAG3sZEc2bhA.png" /></figure><h3>How to Use it?</h3><p>Calling API can’t be easier than it 😎 like the general way we can use redux connect in the component to send a request and receive a response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6m7eRUHIS5BuB6ev094iAA.png" /></figure><h3>How to Customize?</h3><p>You may think of some specific scenarios and how you can handle it with this structure. What solves my problem was this tow powerful option:</p><h4>Option</h4><p>With options. You can define an options object as you need. Something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-Srz8z79fGYAxzIm15zpA.png" /></figure><p>You can define an option for save response in store or show a message after the operation and anything based on your need.</p><h4>Middleware</h4><p>The other thing can give you more control is middleware. If the option is not enough for your need you can define middleware interface like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAEpq4Gl5X9p8qs9ie0Ztw.png" /></figure><p>Now implement this interface and add it to request object to get full control over request flow.</p><p>We need to change APIRequest class to support option and middleware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruIe6_znfnmKMNDctFvLqQ.png" /></figure><h3>Beyond</h3><p>You can even make it better. for example with this structure, you can easily handle all changes in local store to avoid duplication. More specifically you can implement a flow to delete the record from the local store after sending DELETE request In general.</p><p>As I mentioned before I want just to give you an idea about what am I means. if you are interesting you can see a full demo in GitHub:</p><p><a href="https://github.com/PejmanNik/redux-call-api-sample">PejmanNik/redux-call-api-sample</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjxEouS3EaXpavvo6NxfBw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8dd991d0779" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/another-way-to-call-restful-api-in-redux-d8dd991d0779">ANOTHER way to call restful API in Redux</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>