<?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 Pavan Kumar on Medium]]></title>
        <description><![CDATA[Stories by Pavan Kumar on Medium]]></description>
        <link>https://medium.com/@rpavank2000?source=rss-134f05189d1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RkK5pNxx8cN3MpiDO24JKw@2x.jpeg</url>
            <title>Stories by Pavan Kumar on Medium</title>
            <link>https://medium.com/@rpavank2000?source=rss-134f05189d1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:36:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rpavank2000/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[Apple’s Container: Native, Lightweight Container Runtime for macOS]]></title>
            <link>https://medium.com/@rpavank2000/apples-container-native-lightweight-container-runtime-for-macos-44a69d57ef41?source=rss-134f05189d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/44a69d57ef41</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Pavan Kumar]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 07:24:46 GMT</pubDate>
            <atom:updated>2025-06-10T07:45:53.952Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift-based containers with VMs, no Docker daemon, and sub-second Linux boots on Apple Silicon</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZIISILEbiX_6ttGnPXqmA.png" /><figcaption>Generated by ChatGPT</figcaption></figure><blockquote><em>Disclaimer: These are my own thoughts and analysis of the project. I wrote this article based on my understanding and exploration of the technology. I used an AI assistant to help with grammar and sentence refinement for better readability.</em></blockquote><h3>Introduction</h3><p>Apple has open-sourced a new project called <strong>Container</strong>, which represents a native and lightweight container runtime tailored specifically for Apple Silicon Macs. Unlike Docker or Podman, this is a system-level, Swift-powered alternative designed to run Linux container workloads in a secure and high-performance manner using the Virtualization framework.</p><p>The Container project is a complement to another Apple repository called <strong>Containerization</strong>, which provides the infrastructure and tooling to manage container images, networking, and kernel configuration. Container focuses more directly on the runtime execution side.</p><h3>What is Apple Container?</h3><p>Container is a Swift-based runtime that enables executing Linux containers on macOS using lightweight virtual machines. The system uses Apple’s Virtulization.framework to spin up highly optimized micro-VMs for each container.</p><p>This architecture brings better isolation, control, and security to containerized workloads without the complexity of traditional container daemons. Each container runs in its own virtual machine, which means there is no shared kernel or reliance on Linux’s native namespace and cgroup systems.</p><h3>Key Capabilities:</h3><ul><li>Launch containers inside lightweight VMs on Apple Silicon.</li><li>Handle process I/O, lifecycle management, and signals.</li><li>Configure container runtime environments with a GRPC interface via vsock.</li><li>Support container image unpacking and root filesystem mounting.</li><li>Basic container lifecycle commands, e.g., start, exec, wait, kill.</li><li>Cross-platform support for both aarch64 and x86_64 binaries via Rosetta 2.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*1QrFCQE2OGtPg1wKNxg1hg.gif" /></figure><h3>How Is It Different From Docker?</h3><p>While Docker relies on Linux’s built-in containerization primitives (like namespaces and cgroups), Apple’s Container uses the Virtulization.frameworkto run containers in entirely separate micro-VMs. This means stronger security boundaries, but with added boot overhead compared to native Linux containers.</p><p>Docker uses a daemon-based architecture with layered filesystems and complex networking setup. Apple’s Container focuses on simpler, composable components. There is no central daemon, no Dockerfile parsing, and no overlay filesystems. Everything is managed using Swift APIs and shell commands from the CLI.</p><h3>What’s Missing or Still Evolving?</h3><p>Although promising, Apple Container is still in early stages (v0.1.0), and lacks many features developers might expect from mature container runtimes like Docker:</p><ul><li>No Dockerfile or image build tooling.</li><li>No volumes, bind mounts, or advanced networking.</li><li>Limited CLI (no logs, stats, or lifecycle events).</li><li>No support for multi-container orchestration (e.g., Compose or Kubernetes).</li><li>Networking isolation is limited in macOS 15 (containers can’t talk to each other via the same vmnet interface).</li><li>Limited support for dynamically resizing or managing resource limits inside the guest VMs.</li></ul><p>These are expected limitations for a low-level project meant to serve as building blocks, not a plug-and-play Docker replacement.</p><h3>Appreciation for Open Sourcing</h3><p>By open-sourcing both Container and Containerization, Apple has taken a major step toward providing a native container solution that fits into the macOS and Apple Silicon ecosystem. It gives developers more flexibility and control to build security-sensitive, performance-aware applications using Swift and modern macOS APIs.</p><p>This release will also serve as a valuable reference for low-level containerization and virtualization implementation strategies using Swift and the Virtulization.framework.</p><h3>Future Possibilities</h3><p>If Apple continues investing in this tooling, we could see:</p><ul><li>A polished CLI similar to Docker or Podman.</li><li>GUI-based tools for managing containers on macOS.</li><li>Full-featured networking stack for container-to-container communication.</li><li>Deeper integration with macOS system services, Xcode, and Swift Package Manager.</li><li>Support for shared filesystems, logging, and introspection APIs.</li></ul><p>For now, developers comfortable with lower-level tooling and Swift will benefit most. This is not yet a replacement for Docker Desktop for most developers, but it’s a strong foundation that may lead to powerful native container experiences in future macOS releases.</p><h3>Final Thoughts</h3><p>Apple’s Container project is not trying to be the next Docker, and that’s a good thing. It’s a fresh take on containerization — built with Swift, optimized for Apple Silicon, and designed around strong isolation and native performance. For now, it remains a project for power users, system developers, and Swift enthusiasts. But with time and investment, it has the potential to reshape how macOS developers think about and use containers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44a69d57ef41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Missing Out! Build a Real-Time Recommendation Engine in .NET Today]]></title>
            <link>https://medium.com/@rpavank2000/stop-missing-out-build-a-real-time-recommendation-engine-in-net-today-0d7ee2e9d9b6?source=rss-134f05189d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d7ee2e9d9b6</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Pavan Kumar]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 05:48:51 GMT</pubDate>
            <atom:updated>2025-03-31T05:48:51.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Missing Out! Build a Real-Time Recommendation Engine in .NET Today</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGv9jgHd4wHcKI7LY1Dl0g.jpeg" /></figure><p>Why did I choose ML.NET over Python for my hobby project?</p><p>A couple of weeks ago, I was working on a hobby project — a simple social media platform where users could follow each other and get friend suggestions. I wanted to add a <strong>“Suggested Friends”</strong> feature to make it feel more dynamic, but I wasn’t sure how to approach it.</p><p>My first thought was to use Python — after all, it’s the go-to language for machine learning. I even started setting up TensorFlow and scikit-learn. But honestly? It quickly became a headache. 😩</p><p>Switching between my C# backend and a Python model meant setting up separate APIs, dealing with serialization issues, and figuring out how to host the model separately. It felt like I was adding unnecessary complexity to a small project that was supposed to be simple and fun.</p><p>That’s when I stumbled upon <strong>ML.NET</strong>. Since my project was already in .NET, it made perfect sense to try it out. I was surprised by how easy it was to integrate — no need to switch languages or set up external infrastructure. ML.NET supports matrix factorization (perfect for recommendation systems), and the fact that it’s optimized for .NET meant everything just <strong>clicked</strong> together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8XPuU9xVj3L6lnmbKV1tw.jpeg" /></figure><p>For more details and the complete codebase discussed in this article, feel free to explore the project on GitHub:<br><strong>Project Link</strong>: <a href="https://github.com/Pavan8374/mq-cache-example">MQ-Cache-Example</a></p><h3>Scope of the Project</h3><p>In this project, the goal was to recommend followers to a user based on two key factors:</p><ol><li><strong>Location-Based Recommendations</strong> — Suggest followers who are geographically close to the user.</li><li><strong>Mutual Connections</strong> — Suggest followers with shared mutual connections.</li></ol><blockquote>Let’s Start</blockquote><h3><strong>Step 1: Setting Up the Environment</strong></h3><p>The first step was setting up ML.NET and preparing the database. Since I needed location-based recommendations, I decided to store user data in <strong>PostgreSQL</strong> with the <strong>PostGIS extension</strong> enabled. PostGIS allows for efficient geographic queries, which would help filter and rank nearby users.</p><p>I installed the necessary ML.NET packages and connected to the database. The goal was to make sure the data pipeline was clean and efficient before starting the training process.</p><p>Hope you can able to create an ASP.NET Core Web App or Console App, I’m skipping those steps.<br>Here are the necessary NuGet packages you need to install in the project.</p><ol><li>Microsoft.ML</li><li>Microsoft.ML.Recommender</li></ol><h3>Step 2: Preparing the Data Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAgrLNeYEelge_tpeY_sOQ.jpeg" /></figure><h4>Fetching Data Efficiently</h4><p>In my case, this is a hobby project. I simply fetched data from the Database and filtered it by LINQ Queries, not suggesting this approach for production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sdYXYvnZgLbwn4gLtPXEQ.png" /></figure><p>Pulling data from the database directly isn’t always the most efficient approach, especially when the dataset grows over time. To handle this, I would suggest an optimized data pipeline that would fetch and process data in batches or store an individual CSV for every user that stores followers, nearest users&#39; data during scheduled cron jobs, <em>as I explained in more detail in step 5</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*pSOZhzOvq8X559oUWr3mSQ.png" /></figure><p>Raw data is rarely perfect. One should need to:</p><ul><li>Remove duplicate follow-up records.</li><li>Eliminate incomplete or incorrect location data.</li><li>Normalize data to ensure a consistent format and structure.</li></ul><h3>Step 3: Training the Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tfwPpEcIO-cuPKNNF9f2A.jpeg" /></figure><p>This is where the magic happens. I chose a <strong>Matrix Factorization Model</strong> for this task. Why? Because matrix factorization is well-suited for collaborative filtering — identifying patterns in user behavior and relationship data to predict new connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*7pdHXFTFcxZSgEvqMEpSVA.png" /></figure><p>ML.NET provides a built-in matrix factorization trainer that simplifies the process of defining and training the model. After a few iterations and tuning the hyperparameters, the model started generating promising results.</p><h3>Step 4: Generating Real-Time Recommendations</h3><h4>Finding Nearby Users</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLvrx73Bhb9P5oFj1Emrag.jpeg" /></figure><p>To calculate geographic proximity, I used the Haversine formula to determine the distance between two sets of latitude and longitude coordinates. The system then filtered out users beyond a certain distance threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*XWk7Cg2eimlN04qbBvfaRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*d-E7mt8cTs3J_63akejiww.png" /></figure><h4>Ranking Based on Mutual Connections</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ev9puQcR-XolnX-eUXFgGg.jpeg" /></figure><p>Using the trained model, I computed the likelihood of a user following another user based on shared mutual connections. The system ranked potential recommendations by proximity and connection strength to produce highly relevant suggestions.</p><h3>Step 5: Optimizing the Data Pipeline</h3><p>Fetching data in real time can be expensive and slow if not optimized correctly. To reduce database load and improve performance:</p><ul><li>Create a background job to periodically export user data (location and follow records) into a CSV file.</li><li>Store the file in <strong>Azure Blob Storage/S3 Bucket/other providers</strong>.</li><li>ML.NET would then load the data directly from the CSV, improving the efficiency of both training and inference.</li></ul><p>This approach ensured that the system could scale to handle larger datasets without sacrificing speed or accuracy.</p><h3>Conclusion</h3><p>Building a recommendation system with ML.NET was surprisingly straightforward and highly effective. The ability to stay within the .NET ecosystem while implementing complex machine learning models is a huge advantage for developers who primarily work with C#.</p><p>ML.NET’s matrix factorization model, combined with PostGIS for location-based filtering, created a powerful combination that delivered fast and accurate recommendations. Whether you’re working on a hobby project or a production-ready system, ML.NET offers a solid, scalable foundation for building intelligent, real-time recommendation engines.</p><blockquote><em>Make sure to follow me on my social platforms so you don’t miss out! 🚀</em></blockquote><p>I hope this article provided you with a clear understanding of how to design and implement a Recommendation system using ML.NET in an ASP.NET Core App.</p><p>If you found this content helpful or enjoyed reading it, please consider following me for more articles on system design, scalable architectures, and ASP.NET Core development. Your support means a lot and helps me create more valuable content!</p><ul><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/pavan-kumar-169019214/">Pavan Kumar</a></li><li><strong>GitHub</strong>: <a href="https://github.com/Pavan8374">Pavan8374</a></li><li><strong>Website</strong>: <a href="https://pavan-rambhukta.vercel.app/">Pavan Rambhukta</a></li><li><strong>Reddit</strong>: <a href="https://www.reddit.com/user/Backend_biryani/">u/rpavank</a></li></ul><p>For more details and the complete codebase discussed in this article, feel free to explore the project on GitHub:<br><strong>Project Link</strong>: <a href="https://github.com/Pavan8374/mq-cache-example">MQ-Cache-Example</a></p><p>Thank you for reading, and I look forward to connecting with you! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d7ee2e9d9b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EF Core Updates: Simple vs. Smart — The Complete Picture]]></title>
            <link>https://medium.com/@rpavank2000/ef-core-updates-simple-vs-smart-the-complete-picture-45d4ca6bc39a?source=rss-134f05189d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/45d4ca6bc39a</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Pavan Kumar]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 12:01:13 GMT</pubDate>
            <atom:updated>2025-02-14T12:01:13.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>EF Core Updates: Simple vs. Smart — The Complete Picture</h3><p>TL;DR: Entity Framework Core offers multiple ways to update records. While the straightforward approach of fetching and updating all fields might seem inefficient, the performance implications aren’t always what you’d expect. This article explores various update patterns, their trade-offs, and when to use each approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rdC-0rDyztsyUenMnFGncw.jpeg" /></figure><h3><strong>Introduction</strong></h3><p>Picture this: You’re building an API endpoint that updates a user’s email address. Simple enough, right? But as you dive deeper, questions start emerging:</p><ul><li>Should you fetch the entire record first?</li><li>What about updating only changed fields?</li><li>Are you unnecessarily updating unmodified columns?</li><li>Does it even matter?</li></ul><p>Let’s explore these questions and uncover some surprising truths about EF Core’s update patterns.</p><h3><strong>The Common Approaches</strong></h3><h4>1. The Fetch-and-Update Pattern</h4><p>This is what you’ll see in most codebases:</p><pre>public async Task UpdateUser(UserUpdateDto request)<br>{<br>    var user = await _context.Users.FindAsync(request.Id);<br>    if (user == null)<br>        throw new NotFoundException(&quot;User not found&quot;);<br>        <br>    user.Email = request.Email;<br>    user.Name = request.Name;<br>    _context.Users.Update(user);<br>    await _context.SaveChangesAsync();<br>}</pre><p>Simple, readable, and gets the job done. But is it efficient?</p><h4>2. The Direct Update Pattern</h4><p>A more surgical approach:</p><pre>public async Task UpdateUser(UserUpdateDto request)<br>{<br>    await _context.Users<br>        .Where(u =&gt; u.Id == request.Id)<br>        .ExecuteUpdateAsync(s =&gt; <br>            s.SetProperty(b =&gt; b.Email, b =&gt; request.Email));<br>}</pre><p>Looks more efficient, but what about validation?</p><h4>3. The Smart Update Pattern</h4><p>A balanced approach that only updates changed fields:</p><pre>public async Task UpdateUser(UserUpdateDto request)<br>{<br>    var user = await _context.Users.FindAsync(request.Id)<br>        ?? throw new NotFoundException(&quot;User not found&quot;);<br>        <br>    if (request.Email != null &amp;&amp; request.Email != user.Email)<br>        user.Email = request.Email;<br>        <br>    if (request.Name != null &amp;&amp; request.Name != user.Name)<br>        user.Name = request.Name;<br>        <br>    if (_context.ChangeTracker.HasChanges())<br>        await _context.SaveChangesAsync();<br>}</pre><h4>The Performance Truth</h4><p>Here’s where it gets interesting. The actual SQL generated for updating all fields versus just changed fields looks like this:</p><pre>-- Update all fields<br>UPDATE Users SET Name = &#39;John&#39;, Email = &#39;john@email.com&#39; <br>WHERE Id = 1;<br><br>-- Update single field<br>UPDATE Users SET Email = &#39;john@email.com&#39; <br>WHERE Id = 1;</pre><p>The surprising truth? The performance difference is often negligible because:</p><ul><li>Both queries hit the database once</li><li>Both use the same index for the WHERE clause</li><li>The I/O difference for updating 1 vs 2 columns is minimal</li><li>Index updates happen regardless</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMnpThsRRcMmJewDyLHQFg.jpeg" /></figure><h3>When Does It Matter?</h3><h4>High Traffic Scenarios</h4><p>If you’re building the next Twitter:</p><ul><li>Every millisecond counts</li><li>Database load is critical</li><li>Direct updates might be worth it</li></ul><h4>Complex Entities</h4><p>If your entity has 20+ fields:</p><ul><li>Tracking changes becomes more important</li><li>Network payload size matters</li><li>Audit requirements might dictate tracking changes</li></ul><h4>Business Requirements</h4><p>Consider these factors:</p><ul><li>Audit logging needs</li><li>Concurrency handling</li><li>Validation requirements</li><li>Business logic complexity</li></ul><h4>The Decision Framework</h4><p>Use the simple fetch-and-update pattern when:</p><ul><li>Building small to medium applications</li><li>Entity has few fields</li><li>Performance isn’t critical yet</li><li>You need full entity validation</li></ul><p>Use the smart update pattern when:</p><ul><li>Dealing with large entities</li><li>Audit logging is required</li><li>Concurrency is a concern</li><li>Business logic depends on changed fields</li></ul><p>Use direct updates when:</p><ul><li>Performance is absolutely critical</li><li>You don’t need existence validation</li><li>You’re dealing with bulk updates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJrn0wEoHMzVvcG2NhJbYw.jpeg" /></figure><h3>Practical Recommendations</h3><h4>1. Start Simple</h4><p>Begin with the fetch-and-update pattern. It’s:</p><ul><li>Easy to understand</li><li>Easy to maintain</li><li>Sufficient for most cases</li></ul><h4>2. Monitor and Measure</h4><p>Watch for:</p><ul><li>Database performance metrics</li><li>Response times</li><li>Resource utilization</li></ul><h4>3. Optimize When Needed</h4><p>Only complicate your code when:</p><ul><li>You have actual performance issues</li><li>You need specific features (audit, concurrency)</li><li>The complexity trade-off is worth it</li></ul><h3>The Dynamic Update Solution</h3><p>For cases where you need to handle dynamic field updates, here’s a robust solution:</p><pre>public class UserUpdateDto<br>{<br>    public int Id { get; set; }<br>    private HashSet&lt;string&gt; ModifiedProperties { get; } = new();<br>    <br>    public void SetProperty&lt;T&gt;(string propertyName, T value)<br>    {<br>        var property = GetType().GetProperty(propertyName);<br>        if (property != null)<br>        {<br>            property.SetValue(this, value);<br>            ModifiedProperties.Add(propertyName);<br>        }<br>    }<br>}<br><br>public async Task UpdateUserAsync(UserUpdateDto updateDto)<br>{<br>    var user = await _context.Users.FindAsync(updateDto.Id)<br>        ?? throw new NotFoundException(&quot;User not found&quot;);<br>        <br>    foreach (var property in updateDto.ModifiedProperties)<br>    {<br>        var entry = _context.Entry(user);<br>        entry.Property(property).IsModified = true;<br>        entry.Property(property).CurrentValue = <br>            updateDto.GetType().GetProperty(property)?.GetValue(updateDto);<br>    }<br>    await _context.SaveChangesAsync();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVLvxq1dcOiQf2Kcp7Wb7w.jpeg" /></figure><h3>Conclusion</h3><p>The choice between update patterns isn’t always about performance. Often, it’s about finding the right balance between:</p><ul><li>Code maintainability</li><li>Performance requirements</li><li>Business needs</li><li>Team expertise</li></ul><p>Remember: premature optimization is the root of all evil. Start simple, measure, and optimize when needed.</p><h3>Resources</h3><ul><li><a href="https://docs.microsoft.com/en-us/ef/core/">Entity Framework Core Documentation</a></li><li><a href="https://docs.microsoft.com/en-us/ef/core/performance/">Performance Best Practices</a></li><li><a href="https://docs.microsoft.com/en-us/ef/core/change-tracking/">Change Tracking in EF Core</a></li></ul><p>What update patterns have you found most effective in your projects? Share your experiences in the comments below!</p><p>If you found this content helpful or enjoyed reading it, please consider following me for more articles on system design, scalable architectures, and ASP.NET Core development. Your support means a lot and helps me create more valuable content!</p><ul><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/pavan-kumar-169019214/">Pavan Kumar</a></li><li><strong>GitHub</strong>: <a href="https://github.com/Pavan8374">Pavan8374</a></li><li><strong>Website</strong>: <a href="https://pavan-rambhukta.vercel.app/">Pavan Rambhukta</a></li><li><strong>Reddit</strong>: <a href="https://www.reddit.com/user/Backend_biryani/">u/rpavank</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45d4ca6bc39a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Single Responsibility Principle: Beyond the Common Misconception]]></title>
            <link>https://blog.devops.dev/understanding-the-single-responsibility-principle-beyond-the-common-misconception-0977f04be1a3?source=rss-134f05189d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0977f04be1a3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Pavan Kumar]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 06:49:23 GMT</pubDate>
            <atom:updated>2025-01-13T20:06:56.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzWOFWWNkIz4GBVXcr_cwg.png" /></figure><p>The Single Responsibility Principle (SRP) is perhaps the most misunderstood of all SOLID principles in software development. Let’s clear up this confusion and understand what it really means for your code.</p><h4><strong>The Common Misconception</strong></h4><p>When developers first hear about the Single Responsibility Principle, they often think it means “a module should do just one thing.” While this is a valid programming principle used when refactoring large functions into smaller ones, it’s not what SRP is about.</p><h4><strong>What SRP Really Means?</strong></h4><p>The true definition of SRP has evolved over time to become clearer:</p><p>1. Initial version: “A module should have one, and only one, reason to change.”<br>2. Refined version: “A module should be responsible to one, and only one, actor.”</p><p>But what does this mean in practice? An “actor” is a group of users or stakeholders who would want to change the system in a particular way. This could be a department, a team, or any group of users with similar needs.</p><h4>A Real-World Example: The Employee Class</h4><p>Let’s look at a practical example that many developers can relate to: an Employee class in a payroll system. Consider this common but problematic implementation:</p><pre>class Employee {<br> public void calculatePay() { … } // Used by accounting<br> public void reportHours() { … } // Used by HR<br> public void save() { … } // Used by DBAs<br>}</pre><p>At first glance, this might seem fine — after all, these are all employee-related functions. However, this class violates SRP because it serves three different actors:</p><p>Accounting department (reporting to CFO): Uses calculatePay()<br>HR department (reporting to COO): Uses reportHours()<br>Database administrators (reporting to CTO): Uses save()</p><h3>Why This Violation Causes Problems</h3><h4>Problem 1: Accidental Code Duplication and Changes</h4><p>Imagine this scenario:</p><pre><br>class Employee {<br> private float regularHours() { … } // Shared by both methods<br> <br> public void calculatePay() {<br> float hours = regularHours();<br> // Calculate pay using hours<br> }<br> <br> public void reportHours() {<br> float hours = regularHours();<br> // Generate report using hours<br> }<br>}</pre><p>When the accounting team wants to change how regular hours are calculated, they might modify the shared regularHours() method. However, this change could unexpectedly affect HR’s reports, potentially causing significant financial errors. This happened because code serving different actors was too tightly coupled.</p><h4>Problem 2: Risky Code Merges</h4><p>Consider this situation:<br>- A DBA needs to modify the save() method for a database schema change<br>- An HR clerk needs to update the reportHours() method for a new report format</p><p>If two developers work on these changes simultaneously, they’ll need to merge their code. This creates unnecessary risk since these changes are for different actors and shouldn’t need to be coordinated.</p><h3>How to Fix SRP Violations</h3><p>Here are three practical solutions to fix this issue:</p><h4>1. Complete Separation</h4><p>Split the functionality into three separate classes:</p><pre><br>class EmployeeData {<br> // Just data, no methods<br>}<br><br>class PayCalculator {<br> private EmployeeData employeeData;<br> public void calculatePay() { … }<br>}<br><br>class HourReporter {<br> private EmployeeData employeeData;<br> public void reportHours() { … }<br>}<br><br>class EmployeeRepository {<br> private EmployeeData employeeData;<br> public void save() { … }<br>}</pre><h4>2. Using a Facade Pattern</h4><p>Create a facade to simplify usage:</p><pre><br>class EmployeeFacade {<br> private PayCalculator payCalculator;<br> private HourReporter hourReporter;<br> private EmployeeRepository repository;<br> <br> public void calculatePay() {<br> payCalculator.calculatePay();<br> }<br> <br> public void reportHours() {<br> hourReporter.reportHours();<br> }<br> <br> public void save() {<br> repository.save();<br> }<br>}</pre><h4>3. Keeping Core Business Rules Close to Data</h4><p>If calculating pay is the most important function, you might structure it like this:</p><pre><br>class Employee {<br> private EmployeeData data;<br> public void calculatePay() { … } // Most important function stays<br> <br> // Facade methods for other functionalities<br> public void reportHours() {<br> hourReporter.reportHours(data);<br> }<br> <br> public void save() {<br> repository.save(data);<br> }<br>}</pre><h4>Common Concerns Addressed</h4><p>You might worry that this creates too many classes with just one public method each. However, each class will likely contain multiple private methods that work together to accomplish its single responsibility. The key is that these private methods are hidden from the outside world and can be changed without affecting other actors.</p><h4>Conclusion</h4><p>The Single Responsibility Principle isn’t about making every module do just one thing — it’s about organizing code around the actors who will want to change it. When you separate code based on who needs it to change, you create more maintainable, flexible, and robust systems.</p><p>Remember: If you find yourself writing code that different departments or teams might want to change for different reasons, it’s time to think about splitting that code up according to SRP.</p><p>By understanding and applying SRP correctly, you can create code that’s easier to maintain, test, and modify, while reducing the risk of unexpected side effects when making changes. The key is to think about who wants the code to change, rather than just what the code does.</p><p>If you found this content helpful or enjoyed reading it, please consider following me for more articles on system design, scalable architectures, and ASP.NET Core development. Your support means a lot and helps me create more valuable content!</p><ul><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/pavan-kumar-169019214/">Pavan Kumar</a></li><li><strong>GitHub</strong>: <a href="https://github.com/Pavan8374">Pavan8374</a></li><li><strong>Website</strong>: <a href="https://pavan-rambhukta.vercel.app/">Pavan Rambhukta</a></li><li><strong>Reddit</strong>: <a href="https://www.reddit.com/user/Backend_biryani/">u/rpavank</a></li></ul><p>Thank you for reading, and I look forward to connecting with you! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0977f04be1a3" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/understanding-the-single-responsibility-principle-beyond-the-common-misconception-0977f04be1a3">Understanding the Single Responsibility Principle: Beyond the Common Misconception</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Like Button: Architecting a High-Performance Engagement System]]></title>
            <link>https://blog.devops.dev/beyond-the-like-button-architecting-a-high-performance-engagement-system-f549c4003dca?source=rss-134f05189d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f549c4003dca</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Pavan Kumar]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 10:05:29 GMT</pubDate>
            <atom:updated>2025-01-09T15:42:55.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6A-SNcOv4PLx382TkVFaQ.jpeg" /></figure><h3>Introduction</h3><p>In today’s digital landscape, interactive features like “likes” and “dislikes” have become foundational elements of platforms ranging from social media to e-commerce to video-sharing services. These simple interactions drive user engagement and power content discovery algorithms, personalization engines, and analytics dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY8bwRU8Cls_xIv1__5-Hg.jpeg" /></figure><p>However, implementing a robust like/dislike system that can scale to handle millions of interactions per second is a complex technical challenge. Imagine you’re running a platform with millions of active users. Every second, thousands of users like and dislike content, especially during viral moments. The backend is overwhelmed with these requests, leading to performance bottlenecks, slow responses, and potential downtime.</p><p>How can we design a system that handles such massive traffic while ensuring real-time feedback, data consistency, and scalability?<br>In this article, we’ll break down how to build a like/dislike system using ASP.NET Core with a modern, event-driven architecture. We’ll explore the core components that make this architecture scalable, performant, and resilient.</p><p>For more details and the complete codebase discussed in this article, feel free to explore the project on GitHub:<br><strong>Project Link</strong>: <a href="https://github.com/Pavan8374/mq-cache-example">MQ-Cache-Example</a></p><p><em>Before Starting this tutorial make sure to create an ASP.Net core Web API project.</em></p><h4>Key Components of the System Design</h4><h4><strong>1. Event-driven architecture with Message Queues</strong></h4><p>Message queues are the backbone of an event-driven system. They decouple the processing of like/dislike events from the user-facing APIs, allowing the system to process these events asynchronously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*Xu8RnlfibaHx1zzf9w5QeQ.jpeg" /></figure><p><strong>Technology Choices</strong>:</p><ul><li><strong>Apache Kafka</strong>: Ideal for high-throughput scenarios and distributed systems. Kafka provides robust partitioning and replication for fault tolerance.</li><li><strong>RabbitMQ </strong>🐇: Lightweight and easy to integrate, RabbitMQ excels at message routing with support for a variety of messaging patterns.</li></ul><p>By queuing like/dislike events, we can handle bursts of traffic without overwhelming the database or other backend services. The queue acts as a buffer, ensuring smooth processing even during peak load.</p><p><strong>In this tutorial, we are going to use Rabbit MQ for Message Queue </strong>📬<strong> Implementation.</strong></p><blockquote>Please install Rabbit MQ exe in your system to use the server and service. Please checkout this link: <a href="https://www.rabbitmq.com/docs/install-windows#installer">Installing on Windows | RabbitMQ</a></blockquote><p>To install the RabbitMQ.Client package through the NuGet Package Manager or the Package Manager Console, you can use the following instructions:</p><blockquote>Using NuGet Package Manager: Search for RabbitMQ.Client and click Install.</blockquote><blockquote>Using Package Manager Console: Install-Package RabbitMQ.Client -Version 7.0.0</blockquote><p>Make sure to set values in appsettings.json and create a class RabbitMQSettings.cs</p><pre>//appsettings.json<br>&quot;RabbitMQSettings&quot;: {<br> &quot;Host&quot;: &quot;localhost&quot;,<br> &quot;Port&quot;: 5672,<br> &quot;UserName&quot;: &quot;guest&quot;,<br> &quot;Password&quot;: &quot;guest&quot;,<br> &quot;VirtualHost&quot;: &quot;/&quot;,<br> &quot;ConnectionRetryCount&quot;: 5,<br> &quot;ConnectionRetryDelayMs&quot;: 1000,<br> &quot;ExchangeName&quot;: &quot;feed_exchange&quot;,<br> &quot;QueueName&quot;: &quot;likes_queue&quot;,<br> &quot;RoutingKey&quot;: &quot;likes&quot;,<br> &quot;DeadLetterExchange&quot;: &quot;feed_dlx&quot;,<br> &quot;DeadLetterQueue&quot;: &quot;likes_dlq&quot;<br> },<br>  &quot;Redis&quot;: {<br>    &quot;ConnectionString&quot;: &quot;localhost:6379&quot;<br>  },</pre><pre>//Create a setting and add the section values at appsettings.json<br>public class RabbitMQSettings<br>{<br> public string Host { get; set; }<br> public int Port { get; set; }<br> public string UserName { get; set; }<br> public string Password { get; set; }<br> public string VirtualHost { get; set; }<br> public int ConnectionRetryCount { get; set; }<br> public string ConnectionRetryDelayMs { get; set; }<br> public string ExchangeName { get; set; }<br> public string QueueName { get; set; }<br> public string RoutingKey { get; set; }<br> public string DeadLetterExchange { get; set; }<br> public string DeadLetterQueue { get; set; }<br>}</pre><p>Create an IMessageQueueService interface and inherit in RabbitMQService and Implement logic.<br>Methods</p><ul><li>PublishAsync&lt;T&gt;(string queueName, T message): This method is responsible for sending messages of type T to a specified queue.</li><li>ConsumeAsync&lt;T&gt;(string queueName, Func&lt;T, Task&gt; handler): This method sets up a consumer that listens for messages of type T from a specified queue and processes them using the provided handler function.</li></ul><pre>//Interface<br>public interface IMessageQueueService<br>{<br>    Task PublishAsync&lt;T&gt;(string queueName, T message);<br>    Task ConsumeAsync&lt;T&gt;(string queueName, Func&lt;T, Task&gt; handler);<br>}<br><br>// Implementation<br>public class RabbitMQService : IMessageQueueService, IDisposable<br>{<br>    private readonly ILogger&lt;RabbitMQService&gt; _logger;<br>    private readonly RabbitMQSettings _rabbitMQSettings;<br>    private IConnection _connection;<br>    private IChannel _channel;<br>    private readonly SemaphoreSlim _initLock = new SemaphoreSlim(1, 1);<br>    private bool _initialized;<br><br>    public RabbitMQService(ILogger&lt;RabbitMQService&gt; logger, IOptions&lt;RabbitMQSettings&gt; rabbitMQSettings)<br>    {<br>        _logger = logger;<br>        _rabbitMQSettings = rabbitMQSettings.Value;<br>    }<br><br>    private async Task InitializeConnectionAsync()<br>    {<br>        if (_initialized) return;<br><br>        try<br>        {<br>            await _initLock.WaitAsync();<br><br>            if (_initialized) return;<br><br>            var factory = new ConnectionFactory()<br>            {<br>                HostName = _rabbitMQSettings.Host ?? &quot;localhost&quot;,<br>                Port = 5672, // Set directly since you&#39;re explicitly setting it<br>                UserName = _rabbitMQSettings.UserName ?? &quot;guest&quot;,<br>                Password = _rabbitMQSettings.Password ?? &quot;guest&quot;,<br>            };<br><br>            _connection = await factory.CreateConnectionAsync();<br>            _channel = await _connection.CreateChannelAsync();<br>            _initialized = true;<br>        }<br>        finally<br>        {<br>            _initLock.Release();<br>        }<br>    }<br><br>    public async Task PublishAsync&lt;T&gt;(string queueName, T message)<br>    {<br>        try<br>        {<br>            await InitializeConnectionAsync();<br><br>            await _channel.QueueDeclareAsync(queueName, durable: true, exclusive: false, autoDelete: false);<br>            var serializedMessage = JsonSerializer.Serialize(message);<br>            var body = Encoding.UTF8.GetBytes(serializedMessage);<br><br>            var props = new BasicProperties<br>            {<br>                ContentType = &quot;text/plain&quot;,<br>                DeliveryMode = (DeliveryModes)2,<br>                Expiration = &quot;36000000&quot;<br>            };<br><br>            await _channel.BasicPublishAsync(<br>                exchange: &quot;&quot;,<br>                routingKey: queueName,<br>                mandatory: true,<br>                basicProperties: props,<br>                body: body);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error publishing message to queue {QueueName}&quot;, queueName);<br>            throw;<br>        }<br>    }<br><br>    public async Task ConsumeAsync&lt;T&gt;(string queueName, Func&lt;T, Task&gt; handler)<br>    {<br>        try<br>        {<br>            await InitializeConnectionAsync();<br><br>            await _channel.QueueDeclareAsync(queueName, durable: true, exclusive: false, autoDelete: false);<br><br>            var consumer = new AsyncEventingBasicConsumer(_channel);<br>            consumer.ReceivedAsync += async (_, ea) =&gt;<br>            {<br>                try<br>                {<br>                    var body = ea.Body.ToArray();<br>                    var message = Encoding.UTF8.GetString(body);<br>                    var deserializedMessage = JsonSerializer.Deserialize&lt;T&gt;(message);<br><br>                    if (deserializedMessage != null)<br>                    {<br>                        await handler(deserializedMessage);<br>                        await _channel.BasicAckAsync(ea.DeliveryTag, false);<br>                    }<br>                }<br>                catch (Exception ex)<br>                {<br>                    _logger.LogError(ex, &quot;Error processing message from queue {QueueName}&quot;, queueName);<br>                    await _channel.BasicNackAsync(ea.DeliveryTag, false, true);<br>                }<br>            };<br><br>            await _channel.BasicConsumeAsync(queue: queueName, autoAck: false, consumer: consumer);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error setting up consumer for queue {QueueName}&quot;, queueName);<br>            throw;<br>        }<br>    }<br><br>    public void Dispose()<br>    {<br>        _channel?.Dispose();<br>        _connection?.Dispose();<br>        _initLock.Dispose();<br>    }<br>}</pre><blockquote>Configure Message Queue services in Program.cs or StartUp.cs Clas</blockquote><pre>services.AddSingleton&lt;IMessageQueueService, RabbitMQService&gt;()</pre><h4>2. Caching for High-Performance Reads</h4><p>Caching is essential for minimizing latency and reducing the load on the database. Instead of querying the database for every like/dislike count update, we store this information in a high-speed, in-memory cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAQS_JhdAk6ThgnlZjWNTQ.png" /></figure><p><strong>Technology Choices</strong>:</p><ul><li><strong>Redis</strong>: A distributed, in-memory data store that offers ultra-fast reads and writes, along with features like data persistence and pub/sub for real-time updates.</li><li><strong>Memcached</strong>: A simpler alternative for pure in-memory caching needs without persistence.</li></ul><p>The cache holds the current counts of likes and dislikes for each post or content item. This ensures near-instant feedback to users and reduces the need for frequent database queries.</p><h4>We are going to use Redis caching for In-Memory reads.</h4><blockquote>Make sure you install Redis in your system before integrating Redis in the project, To install Redis please check this link: <a href="https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/">Redis installation and setup in the system</a>.</blockquote><p>To install the “Microsoft.Extensions.Caching.StackExchangeRedis” package through the NuGet Package Manager or the Package Manager Console, you can use the following instructions:</p><blockquote>Using NuGet Package Manager: Search for “Microsoft.Extensions.Caching.StackExchangeRedis” and click Install.</blockquote><blockquote>Using Package Manager Console: NuGet\Install-Package Microsoft.Extensions.Caching.StackExchangeRedis -Version 9.0.0</blockquote><p>Create an interface ICacheService.cs and inherit in RedisCacheService.cs class, implement the whole logic in RedisCacheService.cs.</p><blockquote>ICacheService.cs and RedisCacheService.cs:</blockquote><pre>public interface ICacheService<br>{<br>    Task SetAsync&lt;T&gt;(string key, T value, TimeSpan? expiration = null);<br>    Task&lt;T?&gt; GetAsync&lt;T&gt;(string key);<br>    Task RemoveAsync(string key);<br>}<br><br>public class RedisCacheService : ICacheService<br>{<br>    private readonly IDistributedCache _cache;<br>    private readonly ILogger&lt;RedisCacheService&gt; _logger;<br><br>    public RedisCacheService(IDistributedCache cache, ILogger&lt;RedisCacheService&gt; logger)<br>    {<br>        _cache = cache;<br>        _logger = logger;<br>    }<br><br>    public async Task SetAsync&lt;T&gt;(string key, T value, TimeSpan? expiration = null)<br>    {<br>        try<br>        {<br>            var options = new DistributedCacheEntryOptions();<br>            if (expiration.HasValue)<br>                options.AbsoluteExpirationRelativeToNow = expiration;<br><br>            var serializedValue = JsonSerializer.Serialize(value);<br>            await _cache.SetStringAsync(key, serializedValue, options);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error setting cache value for key {Key}&quot;, key);<br>            throw;<br>        }<br>    }<br><br>    public async Task&lt;T?&gt; GetAsync&lt;T&gt;(string key)<br>    {<br>        try<br>        {<br>            var value = await _cache.GetStringAsync(key);<br>            return value == null ? default : JsonSerializer.Deserialize&lt;T&gt;(value);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error getting cache value for key {Key}&quot;, key);<br>            throw;<br>        }<br>    }<br><br>    public async Task RemoveAsync(string key)<br>    {<br>        try<br>        {<br>            await _cache.RemoveAsync(key);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error removing cache value for key {Key}&quot;, key);<br>            throw;<br>        }<br>    }<br>}</pre><p>In our application, we utilize a RedisCacheService to efficiently manage user likes for posts. This service acts as a bridge to our Redis distributed cache, allowing us to store, retrieve, and remove like counts seamlessly.</p><p>When a user likes a post, we use the SetAsync method to save the number of likes in the cache, ensuring quick access. This enhances performance by reducing database queries. To display the current like count, we retrieve the value using the GetAsync method, which allows us to fetch cached data rapidly. If a user removes their like, the RemoveAsync method ensures that our cache stays updated by deleting the corresponding entry.</p><p>By implementing this caching strategy, we improve user experience and application responsiveness, making it easier to handle high volumes of interactions without overwhelming our database. Feel free to modify this overview as needed!</p><h4>3. Background Services for Asynchronous Processing</h4><p>Background services handle the processing of queued events and the eventual consistency of data. These services consume messages from the queue, update the cache, and persist data in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Skasy9qamjdtj5K_cGVmoA.png" /></figure><p><strong>Technology Choices</strong>:</p><ul><li><strong>ASP.NET Core Background Services</strong>: Built-in support for running long-running tasks in the background, making it easy to integrate with other ASP.NET Core components.</li><li><strong>Worker Services</strong>: Standalone services designed for background processing, ideal for distributed environments.</li></ul><p>These services allow us to offload intensive processing tasks from the main API, ensuring the system remains responsive under heavy load.</p><blockquote>LikeProcessingService.cs:</blockquote><pre>public class LikeProcessingService : BackgroundService<br>{<br>    private readonly IMessageQueueService _messageQueueService;<br>    private readonly IServiceProvider _serviceProvider; <br>    private readonly ILogger&lt;LikeProcessingService&gt; _logger;<br>    private const string QUEUE_NAME = &quot;likes_queue&quot;;<br><br>    public LikeProcessingService(<br>        IMessageQueueService messageQueueService,<br>        IServiceProvider serviceProvider, // Inject IServiceProvider<br>        ILogger&lt;LikeProcessingService&gt; logger)<br>    {<br>        _messageQueueService = messageQueueService;<br>        _serviceProvider = serviceProvider; // Store the provider<br>        _logger = logger;<br>    }<br><br>    protected override async Task ExecuteAsync(CancellationToken stoppingToken)<br>    {<br>        await _messageQueueService.ConsumeAsync&lt;LikeRequest&gt;(QUEUE_NAME, async request =&gt;<br>        {<br>            using (var scope = _serviceProvider.CreateScope()) // Create a scope<br>            {<br>                var userLikeService = scope.ServiceProvider.GetRequiredService&lt;IUserLikeService&gt;(); // Resolve IUserLikeService<br><br>                var like = new UserLike<br>                {<br>                    UserId = request.UserId,<br>                    ContentId = request.PostId,<br>                    CreatedAt = DateTime.UtcNow,<br>                };<br><br>                await userLikeService.AddAsync(like);<br>            }<br>        });<br><br>        await Task.Delay(Timeout.Infinite, stoppingToken);<br>    }<br>}</pre><p>Presentation layer:</p><p>Like Manager Class: Leveraging Caching and Message Queues for Efficient Handling</p><blockquote>ILikeManager.cs and LikeManager.cs:</blockquote><pre>public interface ILikeManager <br>{<br>    public Task HandleLikeAsync(LikeRequest request);<br>    public Task&lt;bool&gt; IsLikedAsync(Guid userId, Guid postId);<br>}<br><br>public class LikeManager : ILikeManager<br>{<br>    private readonly ICacheService _cacheService;<br>    private readonly IMessageQueueService _messageQueueService;<br>    private readonly ILogger&lt;LikeManager&gt; _logger;<br>    private const string QUEUE_NAME = &quot;likes_queue&quot;;<br>    private const string CACHE_KEY_FORMAT = &quot;like_{0}_{1}&quot;;<br><br>    public LikeManager(<br>    ICacheService cacheService,<br>    IMessageQueueService messageQueueService,<br>    ILogger&lt;LikeManager&gt; logger)<br>    {<br>        _cacheService = cacheService;<br>        _messageQueueService = messageQueueService;<br>        _logger = logger;<br>    }<br><br>    public async Task HandleLikeAsync(LikeRequest request)<br>    {<br>        try<br>        {<br>            // Store in cache<br>            var cacheKey = GetCacheKey(request.UserId, request.PostId);<br>            await _cacheService.SetAsync(cacheKey, true, TimeSpan.FromDays(7));<br><br>            // Publish to queue<br>            await _messageQueueService.PublishAsync(QUEUE_NAME, request);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, $&quot;Error handling like request for user {request.UserId} and post {request.PostId}&quot;,<br>                request.UserId, request.PostId);<br>            throw;<br>        }<br>    }<br><br>    public async Task&lt;bool&gt; IsLikedAsync(Guid userId, Guid postId)<br>    {<br>        try<br>        {<br>            var cacheKey = GetCacheKey(userId, postId);<br>            return await _cacheService.GetAsync&lt;bool&gt;(cacheKey);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, $&quot;Error checking like status for user {userId} and post {postId}&quot;,<br>                userId, postId);<br>            throw;<br>        }<br>    }<br><br>    private static string GetCacheKey(Guid userId, Guid postId) =&gt;<br>        string.Format(CACHE_KEY_FORMAT, userId, postId);<br>}</pre><p>Now finally implement the endpoints in LikesController.cs</p><blockquote>LikesController.cs and LikeRequest.cs :</blockquote><pre>//Create a request DTO:<br>public record LikeRequest(Guid UserId, Guid PostId);<br><br>//Controller:<br><br>[ApiController]<br>[Route(&quot;/v{version:ApiVersion}/[controller]&quot;)]<br>public class LikesController : ControllerBase<br>{<br>    private readonly ILikeManager _likeManager;<br>    private readonly ILogger&lt;LikesController&gt; _logger;<br>    public LikesController(ILikeManager likeManager, ILogger&lt;LikesController&gt; logger)<br>    {<br>        _likeManager = likeManager;<br>        _logger = logger;<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; LikePost([FromBody] LikeRequest request)<br>    {<br>        try<br>        {<br>            await _likeManager.HandleLikeAsync(request);<br>            return Ok(&quot;User liked the post&quot;);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error processing like request&quot;);<br>            return StatusCode(500, &quot;An error occurred while processing your request&quot;);<br>        }<br>    }<br><br>    [HttpGet(&quot;{userId}/{postId}&quot;)]<br>    public async Task&lt;IActionResult&gt; IsLiked(Guid userId, Guid postId)<br>    {<br>        try<br>        {<br>            var result = await _likeManager.IsLikedAsync(userId, postId);<br>            return Ok(result);<br>        }<br>        catch (Exception ex)<br>        {<br>            _logger.LogError(ex, &quot;Error checking like status&quot;);<br>            return StatusCode(500, &quot;An error occurred while processing your request&quot;);<br>        }<br>    }<br>}</pre><p>Make sure to Configure 🛠 all services ⚙️in StartUp.cs or Program.cs</p><blockquote>StartUp.cs or Program.cs:</blockquote><pre>public virtual void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddMvc();<br><br>    services.AddControllers();<br>    services.AddEndpointsApiExplorer();<br>    services.AddOpenApi();<br>    services.AddCors();<br><br>    ConfigureSqlServerContext(services);<br><br>    services.AddHttpClient();<br><br>    services.Configure&lt;RabbitMQSettings&gt;(Configuration.GetSection(&quot;RabbitMQSettings&quot;));<br><br>    // Register Redis Cache<br>     services.AddStackExchangeRedisCache(options =&gt;<br>    {<br>        options.Configuration = Configuration.GetValue&lt;string&gt;(&quot;Redis:ConnectionString&quot;) ?? &quot;localhost:6379&quot;;<br>    });<br><br>    // Register RabbitMQ services<br>    services.AddSingleton&lt;IConnectionFactory&gt;(sp =&gt;<br>    {<br>        var rabbitConfig = Configuration.GetSection(&quot;RabbitMQSettings&quot;).Get&lt;RabbitMQSettings&gt;();<br><br>        return new ConnectionFactory<br>        {<br>            HostName = rabbitConfig?.Host ?? &quot;localhost&quot;,<br>            UserName = rabbitConfig?.UserName ?? &quot;guest&quot;,<br>            Password = rabbitConfig?.Password ?? &quot;guest&quot;,<br>            VirtualHost = rabbitConfig?.VirtualHost ?? &quot;/&quot;,<br>            Port = rabbitConfig?.Port ?? 5672,<br>            RequestedHeartbeat = TimeSpan.FromSeconds(60),<br>            AutomaticRecoveryEnabled = true<br>        };<br>    });<br><br>    // Register message queue service<br>    services.AddSingleton&lt;IMessageQueueService, RabbitMQService&gt;();<br><br>    // Register cache service<br>    services.AddScoped&lt;ICacheService, RedisCacheService&gt;();<br><br>    // Register LikeManager<br>    services.AddScoped&lt;ILikeManager, LikeManager&gt;();<br><br>    // Add background service for processing likes<br>    services.AddHostedService&lt;LikeProcessingService&gt;();<br><br>    AddServices(services);<br>    AddVersioning(services);<br>}</pre><p><strong>What’s Next?</strong></p><p>Stay tuned for my next article, where I’ll dive into <strong>unit and integration testing</strong> for our like/dislike system. I’ll demonstrate how to test real-time like handling in a RabbitMQ-based application hosted locally. This will include setting up test environments, validating event flows, and ensuring the system works flawlessly under various scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBprbfVIznCaYwasYKVxbw.png" /></figure><blockquote>Make sure to follow me on my social platforms so you don’t miss out! 🚀</blockquote><p>I hope this article provided you with a clear understanding of how to design and implement a scalable like/dislike system using event-driven architecture in ASP.NET Core. By leveraging technologies like message queues, caching, and background services, you can build a system capable of handling massive traffic while maintaining high performance and reliability.</p><p>If you found this content helpful or enjoyed reading it, please consider following me for more articles on system design, scalable architectures, and ASP.NET Core development. Your support means a lot and helps me create more valuable content!</p><ul><li><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/pavan-kumar-169019214/">Pavan Kumar</a></li><li><strong>GitHub</strong>: <a href="https://github.com/Pavan8374">Pavan8374</a></li><li><strong>Website</strong>: <a href="https://pavan-rambhukta.vercel.app/">Pavan Rambhukta</a></li><li><strong>Reddit</strong>: <a href="https://www.reddit.com/user/Backend_biryani/">u/rpavank</a></li></ul><p>For more details and the complete codebase discussed in this article, feel free to explore the project on GitHub:<br><strong>Project Link</strong>: <a href="https://github.com/Pavan8374/mq-cache-example">MQ-Cache-Example</a></p><p>Thank you for reading, and I look forward to connecting with you! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f549c4003dca" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/beyond-the-like-button-architecting-a-high-performance-engagement-system-f549c4003dca">Beyond the Like Button: Architecting a High-Performance Engagement System</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Best Practices for ASP.NET Core Development]]></title>
            <link>https://medium.com/@rpavank2000/essential-best-practices-for-asp-net-core-development-9968e07156fc?source=rss-134f05189d1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9968e07156fc</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pavan Kumar]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 06:43:21 GMT</pubDate>
            <atom:updated>2024-06-12T06:48:35.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vMMnQjJGCG66gf5yZ27Qg.png" /></figure><p>ASP.NET Core is Microsoft’s modern, cross-platform framework for building web applications. To take full advantage of its capabilities and create high-quality, maintainable web apps, it’s essential to follow industry best practices. Here are some key best practices to embrace, with examples:</p><p><strong>1.Embrace Dependency Injection:</strong> Dependency Injection (DI) decouples components from their dependencies, making the code more modular and testable. ASP.NET Core has built-in support for DI through its integrated inversion of control (IoC) container.</p><p>Example: Injecting an ILogger instance into a controller:</p><pre>public class HomeController : Controller<br>{<br>    private readonly ILogger&lt;HomeController&gt; _logger;<br><br>    public HomeController(ILogger&lt;HomeController&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br>    <br>    // ...<br>} </pre><p><strong>2.Implement Proper Exception Handling</strong>: ASP.NET Core includes exception handling middleware that can catch unhandled exceptions and generate detailed error pages or logs.</p><p>Example: Configuring the exception handler in Startup.cs:</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br> if (env.IsDevelopment())<br> {<br> app.UseDeveloperExceptionPage();<br> }<br> else<br> {<br> app.UseExceptionHandler(&quot;/Error&quot;);<br> app.UseHsts();<br> }<br> <br> // …<br>}</pre><p><strong>3.Adhere to SOLID Principles:</strong> The SOLID principles promote maintainable, extensible software. For example, the Single Responsibility Principle states that each class should have only one reason to change, improving code organization.</p><p>Example: Separating concerns in a User service:</p><pre>public class UserService<br>{<br>    private readonly IUserRepository _repository;<br>    private readonly IEmailService _emailService;<br><br>    public UserService(IUserRepository repository, IEmailService emailService)<br>    {<br>        _repository = repository;<br>        _emailService = emailService;<br>    }<br><br>    public void RegisterUser(User user)<br>    {<br>        _repository.AddUser(user);<br>        _emailService.SendWelcomeEmail(user.Email);<br>    }<br>}</pre><p><strong>4.Leverage Asynchronous Programming:</strong> Asynchronous code uses fewer system resources by allowing the server to work on other requests while waiting for time-consuming operations.</p><p>Example: Async controller action:</p><pre>public class ProductsController : Controller<br>{<br>    private readonly IProductRepository _repository;<br><br>    public ProductsController(IProductRepository repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    public async Task&lt;IActionResult&gt; GetProducts()<br>    {<br>        var products = await _repository.GetProductsAsync();<br>        return View(products);<br>    }<br>}</pre><p><strong>5.Implement Proper Caching Strategies:</strong> ASP.NET Core provides flexible caching options like in-memory caching and integrations with distributed caching solutions.</p><p>Example: Caching a data result:</p><pre>public class ProductService<br>{<br>    private readonly IDistributedCache _cache;<br>    private readonly IProductRepository _repository;<br><br>    public ProductService(IDistributedCache cache, IProductRepository repository)<br>    {<br>        _cache = cache;<br>        _repository = repository;<br>    }<br><br>    public async Task&lt;IEnumerable&lt;Product&gt;&gt; GetProductsAsync()<br>    {<br>        var cacheKey = &quot;productsList&quot;;<br>        string serializedProducts;<br>        var products = new List&lt;Product&gt;();<br><br>        serializedProducts = await _cache.GetStringAsync(cacheKey);<br>        if (serializedProducts != null)<br>        {<br>            products = JsonSerializer.Deserialize&lt;List&lt;Product&gt;&gt;(serializedProducts);<br>        }<br>        else<br>        {<br>            products = await _repository.GetProductsAsync();<br>            <br>            serializedProducts = JsonSerializer.Serialize(products);<br>            await _cache.SetStringAsync(cacheKey, serializedProducts,<br>                new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(5)));<br>        }<br><br>        return products;<br>    }<br>}</pre><p><strong>6.Adopt a Consistent Naming Convention:</strong></p><p>Example: Standard ASP.NET Core naming conventions:</p><ul><li>PascalCase for public class names (e.g. HomeController)</li><li>camelCase for private/protected fields (e.g. _logger)</li><li>camelCase for method names (e.g. configureServices)</li></ul><p><strong>7.Leverage Configuration Management:</strong> ASP.NET Core supports configuration from multiple sources like JSON files and environment variables.</p><p>Example: Retrieving a database connection string from configuration:</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>        options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));<br>    <br>    // ...<br>}</pre><p><strong>8.Implement Proper Security Measures:</strong> ASP.NET Core includes security features like authentication, authorization, anti-forgery protection, and data protection APIs.</p><p>Example: Requiring authentication for an admin area:</p><pre>app.UseEndpoints(endpoints =&gt;<br>{<br>    endpoints.MapControllerRoute(<br>        name: &quot;areas&quot;,<br>        pattern: &quot;{area:exists}/{controller=Home}/{action=Index}/{id?}&quot;);<br>    endpoints.MapControllerRoute(<br>        name: &quot;default&quot;,<br>        pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);<br>});<br><br>// Require authentication for the admin area<br>app.UseEndpoints(endpoints =&gt;<br>{<br>    endpoints.MapControllerRoute(<br>        name: &quot;admin&quot;,<br>        pattern: &quot;{area:exists}/Admin/{controller=Home}/{action=Index}/{id?}&quot;,<br>        defaults: new { area = &quot;Admin&quot; });<br>});</pre><p><strong>9.Embrace Automated Testing:</strong> ASP.NET Core integrates with testing frameworks like xUnit for writing unit, integration, and UI tests.</p><p>Example unit test:</p><pre>public class ProductServiceTests<br>{<br>    [Fact]<br>    public async Task GetProductsAsync_WhenCalled_ReturnsAllProducts()<br>    {<br>        // Arrange<br>        var products = GetTestProducts();<br>        var productRepoMock = GetMock(products);<br>        var sut = new ProductService(productRepoMock.Object);<br><br>        // Act<br>        var result = await sut.GetProductsAsync();<br><br>        // Assert<br>        result.Should().BeEquivalentTo(products);<br>    }<br><br>    // ...<br>}</pre><p><strong>10.Leverage Code Analysis Tools:</strong> ASP.NET Core works with code analyzers like StyleCop, FxCop, and platforms like SonarQube that enforce rules and analyze code quality.</p><p>Example StyleCop rule in an .editorconfig file:</p><pre># CSharp code style settings:<br>[*.cs]<br># Prefer &quot;this.&quot; qualifiers<br>dotnet_style_qualification_for_field = true:suggestion<br>dotnet_style_qualification_for_property = true:suggestion</pre><p>By embracing these best practices with code examples, you can develop ASP.NET Core web applications that are secure, performant, maintainable, and aligned with modern software engineering principles. As ASP.NET Core continues evolving, it’s also wise to stay current with new features and updates to development best practices.</p><p>Connect with me:</p><p>LinkedIn: <a href="https://www.linkedin.com/in/pavan-kumar-169019214/">https://www.linkedin.com/in/pavan-kumar-169019214/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9968e07156fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>