<?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 Hoang Phan on Medium]]></title>
        <description><![CDATA[Stories by Hoang Phan on Medium]]></description>
        <link>https://medium.com/@imstevenphan?source=rss-46c9ee410551------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DCFTqPxAkXdS7tbLbdhOIg@2x.jpeg</url>
            <title>Stories by Hoang Phan on Medium</title>
            <link>https://medium.com/@imstevenphan?source=rss-46c9ee410551------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:22:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imstevenphan/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[Simplifying Secrets Management: Programmatically Accessing Azure Key Vault]]></title>
            <link>https://medium.com/@imstevenphan/simplifying-secrets-management-programmatically-accessing-azure-key-vault-97ffcebed74d?source=rss-46c9ee410551------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ffcebed74d</guid>
            <category><![CDATA[azure-key-vault]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Hoang Phan]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 04:53:29 GMT</pubDate>
            <atom:updated>2023-09-21T06:01:06.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x2ODYvnAML4oOLo2.png" /></figure><p><em>If you found this article helpful or enjoyed reading it, consider supporting my work by buying me a coffee! Your support allows me to continue creating valuable content like this : ❤ ❤ ❤</em></p><figure><a href="https://www.buymeacoffee.com/steven.phan1996"><img alt="" src="https://cdn-images-1.medium.com/max/210/1*h-VEYlhRCtVm5zW_kcYYpA.png" /></a></figure><blockquote>In today’s technology landscape, data security is non-negotiable. Azure KeyVault, a versatile and secure secrets management service by Microsoft Azure, empowers developers to store and retrieve sensitive information like API keys, passwords, and certificates with confidence. While tools like Visual Studio offer a seamless way to access Key Vault during development, this article explores how to programmatically connect to Azure Key Vault, ensuring your secrets are safe, regardless of your development environment.</blockquote><h3>The Azure Setup</h3><p>Before we dive into the code, let’s set the stage with the necessary Azure resources:</p><h4>1. Service Principal</h4><p>We’ll start by creating a Service Principal in Azure. Think of it as a special identity that your applications use to interact securely with Azure resources:</p><ul><li>Open <strong>Microsoft Entra ID</strong> in the Azure Portal.</li><li>Navigate to “App Registrations” and create a new registration. Name it something like <strong>azure_key_vault_sample </strong>and register it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xeaBP5-AQrMY7Rl4aJBzVQ.png" /></figure><h4>2. Service Principal’s Secret</h4><p>Now, let’s equip our Service Principal with a secret:</p><ul><li>In the overview of your <strong>Microsoft Entra ID </strong>registration, go to “<strong>Certificates &amp; secrets.</strong>”</li><li>Create a new client secret and give it a name, like <strong>local_secret</strong>.</li><li>Keep this secret safe; you’ll need it shortly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOkZ14S4iXoeJ_VjnjDR1g.png" /></figure><h4>3. Azure KeyVault Instance</h4><p>Create a new Azure Key Vault instance:</p><ul><li>Start by entering the initial details under “Basics.”</li><li>Proceed to the “Access Policies” section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpW6RYKI5Gx_xko3LuBnGQ.png" /></figure><ul><li>Here, grant your Service Principal the necessary permissions by adding an access policy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ncKpHGM6uyFJwOJqZoVsQ.png" /></figure><h4>4. Adding a Secret to Key Vault</h4><p>To demonstrate retrieving a secret programmatically, let’s add one to your Key Vault. Create a secret named first-secret with the value hello-world.</p><h3>Gathering the Required Information</h3><p>To write code that can authenticate with your Azure Key Vault programmatically, you’ll need three essential pieces of information:</p><ul><li><strong>Tenant Id</strong>: This uniquely identifies your <strong>Microsoft Entra ID</strong>.</li><li><strong>Client Id </strong>(Application Id): This represents your Service Principal.</li><li><strong>Client Secret</strong>: The secret we created for the Service Principal.</li></ul><p>Retrieve the Tenant Id and Client Id from the <strong>Microsoft Entra ID</strong> registration overview.</p><h3>The Code</h3><p>Now, let’s put it all together with some code that connects to Azure Key Vault programmatically:</p><pre>using Azure.Identity;<br>using Azure.Security.KeyVault.Secrets;<br>using System;<br><br>class Program<br>{<br>   static async Task Main(string[] args)<br>   {<br>       string keyVaultUrl = &quot;https://your-keyvault-name.vault.azure.net/&quot;;<br>       string tenantId = &quot;your_tentant_id&quot;;<br>       string clientId = &quot;your_client_id&quot;;<br>       string clientSecret = &quot;your_client_secret&quot;;<br><br>       // Create an instance of the SecretClient to interact with the Azure Key Vault.<br>       var client = new SecretClient(new Uri(keyVaultUrl), new ClientSecretCredential(tenantId, clientId, clientSecret));<br>       var secretName = &quot;first-secret&quot;;<br>       var secretValue = await client.GetSecretAsync(secretName);<br>       Console.WriteLine($&quot;Secret value: {secretValue.Value.Value}&quot;);<br>   }<br>}</pre><p><em>In conclusion, programmatically connecting to Azure KeyVault offers flexibility and security, enabling developers to build applications that securely manage secrets. By following best practices and implementing strong security measures, you can harness the full power of Azure KeyVault while safeguarding your organization’s sensitive data.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ffcebed74d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Path to Becoming a Senior Developer: Skills, Attitudes, and Strategies]]></title>
            <link>https://medium.com/@imstevenphan/the-path-to-becoming-a-senior-developer-skills-attitudes-and-strategies-54faa2ddf8e8?source=rss-46c9ee410551------2</link>
            <guid isPermaLink="false">https://medium.com/p/54faa2ddf8e8</guid>
            <category><![CDATA[senior-developer]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Hoang Phan]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 09:40:41 GMT</pubDate>
            <atom:updated>2023-09-19T09:40:41.222Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Becoming a senior developer is a significant milestone in your career as a software engineer. It’s a recognition of your experience, expertise, and leadership abilities. However, reaching this level requires more than just technical proficiency. In this article, we’ll explore the essential skills, attitudes, and strategies to help you on your journey to becoming a senior developer.</blockquote><h3>1. Master Your Technical Skills</h3><p>At the core of every senior developer’s journey is a deep and broad technical skill set. Here’s how you can master your technical skills:</p><h4>a. Continuous Learning</h4><p>Technology evolves rapidly, and senior developers must stay up-to-date with the latest trends and tools. Invest time in continuous learning through online courses, books, blogs, and attending conferences or meetups.</p><h4>b. Depth and Breadth</h4><p>While it’s crucial to have expertise in specific areas (e.g., a programming language or framework), senior developers often have a broader understanding of various technologies. This allows them to choose the right tool for the job.</p><h4>c. Problem Solving</h4><p>Practice problem-solving skills by working on challenging projects or coding challenges. This will help you develop a problem-solving mindset, which is a hallmark of senior developers.</p><h3>2. Embrace Best Practices</h3><p>Senior developers are known for their commitment to best practices in software development. This includes:</p><h4>a. Clean Code</h4><p>Write clean, readable, and maintainable code. Follow coding conventions, use meaningful variable names, and avoid shortcuts that sacrifice code quality.</p><h4>b. Design Patterns</h4><p>Familiarize yourself with common design patterns and apply them appropriately to solve recurring problems.</p><h4>c. Code Reviews</h4><p>Participate in code reviews, whether as a reviewer or reviewee. Constructive feedback and learning from others are invaluable.</p><h3>3. Improve Your Soft Skills</h3><p>Technical skills alone won’t make you a senior developer. Soft skills are equally important:</p><h4>a. Communication</h4><p>Effective communication is vital for collaborating with team members, stakeholders, and clients. Practice clear and concise communication in both written and verbal forms.</p><h4>b. Leadership</h4><p>Senior developers often take on leadership roles within their teams. Develop leadership skills such as mentoring junior developers, leading discussions, and making technical decisions.</p><h4>c. Time Management</h4><p>Master time management to prioritize tasks, meet deadlines, and ensure that your work aligns with project goals.</p><h3>4. Learn from Experience</h3><p>Experience is one of the most significant factors in becoming a senior developer. Here’s how to maximize your learning from experience:</p><h4>a. Work on Diverse Projects</h4><p>Seek opportunities to work on a variety of projects. This exposes you to different technologies, challenges, and perspectives.</p><h4>b. Handle Complexity</h4><p>Embrace complex tasks and projects. The ability to tackle intricate problems and find elegant solutions is a hallmark of senior developers.</p><h4>c. Learn from Mistakes</h4><p>Mistakes happen, even to senior developers. What sets them apart is their ability to learn from their mistakes and avoid repeating them.</p><h3>5. Collaborate Effectively</h3><p>Being a senior developer isn’t just about individual accomplishments; it’s also about teamwork:</p><h4>a. Teamwork</h4><p>Foster a collaborative and inclusive work environment. Share knowledge, support team members, and contribute to a positive team culture.</p><h4>b. Domain Knowledge</h4><p>Understand the domain you’re working in, whether it’s finance, healthcare, e-commerce, or any other field. Domain knowledge helps you make informed technical decisions.</p><h4>c. Customer Focus</h4><p>Keep the end-users in mind. Understanding the user’s needs and pain points is crucial for creating valuable software.</p><h3>6. Stay Humble and Open-Minded</h3><p>Despite your growing expertise, humility and open-mindedness are essential qualities for a senior developer:</p><h4>a. Seek Feedback</h4><p>Be open to feedback from colleagues, superiors, and subordinates. Constructive criticism can help you grow.</p><h4>b. Learn from Others</h4><p>Acknowledge that there’s always more to learn, and others may have insights and approaches you haven’t considered.</p><h3>7. Mentor and Give Back</h3><p>As you progress in your career, consider mentoring junior developers. Sharing your knowledge and experience not only benefits others but also reinforces your own understanding of the subject matter.</p><h3>8. Be Adaptable</h3><p>The tech industry is constantly changing. Being adaptable and open to new technologies and methodologies will help you stay relevant throughout your career.</p><h3>9. Networking</h3><p>Build a professional network by attending conferences, joining online communities, and connecting with fellow developers. Networking can lead to valuable opportunities and collaborations.</p><h3>10. Set Goals</h3><p>Set clear, achievable goals for your career. Whether it’s becoming a technical lead, architect, or pursuing a specific technology stack, having goals will give you direction and motivation.</p><h3>Conclusion</h3><p><em>Becoming a senior developer is a journey that requires continuous learning, technical excellence, strong soft skills, and a growth mindset. It’s about more than just coding; it’s about being a leader, a mentor, and a collaborator. Embrace the challenge, stay humble, and keep pushing yourself to reach new heights in your career. Remember that there’s always more to learn and accomplish, and the path to seniority is an ongoing adventure filled with opportunities for growth and impact.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54faa2ddf8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting LINQ to Entities Performance with Compiled Queries]]></title>
            <link>https://medium.com/@imstevenphan/boosting-linq-to-entities-performance-with-compiled-queries-3bf0d6fae493?source=rss-46c9ee410551------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf0d6fae493</guid>
            <category><![CDATA[ef-core-performance]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[linq]]></category>
            <dc:creator><![CDATA[Hoang Phan]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 08:36:12 GMT</pubDate>
            <atom:updated>2023-09-19T08:42:45.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*csaa0Zoh-VLXfJP2fBsYQw.png" /></figure><blockquote>When it comes to optimizing database queries in .NET applications, Compiled Queries in LINQ to Entities are a powerful tool that can significantly improve performance. In this guide, we will explore Compiled Queries, understand how they work, and provide code samples to demonstrate their usage.What Are Compiled Queries?</blockquote><h3>What Are Compiled Queries?</h3><p>Compiled Queries in LINQ to Entities are precompiled query expressions that are cached for reuse. Unlike regular LINQ queries, which are compiled every time they are executed, Compiled Queries are compiled only once. This compilation process generates an optimized execution plan, including SQL statements and parameter values, which is then cached. This caching eliminates the overhead of query compilation for subsequent executions, resulting in faster and more efficient queries.</p><h3>Creating and Using Compiled Queries</h3><p>Let’s dive into the practical aspects of working with Compiled Queries.</p><h4>Defining a Compiled Query</h4><p>To define a Compiled Query, you encapsulate your query logic within a Func delegate. Here&#39;s a simple example:</p><pre>// Define a Compiled Query to retrieve customers by city.<br>public static readonly Func&lt;MyDbContext, string, IQueryable&lt;Customer&gt;&gt; CustomersByCity =<br>    CompiledQuery.Compile((MyDbContext context, string city) =&gt;<br>        from c in context.Customers<br>        where c.City == city<br>        select c);</pre><h4>Using a Compiled Query</h4><p>Using a Compiled Query is straightforward:</p><pre><br>using (var context = new MyDbContext())<br>{<br>    string targetCity = &quot;New York&quot;;<br><br>    // Use the Compiled Query to retrieve customers by city.<br>    var customersInCity = CompiledQueries.CustomersByCity(context, targetCity);<br><br>    foreach (var customer in customersInCity)<br>    {<br>        Console.WriteLine($&quot;Customer Name: {customer.CustomerName}, City: {customer.City}&quot;);<br>    }<br>}</pre><h4>Parameterization and Reusability</h4><p>Compiled Queries naturally support parameterization, allowing you to reuse them with different parameter values:</p><pre>using (var context = new MyDbContext())<br>{<br>    string city1 = &quot;Seattle&quot;;<br>    string city2 = &quot;San Francisco&quot;;<br><br>    var customersInCity1 = CompiledQueries.CustomersByCity(context, city1);<br>    var customersInCity2 = CompiledQueries.CustomersByCity(context, city2);<br><br>    // Use the results as needed.<br>}</pre><h3>Performance Benefits</h3><p>Compiled Queries offer several performance benefits:</p><ul><li><strong>Reduced Compilation Overhead</strong>: Eliminates the need to compile the query for every execution, reducing overhead.</li><li><strong>Improved Execution Plans</strong>: Provides the Entity Framework more time to optimize SQL queries, resulting in better performance.</li><li><strong>Parameterization</strong>: Supports dynamic queries by allowing parameterized inputs.</li><li><strong>Type Safety</strong>: Maintains strong typing for query results.</li><li><strong>Caching</strong>: Caches execution plans, ensuring consistent and efficient query performance.</li></ul><h3>Best Practices</h3><p>To make the most of Compiled Queries, follow these best practices:</p><ul><li>Use them for frequently executed queries.</li><li>Keep queries simple; avoid overcomplicating them.</li><li>Beware of parameter sniffing and consider separate queries or query hints.</li><li>Ensure thread safety when sharing Compiled Queries.</li><li>Monitor and manage cached queries to optimize memory usage.</li><li>Measure and profile the impact of Compiled Queries in your application.</li></ul><p>In conclusion, Compiled Queries in LINQ to Entities are a valuable tool for improving database query performance in .NET applications. By precompiling, parameterizing, and caching queries, you can achieve significant speed improvements and deliver efficient and scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf0d6fae493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka: A Foundation for Real-time Data Streams — Part 1]]></title>
            <link>https://medium.com/@imstevenphan/apache-kafka-a-foundation-for-real-time-data-streams-part-1-d095f2f3e8fd?source=rss-46c9ee410551------2</link>
            <guid isPermaLink="false">https://medium.com/p/d095f2f3e8fd</guid>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Hoang Phan]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 10:51:31 GMT</pubDate>
            <atom:updated>2023-09-05T10:59:42.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Kafka: A Foundation for Real-time Data Streams — Part 1</h3><p><em>If you found this article helpful or enjoyed reading it, consider supporting my work by buying me a coffee! Your support allows me to continue creating valuable content like this :</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*vZEy-xohSg2RSKF4.png" /></figure><blockquote>In today’s data-driven world, efficiently managing and processing real-time data streams is paramount. Apache Kafka emerges as a formidable solution, often referred to as a “distributed commit log” or a “distributing streaming platform.” In this article, we’ll explore the key concepts and functionalities that make Kafka an indispensable tool for handling data at scale.</blockquote><h3>Why Choose Apache Kafka for Your Messaging Needs</h3><p>Apache Kafka is a standout choice in the world of publish/subscribe messaging systems for several compelling reasons:</p><ol><li><strong>Streamlined Data Aggregation</strong>: Kafka effortlessly handles multiple producers, simplifying the aggregation of data from various sources. This is particularly advantageous for consolidating data from diverse frontend systems into a single, consistent stream.</li><li><strong>Concurrent Processing:</strong> Unlike some queuing systems, Kafka allows multiple consumers to read from the same message stream concurrently. It’s designed to ensure efficient resource utilization without message locking.</li><li><strong>Disk-Based Retention:</strong> Kafka combines real-time processing with durable message retention. Messages are committed to disk with flexible retention rules, catering to specific consumer needs. Even if consumers fall behind, there’s no data loss, and maintenance can be performed without concern.</li><li><strong>Scalability: </strong>Kafka’s architecture grows seamlessly with data demands. You can start small and expand to large-scale clusters while maintaining uninterrupted service availability. Kafka’s multi-broker clusters provide resilience to individual broker failures.</li><li><strong>High-Performance: </strong>Kafka excels in high-load scenarios, offering subsecond message latency. Whether it’s real-time analytics, monitoring systems, or event-driven applications, Kafka delivers exceptional performance.</li></ol><h3>Messages and Batches: The Core of Kafka</h3><p>At the heart of Kafka lies the concept of <strong>messages</strong>. Think of them as the building blocks of data. These messages are byte arrays, providing a flexible canvas for your information. Each message can optionally be associated with a key, also a byte array. Keys come into play when you need to exert control over how messages are distributed among partitions.</p><p>To optimize data transmission, Kafka employs batches. Instead of sending individual messages, Kafka bundles them into batches. This batching approach strikes a balance between latency and throughput. Larger batches allow for efficient handling of a high volume of messages, albeit with slightly increased propagation time.</p><h3>Schemas: Structuring Data for Clarity</h3><p>While Kafka treats messages as byte arrays, structured data interpretation is often essential. This is where schemas come into play. Schemas provide a blueprint for understanding message contents. Various schema options are available, but Apache Avro stands out as a preferred choice.</p><ul><li><strong>JSON and XML</strong>: These formats are simple and human-readable but lack robust type handling and schema evolution capabilities.</li><li><strong>Apache Avro</strong>: Avro offers a compact serialization format with separate schema management. It boasts strong data typing and supports both backward and forward compatibility. Well-defined schemas enable Kafka messages to be comprehensible without tight coordination.</li></ul><h3>Topics and Partitions: Organizing Data Streams</h3><p>Kafka categorizes data into <strong>topics</strong>, akin to database tables or filesystem folders. These topics are further divided into <strong>partitions</strong>, each acting as an independent log. Messages are appended to partitions in a strictly sequential order and are read in the same sequence. However, it’s important to note that time-ordering is guaranteed only within a single partition.</p><p>Partitions are the cornerstone of Kafka’s scalability and fault tolerance. They allow a single topic to be horizontally scaled across multiple servers, ensuring performance that surpasses what a single server can offer.</p><h3>Producers and Consumers: Data Flow in Action</h3><p>In the Kafka ecosystem, <strong>producers </strong>and <strong>consumers </strong>play pivotal roles. Producers are responsible for crafting and sending messages to specific topics. Kafka’s default behavior evenly distributes messages across all topic partitions, but producers can exert control over message partitioning using keys and custom partitioners.</p><p>Consumers, on the other hand, subscribe to topics and read messages in the order they were produced. To maintain their reading position and avoid data loss, consumers rely on <strong>offsets</strong>, unique integer values associated with each message. Kafka enhances this with <strong>consumer groups,</strong> where multiple consumers collaborate to efficiently process a topic. This design ensures that each partition is handled by only one consumer at a time.</p><h3>Brokers and Cluster Management: Keeping Kafka Running</h3><p>In Kafka’s architecture, a <strong>broker </strong>is a server responsible for receiving messages from producers, assigning offsets, and persisting messages on disk. Brokers are organized into <strong>clusters</strong>, with one broker serving as the <strong>cluster controller</strong> for administrative tasks. The controller oversees partition assignment to brokers and monitors for broker failures.</p><h3>Data Durability with Retention</h3><p>Kafka introduces a vital feature known as <strong>retention</strong>, ensuring messages are durably stored for a specified duration or until a size threshold is reached. This prevents Kafka from becoming an infinite data repository, promoting efficient resource management.</p><p>Each topic can have its own retention settings, enabling tailored data management. For instance, tracking data might be retained for several days, while application metrics may be kept for only a few hours. Kafka also supports <strong>log compaction</strong>, retaining only the latest message produced with a specific key. This feature is invaluable for scenarios where only the most recent update is relevant.</p><h3>Multiple Clusters: Versatility and Redundancy</h3><p>As Kafka deployments expand, organizations often find it advantageous to deploy <strong>multiple Kafka clusters</strong>. These clusters serve diverse purposes:</p><ul><li><strong>Segregation of Data Types</strong>: Different clusters can isolate different types of data.</li><li><strong>Security Isolation</strong>: Clusters can be isolated to meet specific security requirements.</li><li><strong>Disaster Recovery</strong>: When dealing with multiple data centers, replicating messages between clusters becomes essential for business continuity.</li></ul><p>To facilitate message replication between clusters, Kafka provides a tool called <strong>MirrorMaker</strong>. MirrorMaker acts as a Kafka consumer and producer, bridging data between clusters. This functionality is especially crucial when online applications need access to user activity data across different sites or data centers.</p><blockquote>In conclusion, Apache Kafka forms the foundation for building real-time data pipelines, stream processing, and data integration solutions. Its ability to efficiently handle data streams, scale seamlessly, and create robust data ecosystems makes it an indispensable component in the modern data-driven landscape. Whether you’re dealing with real-time analytics, monitoring, or building event-driven applications, Kafka empowers you to harness the full potential of your data streams.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d095f2f3e8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using IHttpClientFactory in ASP.NET Core: Optimizing HTTP Requests for Performance and Scalability]]></title>
            <link>https://medium.com/@imstevenphan/leveraging-ihttpclientfactory-in-asp-net-e1970b9719f5?source=rss-46c9ee410551------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1970b9719f5</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Hoang Phan]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 03:38:04 GMT</pubDate>
            <atom:updated>2023-09-05T04:11:03.832Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you found this article helpful or enjoyed reading it, consider supporting my work by buying me a coffee! Your support allows me to continue creating valuable content like this :</em></p><figure><a href="https://www.buymeacoffee.com/steven.phan1996"><img alt="" src="https://cdn-images-1.medium.com/max/210/1*h-VEYlhRCtVm5zW_kcYYpA.png" /></a></figure><blockquote>In the modern landscape of web development, applications are often required to interact with various external services, APIs, and resources over the internet. Whether it’s fetching data from a remote server, sending requests to third-party APIs, or communicating with microservices within your own architecture, the need for making HTTP requests is ubiquitous. However, handling HTTP requests efficiently and effectively is crucial for the overall performance, scalability, and maintainability of your application.</blockquote><p>The <strong>HttpClient</strong> class has been a staple in .NET for making HTTP requests, but as applications grow in complexity, so do the challenges associated with its usage. This is where <strong>HttpClientFactory </strong>comes into play, offering a sophisticated solution to address these challenges while providing a streamlined approach to managing HTTP clients. In this article, we will delve deep into the reasons why we need to use <strong>HttpClientFactory </strong>in ASP.NET Core, exploring its benefits and best practices.</p><p>Challenges with Direct <strong>HttpClient </strong>Usage</p><p>Before we explore the merits of <strong>HttpClientFactory </strong>, let&#39;s take a moment to understand the challenges that can arise when using <strong>HttpClient </strong>directly.</p><ol><li>Resource Exhaustion: When <strong>HttpClient </strong>instances are created and disposed of individually, it can lead to resource exhaustion due to socket exhaustion. This is particularly problematic when dealing with a large number of requests in a short period of time.</li><li>Connection Reuse and DNS Caching: Reusing connections across multiple requests is crucial for performance. With direct <strong>HttpClient </strong>usage, managing connection reuse and DNS caching becomes complex and error-prone.</li><li>Timeouts and Circuit Breaking: Applying consistent timeout values and implementing circuit-breaking patterns for fault tolerance require manual intervention, making the codebase harder to maintain.</li><li>Logging and Instrumentation: Incorporating proper logging and instrumentation for monitoring request and response details can become cumbersome when dealing with multiple <strong>HttpClient </strong>instances.</li></ol><h3><strong>Introducing HttpClientFactory</strong></h3><p><strong>HttpClientFactory </strong>is a feature introduced in ASP.NET Core to address the challenges associated with direct <strong>HttpClient </strong>usage. It serves as a centralized mechanism for creating and managing instances of <strong>HttpClient</strong>, promoting best practices and enhancing performance and maintainability.</p><p>Benefits of Using <strong>HttpClientFactory</strong></p><ol><li>Resource Management: One of the core benefits of <strong>HttpClientFactory </strong>is its efficient management of <strong>HttpClient </strong>instances. By using a pool of reusable <strong>HttpClient </strong>instances, it mitigates the issues of resource exhaustion and socket leaks that can occur with direct instantiation.</li><li>Connection Pooling: <strong>HttpClientFactory </strong>manages connection pooling automatically, reusing connections across multiple requests. This leads to reduced overhead and improved performance, especially in scenarios where a high volume of requests is anticipated.</li><li>Lifetime Management: With <strong>HttpClientFactory</strong>, you can define the lifetime of <strong>HttpClient </strong>instances. Scoped lifetime, for example, ensures that an instance is reused within a single HTTP request, while singleton lifetime allows sharing an instance across the entire application. This flexibility ensures optimal memory usage and connection reuse.</li><li>Configuration and Policies: <strong>HttpClientFactory </strong>provides a convenient way to configure and apply policies to <strong>HttpClient </strong>instances. This includes setting timeout values, defining retry behaviors, and implementing circuit-breaking patterns. This abstraction simplifies the codebase and centralizes the configuration logic.</li><li>Logging and Instrumentation: Incorporating logging and instrumentation becomes seamless with <strong>HttpClientFactory</strong>. You can apply message logging and capture detailed request and response information without cluttering your business logic.</li><li>Testing and Mocking: <strong>HttpClientFactory </strong>enhances testability by allowing you to inject mock or custom implementations of <strong>HttpClient </strong>. This makes unit testing more straightforward and decouples your code from the actual HTTP requests during testing.</li></ol><h3><strong>Code sample</strong></h3><p>Here’s a sample code that demonstrates how to use <strong>HttpClientFactory </strong>in an ASP.NET Core application. This example will show you how to create a service that makes HTTP requests using <strong>HttpClientFactory</strong>.</p><p>Let’s assume you have an ASP.NET Core application set up and you want to create a service that interacts with an external API.</p><ol><li>Register <strong>HttpClientFactory</strong> in <strong>Startup.cs:</strong></li></ol><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    // Other service registrations<br>    <br>    services.AddHttpClient();<br>    <br>    // Register your custom services<br>    services.AddScoped&lt;IMyApiService, MyApiService&gt;();<br>}</pre><p>2. Create a Service Interface:</p><pre>public interface IMyApiService<br>{<br>    Task&lt;string&gt; GetApiResponseAsync();<br>}</pre><p>3. Implement the Service Using <strong>HttpClientFactory</strong>:</p><pre>public class MyApiService : IMyApiService<br>{<br>    private readonly IHttpClientFactory _httpClientFactory;<br><br>    public MyApiService(IHttpClientFactory httpClientFactory)<br>    {<br>        _httpClientFactory = httpClientFactory;<br>    }<br><br>    public async Task&lt;string&gt; GetApiResponseAsync()<br>    {<br>        // Create a named client or use the default client<br>        HttpClient client = _httpClientFactory.CreateClient();<br><br>        // Make an HTTP GET request<br>        HttpResponseMessage response = await client.GetAsync(&quot;https://api.example.com/data&quot;);<br><br>        if (response.IsSuccessStatusCode)<br>        {<br>            string responseBody = await response.Content.ReadAsStringAsync();<br>            return responseBody;<br>        }<br>        else<br>        {<br>            // Handle error<br>            return &quot;Error occurred.&quot;;<br>        }<br>    }<br>}</pre><p>4. Use the Service in a Controller:</p><pre>public class MyController : Controller<br>{<br>    private readonly IMyApiService _myApiService;<br><br>    public MyController(IMyApiService myApiService)<br>    {<br>        _myApiService = myApiService;<br>    }<br><br>    public async Task&lt;IActionResult&gt; Index()<br>    {<br>        string apiResponse = await _myApiService.GetApiResponseAsync();<br>        return View(apiResponse);<br>    }<br>}</pre><p>In this example, we’ve utilized <strong>IHttpClientFactoryto </strong>create an <strong>HttpClient </strong>instance within the <strong>MyApiService </strong>class. By doing this, we ensure that the instance is managed efficiently, benefiting from connection pooling and proper resource management. This pattern of using <strong>IHttpClientFactory </strong>to is scalable, maintainable, and aligns with best practices for working with HTTP requests in ASP.NET Core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1970b9719f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>