<?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[Best practise - Medium]]></title>
        <description><![CDATA[Architecture, Software development and digital management best practises - Medium]]></description>
        <link>https://medium.com/best-practise?source=rss----54150f9dc243---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Best practise - Medium</title>
            <link>https://medium.com/best-practise?source=rss----54150f9dc243---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:22:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/best-practise" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Deploy a Vite + React App to IIS with SPA Routing, Base URL, and Static Assets]]></title>
            <link>https://medium.com/best-practise/how-to-deploy-a-vite-react-app-to-iis-with-spa-routing-base-url-and-static-assets-fda27508820a?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/fda27508820a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Thu, 08 May 2025 08:29:52 GMT</pubDate>
            <atom:updated>2025-05-08T08:29:52.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKxGYGL3vQUPEIXokGBD4w.png" /></figure><p>Deploying a modern React app (built with Vite) to IIS can be tricky, especially when it comes to routing, static assets, and subfolder deployments. Here’s a step-by-step guide to get your app running smoothly on IIS, with all images and routes working in both development and production.</p><h3>1. Set the Correct Base URL in Vite</h3><p>In your vite.config.ts, set the base option dynamically based on the build mode:</p><pre>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br><br>export default defineConfig(({ mode }) =&gt; ({<br>  plugins: [react()],<br>  base: mode === &#39;production&#39; ? &#39;/your-app-subfolder/&#39; : &#39;/&#39;,<br>}));</pre><ul><li>Replace /your-app-subfolder/ with your actual IIS virtual directory.</li><li>This ensures all asset URLs are correct in both dev and production.</li></ul><h3>2. Use &lt;BrowserRouter basename={import.meta.env.BASE_URL}&gt;</h3><p>In your main.tsx (or wherever you set up your router), use the Vite-provided base URL:</p><pre>import { BrowserRouter } from &quot;react-router-dom&quot;;<br>import App from &#39;./App&#39;;<br><br>createRoot(document.getElementById(&quot;root&quot;)!).render(<br>  &lt;BrowserRouter basename={import.meta.env.BASE_URL}&gt;<br>    &lt;App /&gt;<br>  &lt;/BrowserRouter&gt;<br>);</pre><ul><li>This tells React Router to handle routes relative to your subfolder.</li></ul><h3>3. Reference Static Assets with the Base URL</h3><p>When referencing images or other static files, always use the base URL:</p><pre>&lt;img src={`${import.meta.env.BASE_URL}uploads/logo.svg`} alt=&quot;Logo&quot; /&gt;<br>&lt;img src={`${import.meta.env.BASE_URL}placeholder.svg`} alt=&quot;Placeholder&quot; /&gt;</pre><ul><li>Never use /public in the path.</li><li>This ensures images work in both dev and production.</li></ul><p>Tip: You can create a helper in src/types/resources.ts:</p><pre>export function getImageUrl(path: string) {<br>  return `${import.meta.env.BASE_URL}${path.replace(/^\//, &#39;&#39;)}`;<br>}</pre><p>And use it like:</p><pre>&lt;img src={getImageUrl(&#39;uploads/logo.svg&#39;)} alt=&quot;Logo&quot; /&gt;</pre><h3>4. Build Your App</h3><p>Run the build command:</p><pre>npm run build</pre><p>The output will be in the dist folder.</p><h3>5. Deploy to IIS</h3><ul><li>Copy the entire dist folder to your IIS server.</li><li>Set the IIS site or application’s physical path to the dist folder.</li><li>Set the virtual path (e.g., /your-app-subfolder).</li><li>If you don’t have yet, add No managed code application pool for the app.</li><li>If you don’t have yet, install the Rewrite from here <a href="https://www.iis.net/downloads/microsoft/url-rewrite">https://www.iis.net/downloads/microsoft/url-rewrite</a></li></ul><h3>6. Add a web.config for SPA Routing</h3><p>Place this web.config in your dist folder:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;configuration&gt;<br>  &lt;system.webServer&gt;<br>    &lt;rewrite&gt;<br>      &lt;rules&gt;<br>        &lt;rule name=&quot;React Router&quot; stopProcessing=&quot;true&quot;&gt;<br>          &lt;match url=&quot;.*&quot; /&gt;<br>          &lt;conditions logicalGrouping=&quot;MatchAll&quot;&gt;<br>            &lt;add input=&quot;{REQUEST_FILENAME}&quot; matchType=&quot;IsFile&quot; negate=&quot;true&quot; /&gt;<br>            &lt;add input=&quot;{REQUEST_FILENAME}&quot; matchType=&quot;IsDirectory&quot; negate=&quot;true&quot; /&gt;<br>          &lt;/conditions&gt;<br>          &lt;action type=&quot;Rewrite&quot; url=&quot;/your-app-subfolder/index.html&quot; /&gt;<br>        &lt;/rule&gt;<br>      &lt;/rules&gt;<br>    &lt;/rewrite&gt;<br>    &lt;staticContent&gt;<br>      &lt;mimeMap fileExtension=&quot;.webmanifest&quot; mimeType=&quot;application/manifest+json&quot; /&gt;<br>      &lt;mimeMap fileExtension=&quot;.svg&quot; mimeType=&quot;image/svg+xml&quot; /&gt;<br>    &lt;/staticContent&gt;<br>  &lt;/system.webServer&gt;<br>&lt;/configuration&gt;</pre><ul><li>This ensures all non-file, non-directory requests are routed to index.html for client-side routing.</li></ul><h3>7. Test Your Deployment</h3><ul><li>Open <a href="http://your-server/your-app-subfolder/">http://your-server/your-app-subfolder/</a> in your browser.</li><li>All routes should work (no 404s on refresh).</li><li>All images and static assets should load from /your-app-subfolder/….</li></ul><h3>8. Troubleshooting</h3><ul><li>404s on refresh: Check your web.config rewrite rule and Vite base URL.</li><li>Broken images/assets: Make sure all static asset paths use ${import.meta.env.BASE_URL} or your helper.</li><li>App loads at root but not subfolder: Double-check the base in vite.config.ts and basename in BrowserRouter.</li><li>Check both — local npm run dev and npm run build versions with different localhost addresses.</li><li><a href="http://localhost:3000/designer">http://localhost:3000/designer</a></li><li><a href="http://localhost/grekai-report-forge/designer">http://localhost/grekai-report-forge/designer</a></li></ul><h3>Conclusion</h3><p>By following these steps, you’ll have a Vite + React app that works perfectly on IIS, with SPA routing and static assets loading correctly in any subfolder. No more 404s or missing images!</p><p>Happy deploying!</p><p>If you found this helpful, follow me for more React and deployment tips.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fda27508820a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/how-to-deploy-a-vite-react-app-to-iis-with-spa-routing-base-url-and-static-assets-fda27508820a">How to Deploy a Vite + React App to IIS with SPA Routing, Base URL, and Static Assets</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Leading IAM Solutions for Your Business: Identity and Access Simplified]]></title>
            <link>https://medium.com/best-practise/5-leading-iam-solutions-for-your-business-identity-and-access-simplified-72a318459404?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/72a318459404</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[identity]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 10:37:52 GMT</pubDate>
            <atom:updated>2024-10-01T11:30:01.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7fgh9GBq-haOR8Yl113pQ.png" /></figure><h3>Introduction</h3><p>In the digital age, organizations face increasing challenges in managing user identities and securing access to their systems. Choosing the right Identity and Access Management (IAM) solution is crucial for ensuring data security, regulatory compliance, and user convenience. This blog will help you navigate the top IAM solutions, including <strong>Duende IdentityServer</strong>, <strong>Keycloak</strong>, <strong>Auth0</strong>, <strong>Okta</strong>, and <strong>Custom ASP.NET Core Identity</strong>, and guide you to make the best choice for your organization.</p><h3>What is Identity and Access Management (IAM)?</h3><p>Identity and Access Management (IAM) is the framework of policies and technologies used to ensure the right individuals get the right access to technology resources. An effective IAM solution manages user identities, enforces policies, controls access, and protects sensitive data. Key aspects of IAM include:</p><ul><li><strong>Authentication and Authorization</strong>: Ensuring users are who they say they are and providing access only to authorized resources.</li><li><strong>Role-Based Access Control (RBAC)</strong>: Assigning permissions to users based on their roles in an organization, ensuring they have access only to the resources necessary for their job.</li><li><strong>Scalability and Integration</strong>: Supporting a growing user base, integrating with different applications, and ensuring the system evolves with business needs.</li><li><strong>Compliance and Security</strong>: Adhering to regulatory requirements and implementing multi-factor authentication (MFA), token management, and other security measures.</li></ul><h3>Comparison of IAM Solutions</h3><p>Below, we provide an in-depth comparison of the five leading IAM solutions that cater to different organizational needs.</p><h3>1. Duende IdentityServer</h3><p><strong>Overview</strong>: Duende IdentityServer is a feature-rich, self-hosted IAM solution built specifically for ASP.NET Core environments. It supports OAuth2, OpenID Connect, and SAML with external integrations.</p><ul><li><strong>Pros</strong>: Strong integration with ASP.NET Core, highly customizable, full control over infrastructure.</li><li><strong>Cons</strong>: Licensing fees, complex self-hosted setup, SAML requires external work.</li><li><strong>Recommendation</strong>: Ideal for enterprises heavily invested in the Microsoft ecosystem requiring scalable and advanced identity management.</li></ul><h3>2. Keycloak</h3><p><strong>Overview</strong>: Keycloak is an open-source IAM solution maintained by Red Hat that natively supports SAML, OAuth2, and OpenID Connect.</p><ul><li><strong>Pros</strong>: Native SAML support, free and open-source, highly customizable.</li><li><strong>Cons</strong>: Complex setup, performance issues at scale, limited .NET SDK.</li><li><strong>Recommendation</strong>: Suitable for companies with strong technical resources needing a cost-effective, self-hosted solution that supports both legacy and modern systems.</li></ul><h3>3. Auth0</h3><p><strong>Overview</strong>: Auth0 is a fully managed cloud-based identity platform with out-of-the-box support for OAuth2, OpenID Connect, and SAML.</p><ul><li><strong>Pros</strong>: Easy setup, SaaS-based, feature-rich (MFA, SSO, RBAC).</li><li><strong>Cons</strong>: Costs increase with user base, limited deep customization.</li><li><strong>Recommendation</strong>: Best suited for high-tech companies, startups, and SaaS businesses looking for rapid deployment without infrastructure management.</li></ul><h3>4. Okta</h3><p><strong>Overview</strong>: Okta is a fully managed IAM provider known for its enterprise-grade features, including SAML, OAuth2, and OpenID Connect support.</p><ul><li><strong>Pros</strong>: Easy to set up, robust security features, compliance-ready.</li><li><strong>Cons</strong>: Costs can be high for larger deployments, limited customization.</li><li><strong>Recommendation</strong>: Ideal for large enterprises needing enterprise-level security, scalability, and compliance.</li></ul><h3>5. Custom ASP.NET Core Identity</h3><p><strong>Overview</strong>: ASP.NET Core Identity is an open-source solution provided by Microsoft that allows developers to build custom authentication and authorization features directly into their applications.</p><ul><li><strong>Pros</strong>: Free, fully customizable, seamless integration with ASP.NET Core.</li><li><strong>Cons</strong>: Requires custom development for advanced features, increased maintenance effort, security responsibilities.</li><li><strong>Recommendation</strong>: Suitable for small to medium-sized businesses with basic identity needs, willing to invest in custom development.</li></ul><h3>Summary Table of Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*SOt7oKwl50W6AiB44CyjDA.png" /></figure><p><strong>OIDC ProviderPricingSAML SupportEase of SetupCustomizationScalabilityBig Companies Using ItDuende IdentityServer</strong>€600/year (2 instances) — €6000/year (unlimited)Requires external integrationModerate (self-hosted)HighHigh (manual)Siemens, Bosch, 3M<strong>Custom ASP.NET Core Identity</strong>FreeRequires custom developmentSimple for basic features, complex with advanced featuresVery High — Complete freedom to develop custom featuresCustom scalability — Requires additional developmentSmall to medium-sized businesses in the Microsoft ecosystem<strong>Keycloak</strong>Free (Open-source)NativeComplex (self-hosted)HighHigh (manual; requires cluster setup)Vodafone, Poste Italiane, T-Systems<strong>Auth0</strong>Free (up to 7000 users) — Starts at $23/month for paid tiersNativeEasy (fully managed)MediumHigh (cloud-based; scales automatically)T-Mobile, NVIDIA, AWS, Mazda<strong>Okta</strong>Free (up to 1000 users) — $2/user or $35+/monthNativeEasy (fully managed)MediumHigh (cloud-based; scales automatically)JetBlue, Atlassian, Engie, Fujitsu, MGM Resorts</p><h3>Conclusion</h3><p>Choosing the right IAM solution depends on your organization’s specific requirements, such as the level of control, scalability, compliance, and budget. Here’s a brief summary:</p><ul><li><strong>Auth0</strong>: Rapid deployment for companies looking for ease of use with managed services.</li><li><strong>Keycloak</strong>: Best for those needing an open-source, flexible solution with advanced customization.</li><li><strong>Duende IdentityServer</strong>: Excellent for enterprises in the ASP.NET ecosystem needing full control.</li><li><strong>Okta</strong>: Enterprise-grade scalability and security for larger organizations.</li><li><strong>Custom ASP.NET Core Identity</strong>: Ideal for small to medium-sized businesses with simple needs and a preference for complete customization.</li></ul><p>Selecting the right IAM solution is a vital step towards building a secure and scalable digital infrastructure that aligns with your organizational goals. We hope this comparison helps you make an informed decision for your business’s identity management needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a318459404" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/5-leading-iam-solutions-for-your-business-identity-and-access-simplified-72a318459404">5 Leading IAM Solutions for Your Business: Identity and Access Simplified</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is BFF (Backend for Frontend) the Best Practice?]]></title>
            <link>https://medium.com/best-practise/is-bff-backend-for-frontend-the-best-practice-c32041b08b0f?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/c32041b08b0f</guid>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 10:36:20 GMT</pubDate>
            <atom:updated>2024-12-15T15:22:23.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*x4A3bi8mzM_wrm4O.png" /></figure><p>BFF is a widely adopted best practice, particularly in <strong>microservices architectures</strong> and modern applications with diverse frontends (web, mobile, IoT). It addresses the challenge of tailoring backend responses for different client types by introducing an intermediary layer that improves efficiency and user experience.</p><p>However, the suitability of BFF depends on the complexity of the application:</p><ul><li><strong>When BFF is appropriate</strong>: Applications with multiple frontends (mobile, web, desktop) that have varying data requirements and response structures.</li><li><strong>When BFF might not be ideal</strong>: Simple systems where a single API layer can effectively serve all frontend clients.</li></ul><h3>Key Components of a BFF Architecture</h3><ol><li><strong>API Gateway</strong> (Optional):</li></ol><ul><li>Routes requests to the correct BFF or backend services.</li><li>Provides basic functionalities like load balancing, rate-limiting, and routing.</li></ul><ol><li><strong>BFF Layer</strong> (Backend for Frontend):</li></ol><ul><li><strong>Purpose</strong>: Tailors API responses specifically for a particular frontend (e.g., Web, Mobile, or RDT).</li><li><strong>Key Responsibilities</strong>:</li><li>Orchestration: Aggregates and transforms data from multiple microservices into a single tailored response.</li><li>Security: Handles authorization, token management, and integrates with Identity APIs.</li><li>Business Logic: Implements client-specific logic or presentation formatting that doesn’t fit into general backend services.</li><li>Caching: Caches frontend-specific data to improve performance.</li><li>API Simplification: Reduces complexity for the frontend by abstracting backend service details.</li></ul><ol><li><strong>Backend Services</strong>:</li></ol><ul><li>Core microservices or APIs that perform business logic, database operations, or external integrations.</li><li>These are <strong>independent</strong> and <strong>reusable</strong> across different frontends.</li></ul><ol><li><strong>Data Layer</strong>:</li></ol><ul><li>Databases or storage systems that backend services interact with to fetch or persist data.</li></ul><ol><li><strong>Security Layer</strong>:</li></ol><ul><li>Handles token validation, encryption, identity management, and role-based access control (RBAC).</li></ul><ol><li><strong>Client-Specific Logic</strong>:</li></ol><ul><li>Encapsulated in the BFF to serve frontend-specific needs such as pagination, filtering, and response transformation.</li></ul><h3>Why Use BFF?</h3><p><strong>Frontend Flexibility</strong>:</p><p>Different frontends have different data and performance requirements. BFF tailors responses for each.</p><p><strong>Performance</strong>:</p><p>Reduces the number of API calls from the frontend by aggregating responses.</p><p><strong>Simplified Frontends</strong>:</p><p>The frontend does not need to understand the complexity of the backend services.</p><p><strong>Separation of Concerns</strong>:</p><p>Keeps backend services clean and generic while the BFF layer handles client-specific logic.</p><p><strong>Improved Developer Experience</strong>:</p><p>Teams working on the web, mobile, or other frontends can independently define and maintain their own BFF.</p><h3>Example Components in a BFF:</h3><ol><li><strong>Authentication Service</strong>: Interfaces with Identity Providers (e.g., OAuth, SSO, LDAP) to validate users.</li><li><strong>MenuAPI</strong>: Tailors navigation or menus for specific frontend users.</li><li><strong>ScreenGeneratorAPI</strong>: Dynamically generates UI screens or layouts based on frontend requirements.</li><li><strong>TableEditorAPI</strong>: Prepares JSON for dynamic table editors specific to frontend clients.</li><li><strong>AppComponentDockAPI</strong>: Manages component layout and organization for dashboards.</li><li><strong>Caching Layer</strong>: Stores frequently accessed data in Redis or similar systems.</li><li><strong>Data Orchestration</strong>: Combines and transforms data from multiple backend APIs.</li></ol><h3>Conclusion:</h3><p>BFF is <strong>best practice</strong> for applications with complex frontend needs because it improves performance, streamlines client-server communication, and keeps backend services clean. The BFF layer bridges the gap between generic microservices and frontend-specific requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c32041b08b0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/is-bff-backend-for-frontend-the-best-practice-c32041b08b0f">Is BFF (Backend for Frontend) the Best Practice?</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Unit of Work Pattern in C# for Modern Applications]]></title>
            <link>https://medium.com/best-practise/mastering-the-unit-of-work-pattern-in-c-for-modern-applications-dd790d029f90?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/dd790d029f90</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[csharp-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[entity-framework]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:41:55 GMT</pubDate>
            <atom:updated>2024-11-06T03:12:26.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAMpmc_NlXPSH_tamJ7hww.png" /></figure><h3>Introduction</h3><p>In the ever-evolving world of software development, maintaining code quality and ensuring data integrity across various application layers is paramount. The Unit of Work (UOW) pattern, especially when combined with Repository and Entity Framework (EF), stands out as a powerful tool to achieve these goals. This blog post will deep dive into the difficulties of the UOW pattern, its integration with modern technologies like Redis, and its implementation in complex systems such as Warehouse Management Systems (WMS).</p><h3>Why Use the UoW Pattern?</h3><p><strong>1. Separation of Concerns</strong>: UOW decouples business logic from data access logic, ensuring a cleaner and more maintainable codebase.</p><p><strong>2. Testability</strong>: By abstracting data access through repositories, the UOW pattern facilitates easier unit testing with mock repositories.</p><p><strong>3. Consistency</strong>: Ensures that transactions across multiple repositories are handled uniformly, maintaining data integrity.</p><h3>Using UOW in a 20-Year Legacy WMS Project</h3><p>For a complex Warehouse Management System (WMS), the UoW pattern is particularly beneficial:</p><p><strong>1. Transactional Integrity</strong>: Ensures all operations in a transaction succeed or none do, preventing data corruption. This is crucial for inventory updates and order processing.</p><p><strong>2. Managing Complex Interdependencies</strong>: Coordinates changes across different repositories, ensuring related operations are handled together. This is vital for batch processing and inventory reconciliation.</p><p><strong>3. Legacy Integration</strong>: Provides a structured way to modernize and refactor without breaking existing functionality. The gradual integration of modern practices becomes feasible.</p><p><strong>4. Scalability and Maintainability</strong>: Decouples business logic from data access logic, allowing independent updates or scaling. This helps in evolving the system without significant downtime.</p><p><strong>5. Consistency and Reliability</strong>: Ensures consistent state management, crucial for operations such as inventory management and shipping logistics.</p><h3>UOW with Repository Pattern and EF</h3><p>The UoW pattern complements the Repository pattern, especially with Entity Framework (EF):</p><ul><li><strong>Transaction Management</strong>: Ensures all operations complete successfully or none do, maintaining data integrity.</li><li><strong>Change Tracking</strong>: Tracks changes to entities, minimizing database operations.</li><li><strong>Centralized Save Operation</strong>: Commits all changes in a single transaction.</li></ul><p><strong>Implementation Example</strong>:</p><p><strong>Repository Interface</strong>:</p><pre>public interface IRepository&lt;T&gt; where T : class {<br>    IEnumerable&lt;T&gt; GetAll();<br>    T GetById(int id);<br>    void Add(T entity);<br>    void Update(T entity);<br>    void Delete(T entity);<br>}</pre><p><strong>Repository Implementation</strong>:</p><pre>public class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class {<br>    protected readonly DbContext _context;<br>    protected readonly DbSet&lt;T&gt; _dbSet;<br><br>    public Repository(DbContext context) {<br>        _context = context;<br>        _dbSet = context.Set&lt;T&gt;();<br>    }<br><br>    public IEnumerable&lt;T&gt; GetAll() =&gt; _dbSet.ToList();<br>    public T GetById(int id) =&gt; _dbSet.Find(id);<br>    public void Add(T entity) =&gt; _dbSet.Add(entity);<br>    public void Update(T entity) {<br>        _dbSet.Attach(entity);<br>        _context.Entry(entity).State = EntityState.Modified;<br>    }<br>    public void Delete(T entity) {<br>        if (_context.Entry(entity).State == EntityState.Detached) {<br>            _dbSet.Attach(entity);<br>        }<br>        _dbSet.Remove(entity);<br>    }<br>}</pre><p><strong>Unit of Work Interface</strong>:</p><pre>public interface IUnitOfWork : IDisposable {<br>    IRepository&lt;User&gt; Users { get; }<br>    IRepository&lt;Order&gt; Orders { get; }<br>    int Complete();<br>}</pre><p><strong>Unit of Work Implementation</strong>:</p><pre>public class UnitOfWork : IUnitOfWork {<br>    private readonly DbContext _context;<br>    public IRepository&lt;User&gt; Users { get; private set; }<br>    public IRepository&lt;Order&gt; Orders { get; private set; }<br><br>    public UnitOfWork(DbContext context) {<br>        _context = context;<br>        Users = new Repository&lt;User&gt;(context);<br>        Orders = new Repository&lt;Order&gt;(context);<br>    }<br><br>    public int Complete() =&gt; _context.SaveChanges();<br>    public void Dispose() =&gt; _context.Dispose();<br>}</pre><p><strong>Usage Example</strong>:</p><pre>using (var unitOfWork = new UnitOfWork(new ApplicationDbContext())) {<br>    var user = unitOfWork.Users.GetById(1);<br>    user.Name = &quot;New Name&quot;;<br><br>    var order = unitOfWork.Orders.GetById(1);<br>    order.Status = &quot;Completed&quot;;<br><br>    unitOfWork.Complete();<br>}</pre><h3>Pros and Cons of Using UOW</h3><p><strong>Pros</strong>:</p><ul><li><strong>Transaction Management</strong>: Ensures operations either all succeed or all fail.</li><li><strong>Change Tracking</strong>: Optimizes database interactions by tracking changes.</li><li><strong>Simplified CRUD Operations</strong>: Provides a central point for committing changes.</li><li><strong>Decoupling</strong>: Separates business logic from data access logic.</li><li><strong>Testability</strong>: Enhances testability by abstracting the data access layer.</li></ul><p><strong>Cons</strong>:</p><ul><li><strong>Complexity</strong>: Introduces additional complexity.</li><li><strong>Performance Overhead</strong>: Can introduce overhead due to tracking of entity states and managing transactions.</li><li><strong>Learning Curve</strong>: Requires understanding of both UOW and Repository patterns.</li><li><strong>Overhead for Simple Applications</strong>: May be overkill for straightforward data access needs.</li><li><strong>Tight Coupling with ORM</strong>: Often tightly coupled with a specific ORM.</li><li><strong>Difficulty with Distributed Transactions</strong>: Managing transactions across multiple databases can be challenging.</li></ul><h3>UOW and Redis Bus Events with DDD and Identity API Security</h3><p><strong>Integration Overview</strong>:</p><ul><li><strong>UOW and DDD Transactions Between DbContexts</strong>: Ensures consistency and integrity across different bounded contexts.</li><li><strong>Redis Bus Events</strong>: Handles events in a distributed system.</li><li><strong>Identity API Security</strong>: Ensures only authenticated and authorized users can access certain endpoints.</li></ul><p><strong>Implementation Example</strong>:</p><p><strong>UnitOfWork Implementation</strong>:</p><pre>public class UnitOfWork : IUnitOfWork {<br>    private readonly FirstDbContext _firstContext;<br>    private readonly SecondDbContext _secondContext;<br>    private readonly IConnectionMultiplexer _redis;<br><br>    public IUserRepository Users { get; private set; }<br>    public IOrderRepository Orders { get; private set; }<br>    public IEventPublisher EventPublisher { get; private set; }<br><br>    public UnitOfWork(FirstDbContext firstContext, SecondDbContext secondContext, IConnectionMultiplexer redis) {<br>        _firstContext = firstContext;<br>        _secondContext = secondContext;<br>        _redis = redis;<br>        Users = new UserRepository(_firstContext);<br>        Orders = new OrderRepository(_secondContext);<br>        EventPublisher = new EventPublisher(_redis);<br>    }<br><br>    public int Complete() {<br>        using (var transaction1 = _firstContext.Database.BeginTransaction())<br>        using (var transaction2 = _secondContext.Database.BeginTransaction()) {<br>            try {<br>                int result1 = _firstContext.SaveChanges();<br>                int result2 = _secondContext.SaveChanges();<br><br>                transaction1.Commit();<br>                transaction2.Commit();<br><br>                // Publish event to Redis<br>                EventPublisher.PublishEvent(&quot;OrderChannel&quot;, &quot;Order created&quot;);<br><br>                return result1 + result2;<br>            } catch (Exception ex) {<br>                transaction1.Rollback();<br>                transaction2.Rollback();<br>                throw;<br>            }<br>        }<br>    }<br><br>    public void Dispose() {<br>        _firstContext.Dispose();<br>        _secondContext.Dispose();<br>    }<br>}</pre><p><strong>Secure Controller Implementation</strong>:</p><pre>[Authorize]<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class OrdersController : ControllerBase {<br>    private readonly UserService _userService;<br><br>    public OrdersController(UserService userService) {<br>        _userService = userService;<br>    }<br><br>    [HttpPost]<br>    public IActionResult CreateUserAndOrder(User user, Order order) {<br>        try {<br>            _userService.CreateUserAndOrder(user, order);<br>            return Ok();<br>        } catch (Exception ex) {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br>}</pre><p><strong>Event Publisher Implementation</strong>:</p><pre>public class EventPublisher : IEventPublisher {<br>    private readonly IConnectionMultiplexer _redis;<br><br>    public EventPublisher(IConnectionMultiplexer redis) {<br>        _redis = redis;<br>    }<br><br>    public void PublishEvent(string channel, string message) {<br>        var subscriber = _redis.GetSubscriber();<br>        subscriber.Publish(channel, message);<br>    }<br>}</pre><p><strong>Event Subscriber Implementation</strong>:</p><pre>public class EventSubscriber {<br>    private readonly IConnectionMultiplexer _redis;<br><br>    public EventSubscriber(IConnectionMultiplexer redis) {<br>        _redis = redis;<br>    }<br><br>    public void SubscribeToEvent(string channel) {<br>        var subscriber = _redis.GetSubscriber();<br>        subscriber.Subscribe(channel, (ch, msg) =&gt; {<br>            // Handle the message<br>            Console.WriteLine($&quot;Received message: {msg}&quot;);<br>        });<br>    }<br>}</pre><h3>Added Value for New Developers</h3><ul><li><strong>Consistency</strong>: Ensures operations are completed successfully or not at all.</li><li><strong>Maintainability</strong>: Promotes a clean separation of concerns.</li><li><strong>Scalability</strong>: Supports scalable and distributed systems.</li><li><strong>Security</strong>: Ensures robust security with API authentication and authorization.</li><li><strong>Testability</strong>: Facilitates testing with DI and mock repositories.</li><li><strong>Readability</strong>: Provides a well-structured project with clear responsibilities for each layer.</li></ul><h3>Real-Life Use Cases</h3><p><strong>For Developers</strong>: Implementing UOW can simplify the development process, ensuring that changes across multiple repositories are handled seamlessly. It also makes unit testing more straightforward, as developers can mock repositories and test business logic in isolation.</p><p><strong>For Team Leads</strong>: UOW promotes a consistent coding standard across the team. It ensures that everyone follows the same transaction management practices, reducing bugs and improving code quality.</p><p><strong>For Architects</strong>: UOW provides a scalable architecture that can handle complex transactions across different parts of a system# Mastering the Unit of Work Pattern in C# for Modern Applications</p><p><strong>Bibliography</strong></p><p><strong>Pros and Cons of Using the Unit of Work Pattern</strong></p><p><strong>Pros:</strong></p><p>1. <strong>Transaction Management</strong>: Explains how UOW ensures data integrity by managing transactions in ASP.NET MVC. <a href="https://www.codeproject.com/Articles/5268748/Understanding-the-Repository-and-Unit-of-Work-Pat">Understanding the Repository and Unit of Work Patterns in ASP.NET MVC</a></p><p>2. <strong>Change Tracking</strong>: Discusses how UOW keeps track of entity changes to optimize database operations. <a href="https://dotnettutorials.net/lesson/repository-design-pattern-csharp/">Repository and Unit of Work Pattern in ASP.NET MVC</a></p><p>3. <strong>Simplified CRUD Operations</strong>: Highlights how UOW simplifies data modifications with a centralized SaveChanges call. <a href="https://www.c-sharpcorner.com/article/repository-and-unit-of-work-pattern-in-asp-net-core/">Repository and Unit of Work Pattern in ASP.NET Core</a></p><p>4. <strong>Decoupling and Separation of Concerns</strong>: Details how UOW separates business logic from data access logic for maintainable code. <a href="https://medium.com/@alirezaghey/using-the-unit-of-work-and-repository-pattern-with-entity-framework-dbcontext-41d44d330594">Using the Unit of Work and Repository Pattern with Entity Framework</a></p><p>5. <strong>Testability</strong>: Enhances unit testing by abstracting the data access layer through repositories. <a href="https://docs.microsoft.com/en-us/ef/core/testing/">Unit Testing with the Unit of Work Pattern</a></p><p>6. <strong>Consistent API</strong>: Provides a standard API for data operations, making the code more predictable. <a href="https://dev.to/n_develop/applying-the-unit-of-work-pattern-in-your-applications-3djf">Applying the Unit of Work Pattern in Your Applications</a></p><p><strong>Cons:</strong></p><p>1. <strong>Complexity</strong>: Discusses the additional complexity introduced by the UOW pattern. <a href="https://ardalis.com/the-drawbacks-of-the-repository-and-unit-of-work-patterns/">The Drawbacks of the Repository and Unit of Work Patterns</a></p><p>2. <strong>Performance Overhead</strong>: Highlights potential performance issues due to entity state tracking and transaction management. <a href="https://deviq.com/repository-pattern/">Repository Pattern &amp; Unit of Work: When To Use It and Why</a></p><p>3. <strong>Learning Curve</strong>: Emphasizes the need to understand both UOW and Repository patterns. <a href="https://www.ryadel.com/en/asp-net-mvc-unit-of-work-repository-pattern/">Understanding Repository and Unit of Work Pattern</a></p><p><strong>4. Overhead for Simple Applications</strong>: Argues that UOW might be overkill for simple applications with basic data access needs. <a href="https://www.thereformedprogrammer.net/why-i-dont-use-the-repository-pattern-with-ef-core/">Do We Really Need the Repository Pattern?</a></p><p>5.<strong> Tight Coupling with ORM</strong>: Discusses the tight coupling of UOW with specific ORMs like Entity Framework. <a href="https://ardalis.com/repository-pattern-vs-entity-framework/">Repository Pattern vs. Entity Framework</a></p><p>6. <strong>Difficulty with Distributed Transaction</strong>: Covers challenges in managing distributed transactions with UOW. <a href="https://medium.com/swlh/handling-distributed-transactions-in-microservices-architecture-21ba2d4e5d53">Handling Distributed Transactions with UOW</a></p><p><strong>Using UOW with Redis and ETL</strong></p><p><strong>1. UOW and DDD Transactions Between DbContexts</strong>: Explains UOW in the context of Domain-Driven Design transactions. <a href="https://enterprisecraftsmanship.com/posts/repository-implementation-patterns/">DDD and the Unit of Work Pattern</a></p><p>2. <strong>Redis Bus Events</strong>: Details using Redis for event messaging in distributed systems. <a href="https://redis.io/topics/pubsub">Using Redis for Event Messaging</a></p><p>3. <strong>Identity API Security</strong>: Discusses securing APIs with IdentityServer4 for authentication and authorization. <a href="https://identityserver4.readthedocs.io/en/latest/">Securing ASP.NET Core APIs with IdentityServer4</a></p><p>4. <strong>ETL Process Management</strong>: Describes how UOW can be applied to manage ETL processes efficiently. <a href="https://towardsdatascience.com/how-to-create-a-scalable-etl-solution-with-python-5c47e3a49f6f">Unit of Work Pattern in ETL Processes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd790d029f90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/mastering-the-unit-of-work-pattern-in-c-for-modern-applications-dd790d029f90">Mastering the Unit of Work Pattern in C# for Modern Applications</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working Plan for Integrating Log Exception Health Check
1.]]></title>
            <link>https://medium.com/best-practise/working-plan-for-integrating-log-exception-health-check-1-a3ab2922a559?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/a3ab2922a559</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:41:45 GMT</pubDate>
            <atom:updated>2024-11-06T03:12:07.328Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Working Plan for Integrating Log Exception Health Check</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*-dL_prZi2wvRa7HxGTFCCw.png" /><figcaption>Health</figcaption></figure><h3><strong>1. Project Overview and Objectives</strong></h3><p>The goal is to integrate a robust logging and health check system into the organization’s renovation project. This will ensure real-time monitoring, efficient log management, and prompt alerting for exceptions in the microservices architecture. The solution will leverage <strong>Serilog</strong> for structured logging, <strong>Prometheus</strong> for metrics collection, and <strong>Grafana</strong> for visualization and alerting.</p><h3>2. System Architecture</h3><p><strong>Components:</strong></p><ul><li><strong>Microservices</strong>: .NET Core microservices generating logs and metrics.</li><li><strong>Serilog</strong>: For structured logging and storage in SQL Server.</li><li><strong>Prometheus</strong>: For scraping and storing metrics.</li><li><strong>Grafana</strong>: For visualizing logs and metrics, and setting up alerts.</li><li><strong>HealthChecks.UI</strong>: For displaying the health status of microservices.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*hTz5ofq3A76dk_QOUW6nFg.png" /></figure><p><strong>Data Flow:</strong></p><ol><li>Log Generation: Microservices use Serilog to generate logs.</li><li>Metrics Scraping: Prometheus scrapes metrics from microservices.</li><li>Data Storage: Logs in SQL Server; metrics in Prometheus.</li><li>Visualization: Grafana retrieves data from Prometheus and SQL Server to create dashboards.</li><li>Alerting: Grafana triggers alerts based on Prometheus metrics.</li></ol><h3>3. Implementation Plan</h3><p><strong>Milestone 1: Logging Setup with Serilog</strong></p><ul><li>Configure Serilog in each microservice to log to SQL Server.</li><li>Set up centralized exception handling middleware.</li><li><strong>Timeline</strong>: 2 weeks</li></ul><p><strong>Milestone 2: Health Check Endpoints</strong></p><ul><li>Implement health check endpoints in each microservice.</li><li>Deploy microservices on IIS, ensuring health endpoints are accessible.</li><li><strong>Timeline</strong>: 1 week</li></ul><p><strong>Milestone 3: Prometheus and Grafana Setup</strong></p><ul><li>Install and configure Prometheus to scrape metrics.</li><li>Install and configure Grafana, adding Prometheus and SQL Server as data sources.</li><li>Create dashboards in Grafana for monitoring.</li><li><strong>Timeline</strong>: 2 weeks</li></ul><p><strong>Milestone 4: HealthChecks.UI Setup</strong></p><ul><li>Install and configure HealthChecks.UI to monitor health check endpoints.</li><li>Integrate with Grafana for consolidated monitoring.</li><li><strong>Timeline</strong>: 1 week</li></ul><p><strong>Milestone 5: Alerting Configuration</strong></p><ul><li>Define alert rules in Prometheus and Grafana.</li><li>Set up notification channels (email, Slack) for alerts.</li><li><strong>Timeline</strong>: 1 week</li></ul><p><strong>Milestone 6: Testing and Validation</strong></p><ul><li>Thorough testing of logging, health check, and alerting setup.</li><li>Validate performance and reliability.</li><li><strong>Timeline</strong>: 2 weeks</li></ul><p><strong>Milestone 7: Documentation and Training</strong></p><ul><li>Document the setup for future reference.</li><li>Conduct training for development and operations teams.</li><li><strong>Timeline</strong>: 1 week</li></ul><h3>4. Detailed Steps for Each Milestone</h3><p><strong>Milestone 1: Logging Setup with Serilog</strong></p><p><strong>Program.cs Configuration:</strong></p><pre>using Serilog;<br>using Serilog.Sinks.MSSqlServer;<br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        Log.Logger = new LoggerConfiguration()<br>            .WriteTo.MSSqlServer(<br>                connectionString: &quot;YourConnectionString&quot;,<br>                sinkOptions: new MSSqlServerSinkOptions { TableName = &quot;Logs&quot;, AutoCreateSqlTable = true })<br>            .CreateLogger();<br>         try<br>        {<br>            Log.Information(&quot;Starting up&quot;);<br>            CreateHostBuilder(args).Build().Run();<br>        }<br>        catch (Exception ex)<br>        {<br>            Log.Fatal(ex, &quot;Application start-up failed&quot;);<br>        }<br>        finally<br>        {<br>            Log.CloseAndFlush();<br>        }<br>    }<br>public static IHostBuilder CreateHostBuilder(string[] args) =&gt;<br>        Host.CreateDefaultBuilder(args)<br>            .UseSerilog()<br>            .ConfigureWebHostDefaults(webBuilder =&gt; { webBuilder.UseStartup&lt;Startup&gt;(); });<br>}</pre><p><strong>Centralized Exception Handling Middleware:</strong></p><pre>public class ExceptionHandlingMiddleware<br>{<br>    private readonly RequestDelegate _next;<br>    public ExceptionHandlingMiddleware(RequestDelegate next)<br>    {<br>        _next = next;<br>    }<br>    <br>    public async Task Invoke(HttpContext context)<br>    {<br>        try<br>        {<br>            await _next(context);<br>        }<br>        catch (Exception ex)<br>        {<br>            LogError(context, ex);<br>            throw;<br>        }<br>    }<br>     private void LogError(HttpContext context, Exception ex)<br>    {<br>        Log.Error(ex, &quot;An unhandled exception occurred. Path: {Path}&quot;, context.Request.Path);<br>    }<br>}<br>// In Startup.cs<br>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    app.UseMiddleware&lt;ExceptionHandlingMiddleware&gt;();<br>    // other middlewares...<br>}</pre><p><strong>Milestone 2: Health Check Endpoints</strong></p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddHealthChecks()<br>        .AddSqlServer(Configuration[&quot;ConnectionStrings:DefaultConnection&quot;]);<br>}<br>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    app.UseEndpoints(endpoints =&gt; { endpoints.MapHealthChecks(&quot;/health&quot;); });<br>}</pre><p><strong>Milestone 3: Prometheus and Grafana Setup</strong></p><p><strong>Prometheus Configuration (</strong><strong>prometheus.yml):</strong></p><pre>global:<br>  scrape_interval: 15s<br>  scrape_configs:<br>  - job_name: &#39;made4net-microservices&#39;<br>    static_configs:<br>      - targets: [&#39;microservice1:5000&#39;, &#39;microservice2:5000&#39;]</pre><p><strong>Grafana Configuration:</strong></p><ul><li>Add Prometheus as a data source.</li><li>Create dashboards to visualize CPU, memory usage, request rates, error rates, and custom metrics.</li></ul><p><strong>Milestone 4: HealthChecks.UI Setup</strong></p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    services.AddHealthChecksUI(setup =&gt;<br>    {<br>        setup.AddHealthCheckEndpoint(&quot;Service 1&quot;, &quot;http://vm1/service1/health&quot;);<br>        setup.AddHealthCheckEndpoint(&quot;Service 2&quot;, &quot;http://vm2/service2/health&quot;);<br>    }).AddInMemoryStorage();<br>}<br>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>    app.UseEndpoints(endpoints =&gt; { endpoints.MapHealthChecksUI(); });<br>}</pre><p><strong>Milestone 5: Alerting Configuration</strong></p><p><strong>Example Prometheus Alert Rule:</strong></p><pre>alert: HighErrorRate<br>expr: increase(http_requests_total{status=&quot;500&quot;}[5m]) &gt; 10<br>for: 5m<br>labels:<br>  severity: critical<br>annotations:<br>  summary: &quot;High error rate detected&quot;<br>  description: &quot;The error rate is above 10 in the last 5 minutes.&quot;</pre><p><strong>Grafana Alert Configuration:</strong></p><ul><li>Set up notification channels (e.g., email, Slack).</li><li>Define alert rules based on Prometheus metrics.</li></ul><h3>5. Testing and Validation</h3><ul><li>Conduct end-to-end testing of the logging and health check integration.</li><li>Validate performance and reliability.</li><li>Ensure alerts are triggered correctly.</li></ul><h3>6. Documentation and Training</h3><ul><li>Document the setup for future reference.</li><li>Conduct training sessions for the development and operations teams.</li></ul><p><strong>Conclusion:</strong> Following this comprehensive plan will ensure that the integration of log exception health checks into your microservices architecture is systematic and efficient, providing robust monitoring, logging, and alerting capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ab2922a559" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/working-plan-for-integrating-log-exception-health-check-1-a3ab2922a559">Working Plan for Integrating Log Exception Health Check
1.</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prometheus and Grafana 

Introduction
This document outlines the integration and…]]></title>
            <link>https://medium.com/best-practise/prometheus-and-grafana-introduction-this-document-outlines-the-integration-and-1c3b2e8fa86e?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/1c3b2e8fa86e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:41:34 GMT</pubDate>
            <atom:updated>2024-11-06T03:11:39.414Z</atom:updated>
            <content:encoded><![CDATA[<p>Prometheus and Grafana<br><br>Introduction<br>This document outlines the integration and usage of Prometheus and Grafana for monitoring and visualizing the performance and health of our .NET Core microservices. This setup will enable real-time monitoring, alerting, and detailed visualization of logs and metrics.<br>Objectives<br>•	Monitoring: Provide real-time monitoring of microservices.<br>•	Visualization: Enable detailed visualization of metrics and logs.<br>•	Alerting: Set up alerting mechanisms for critical conditions.<br>•	Scalability: Ensure the monitoring setup can scale with the application.<br>Architecture Overview<br>Components<br>1.	Microservices: .NET Core microservices generating metrics and logs.<br>2.	Prometheus: Monitoring system to scrape metrics from microservices.<br>3.	Grafana: Visualization tool to create dashboards and alerts based on Prometheus data.<br>4.	Log Storage: SQL Server for storing logs.<br>5.	Log Aggregation and Processing: Using Serilog for structured logging and log storage.<br>6.	Alerting System: Grafana integrated with Prometheus for alerting based on predefined conditions.<br>Data Flow<br>7.	Metrics Generation: Microservices expose metrics endpoints.<br>8.	Metrics Scraping: Prometheus scrapes metrics from these endpoints.<br>9.	Data Storage: Prometheus stores the scraped metrics.<br>10.	Visualization: Grafana retrieves data from Prometheus to create dashboards.<br>11.	Alerting: Alerts are configured in Grafana based on Prometheus data.<br>12.	Log Generation and Storage: Microservices log to SQL Server using Serilog.<br>13.	Log Visualization: Grafana visualizes logs stored in SQL Server.<br>Detailed Design<br>Prometheus Setup<br>Installation:<br>•	Install Prometheus on a dedicated server or within the Kubernetes cluster.<br>•	Configure Prometheus to scrape metrics from the microservices.<br>Configuration:<br>•	Define a prometheus.yml configuration file to specify scrape targets:<br>yaml<br><br>global:<br> scrape_interval: 15s<br><br>scrape_configs:<br> - job_name: &#39;microservices&#39;<br> static_configs:<br> - targets: [’microservice1:5000’, &#39;microservice2:5000’]<br><br>Microservices Metrics Exposure<br>Using Prometheus.NET:<br>•	Add Prometheus.NET package to your microservices:<br>shell<br><br>dotnet add package prometheus-net.AspNetCore<br><br>•	Expose metrics endpoint in your Startup.cs:<br>csharp<br><br>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br> // other middlewares...<br> app.UseMetricServer();<br> // other middlewares...<br>}<br><br>Grafana Setup<br>Installation:<br>•	Install Grafana on a dedicated server or within the Kubernetes cluster.<br>•	Configure Grafana to use Prometheus as a data source.<br>Configuration:<br>•	Add Prometheus as a data source in Grafana:<br>yaml<br><br>apiVersion: 1<br>datasources:<br> - name: Prometheus<br> type: prometheus<br> access: proxy<br> url: http://prometheus-server:9090<br><br>Creating Dashboards in Grafana<br>14.	Add Data Source: Add Prometheus as a data source in Grafana.<br>15.	Create Dashboards: Use Grafana to create dashboards visualizing metrics from Prometheus.<br>16.	Example Panels:<br>o	CPU and Memory Usage<br>o	Request Rates<br>o	Error Rates<br>o	Custom Application Metrics<br>Alerting with Grafana<br>17.	Configure Alerting: Set up alert rules in Grafana based on Prometheus metrics.<br>18.	Notification Channels: Define notification channels (e.g., email, Slack) for alerts.<br>19.	Example Alert Rule:<br>o	High Error Rate Alert:<br>yaml<br><br><br>alert: HighErrorRate<br>expr: increase(http_requests_total{status=&quot;500&quot;}[5m]) &gt; 10<br>for: 5m<br>labels:<br> severity: critical<br>annotations:<br> summary: &quot;High error rate detected&quot;<br> description: &quot;The error rate is above 10 in the last 5 minutes.&quot;<br><br>Log Aggregation and Processing<br>Using Serilog:<br>•	Add Serilog packages to your microservices:<br>shell<br><br>dotnet add package Serilog<br>dotnet add package Serilog.Sinks.MSSqlServer<br><br>•	Configure Serilog to log to SQL Server:<br>csharp<br><br>public class Program<br>{<br> public static void Main(string[] args)<br> {<br> Log.Logger = new LoggerConfiguration()<br> .WriteTo.MSSqlServer(<br> connectionString: &quot;YourConnectionString&quot;,<br> sinkOptions: new MSSqlServerSinkOptions { TableName = &quot;Logs&quot;, AutoCreateSqlTable = true })<br> .CreateLogger();<br><br> CreateHostBuilder(args).Build().Run();<br> }<br><br> public static IHostBuilder CreateHostBuilder(string[] args) =&gt;<br> Host.CreateDefaultBuilder(args)<br> .UseSerilog()<br> .ConfigureWebHostDefaults(webBuilder =&gt;<br> {<br> webBuilder.UseStartup&lt;Startup&gt;();<br> });<br>}<br><br>Visualizing Logs in Grafana<br>Connecting SQL Server:<br>•	Add SQL Server as a data source in Grafana.<br>•	Create dashboards to visualize logs stored in SQL Server.<br>Pricing and Licensing<br>Prometheus<br>Pricing:<br>•	Free: Prometheus is an open-source project and is free to use.<br>Licensing:<br>•	Apache 2.0 License: Permissive open-source license that allows for free use, modification, and distribution.<br>Explanation:<br>•	Prometheus is a highly flexible and robust monitoring system that can be freely used and modified. It is suitable for both on-premise and cloud deployments.<br>Grafana<br>Pricing:<br>•	Free: Grafana is open-source and free for basic use.<br>•	Grafana Cloud: Offers hosted Grafana services with additional features, starting at $49/month for the Pro plan.<br>Licensing:<br>•	AGPLv3 License: Open-source license for the community edition.<br>•	Commercial License: Available for enterprise features and support.<br>Explanation:<br>•	Grafana provides powerful visualization and alerting capabilities. The free version is sufficient for many use cases, while the cloud version offers additional features and managed services.<br>Conclusion and Recommendation<br>Integrating Prometheus and Grafana provides a powerful solution for monitoring, visualizing, and alerting on the performance and health of our .NET Core microservices. This setup enables real-time insights into application metrics and logs, ensuring prompt detection and resolution of issues. By leveraging Prometheus for metrics scraping and Grafana for visualization and alerting, we can achieve a scalable and robust monitoring solution tailored to our needs.<br>Recommendation:<br>•	Use Prometheus for metrics scraping and storage due to its robust, free, and open-source nature.<br>•	Use Grafana for visualization and alerting, leveraging the free version for basic use or considering the Grafana Cloud for additional features and managed services if needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3b2e8fa86e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/prometheus-and-grafana-introduction-this-document-outlines-the-integration-and-1c3b2e8fa86e">Prometheus and Grafana 

Introduction
This document outlines the integration and…</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging Architecture Comparison Document

	
		
Summary – Serilog is the best option.]]></title>
            <link>https://medium.com/best-practise/logging-architecture-comparison-document-summary-serilog-is-the-best-option-03bdd2302dbf?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/03bdd2302dbf</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:41:23 GMT</pubDate>
            <atom:updated>2024-11-06T03:11:04.988Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Choosing the Best Logging Framework for .NET Core Microservices</strong></h3><p>When it comes to building robust microservices, logging plays a crucial role in ensuring system observability, monitoring, and troubleshooting. Choosing the right logging framework is an architectural decision that can significantly impact how we handle system events, metrics, and alerts. In this post, we’ll compare three widely-used logging frameworks — <strong>Serilog</strong>, <strong>NLog</strong>, and <strong>log4net</strong> — and recommend the best solution for .NET Core microservices.</p><h4>Out of Scope and Requirements</h4><p>While this comparison primarily focuses on logging frameworks, the following are outside the scope of this review:</p><ul><li>Monitoring-only tools without built-in logging capabilities (e.g., Grafana, Kibana).</li><li>Logging tools that do not natively support structured logging.</li><li>Frameworks that cannot easily integrate with .NET Core.</li><li>Solutions requiring extensive external configuration for every log export or alert.</li></ul><h3>Requirements:</h3><ol><li><strong>Structured Logging</strong>: The ability to create searchable, detailed logs that go beyond simple text.</li><li><strong>Ease of Configuration</strong>: Fluent API or code-based configurations for minimal overhead.</li><li><strong>Performance</strong>: Asynchronous logging to handle high throughput efficiently.</li><li><strong>Integration with Monitoring Tools</strong>: Seamless integration with <strong>Prometheus</strong> and <strong>Grafana</strong> for monitoring and alerting.</li><li><strong>Flexibility</strong>: Dynamic log level adjustments and support for log enrichment (e.g., adding custom fields).</li><li><strong>Community and Documentation</strong>: Strong community support and up-to-date documentation to future-proof the logging setup.</li></ol><h3>Logging Framework Comparison</h3><p>Here’s a high-level comparison of the three logging frameworks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*0m14ZgeODhpUYFPGuQHHjQ.png" /></figure><h3>Key Highlights</h3><h4>Serilog — Best for Structured Logging and Modern Needs</h4><ul><li><strong>Pros</strong>: Excellent structured logging support, wide range of sinks, ease of configuration with fluent API, good integration with monitoring tools like Prometheus and Grafana, strong community support.</li><li><strong>Cons</strong>: Slightly steeper learning curve for developers new to structured logging.</li></ul><h4>NLog — Flexible but Limited in Structured Logging</h4><ul><li><strong>Pros</strong>: Flexible, highly configurable, good performance, well-suited for simpler logging needs.</li><li><strong>Cons</strong>: Limited structured logging support, complex configurations for advanced scenarios.</li></ul><h4>log4net — Mature but Lacks Modern Features</h4><ul><li><strong>Pros</strong>: A well-established framework with a stable user base.</li><li><strong>Cons</strong>: Lacks modern features like structured logging and easy integration with Prometheus/Grafana.</li></ul><h3>Architectural Decision</h3><p>After analyzing the strengths and weaknesses of each logging framework, <strong>Serilog</strong> stands out as the clear choice for our .NET Core microservices architecture. Here’s why:</p><ol><li><strong>Structured Logging</strong>: Serilog’s excellent support for structured logging ensures that logs are detailed, searchable, and provide meaningful insights into system behavior.</li><li><strong>Ease of Configuration</strong>: With its fluent configuration model and tight integration with .NET Core’s dependency injection, Serilog offers simplicity in managing complex logging setups.</li><li><strong>Performance</strong>: Serilog’s asynchronous logging ensures that our microservices can handle high traffic efficiently without slowing down.</li><li><strong>Seamless Integration</strong>: Serilog integrates smoothly with <strong>Prometheus</strong> for metrics and <strong>Grafana</strong> for visualization, making monitoring and alerting straightforward.</li><li><strong>Future-Proof</strong>: Its active community and continuous improvement mean that Serilog will remain a robust and future-proof solution as our architecture evolves.</li></ol><h3>Conclusion</h3><p>For an architecture focused on scalability, flexibility, and robust monitoring, <strong>Serilog</strong> is the most suitable logging framework. Its structured logging, ease of configuration, and strong integration capabilities make it an ideal choice for modern microservices in .NET Core environments. While <strong>NLog</strong> and <strong>log4net</strong> have their own advantages, they lack the modern features and ease of integration required for our needs.</p><p>Implementing Serilog will ensure we have a reliable, scalable, and maintainable logging solution that can grow with our architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03bdd2302dbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/logging-architecture-comparison-document-summary-serilog-is-the-best-option-03bdd2302dbf">Logging Architecture Comparison Document

	
		
Summary – Serilog is the best option.</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Plan: Logging in Nx Monorepo with TypeScript and .NET Core]]></title>
            <link>https://medium.com/best-practise/integration-plan-logging-in-nx-monorepo-with-typescript-and-net-core-cd26e610a354?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/cd26e610a354</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:41:14 GMT</pubDate>
            <atom:updated>2024-10-14T17:22:40.678Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building a Centralized Logging Solution in Nx Monorepo with TypeScript and .NET Core</strong></h3><p>To create a reusable and interchangeable logging library within an Nx monorepo, the key is to design the library with flexibility in mind, allowing the underlying logging implementation to be swapped out without changing the consuming code. This approach promotes centralization and reuse across different parts of the monorepo.<br><br>Best Practices for React Logging and Error Handling<br>Use Error Boundaries: To catch errors in the UI rendering process and display fallback UIs.<br>Employ Try-Catch in Async Operations: To catch and handle errors during data fetching or any asynchronous code.<br>Centralized Error Logging: Use services like Sentry, LogRocket, or a custom backend service to collect and store logs for analysis.<br>Avoid Writing to Local Files: Instead of attempting to write logs directly to files in the browser, send them to a backend service where they can be stored securely.<br><br><br>Nx Monorepo (Frontend) - Logging Library in TypeScript:<br>plaintext<br>Copy code<br>libs/<br>├── logging/<br>│ ├── src/<br>│ │ ├── index.ts<br>│ │ ├── logger.ts<br>│ │ ├── errors/<br>│ │ │ ├── AppError.ts<br>│ │ │ ├── ComponentRenderingError.ts<br>│ │ │ ├── NetworkRequestFailedError.ts<br>│ │ │ ├── ValidationError.ts<br>│ │ │ └── index.ts<br>│ │ ├── services/<br>│ │ │ ├── apiService.ts<br>│ ├── tsconfig.json<br>│ ├── package.json<br><br>Backend (.NET Core) - Logging Project:<br>plaintext<br>Copy code<br>src/<br>├── Logging/<br>│ ├── Grafana/<br>│ │ ├── GrafanaConfiguration.cs<br>│ ├── Prometheus/<br>│ │ ├── PrometheusMetricsMiddleware.cs<br>│ ├── Serilog/<br>│ │ ├── SerilogConfiguration.cs<br>│ ├── ErrorHandling/<br>│ │ ├── ErrorHandlingMiddleware.cs<br>│ ├── LoggingService.cs<br>│ ├── Models/<br>│ │ ├── AppError.cs<br>│ │ ├── DatabaseConnectionError.cs<br>│ │ ├── ValidationError.cs<br>│ ├── Program.cs<br>│ ├── Startup.cs<br>│ ├── appsettings.json<br>└── backend.sln<br><br>2. Integration Details<br><br>1. Library Structure<br>The logging library should be modular and follow the dependency injection (DI) pattern, making it easy to replace or extend the logging implementation.<br>2. Define the ILogger Interface<br>This interface ensures that all logging implementations adhere to a consistent API, making it easy to swap between different logging providers.<br>typescript<br>Copy code<br>// libs/logging/src/ILogger.ts<br>export interface ILogger {<br> logInfo(message: string, data?: any): void;<br> logError(message: string, error?: any): void;<br> logWarning(message: string, data?: any): void;<br> logDebug(message: string, data?: any): void;<br>}<br><br>3. Create the Logger Service<br>This service acts as the central logging hub, using the selected logging provider to perform the actual logging.<br>typescript<br>Copy code<br>// libs/logging/src/LoggerService.ts<br>import { ILogger } from &#39;./ILogger’;<br>import { LogProviderFactory } from &#39;./LogProviderFactory’;<br><br>export class LoggerService implements ILogger {<br> private logger: ILogger;<br><br> constructor() {<br> this.logger = LogProviderFactory.getLogger();<br> }<br><br> logInfo(message: string, data?: any): void {<br> this.logger.logInfo(message, data);<br> }<br><br> logError(message: string, error?: any): void {<br> this.logger.logError(message, error);<br> }<br><br> logWarning(message: string, data?: any): void {<br> this.logger.logWarning(message, data);<br> }<br><br> logDebug(message: string, data?: any): void {<br> this.logger.logDebug(message, data);<br> }<br>}<br><br>4. Implement Different Logging Providers<br>Each logging provider implements the ILogger interface, allowing you to switch between different logging mechanisms.<br>Console Logger Example:<br>typescript<br>Copy code<br>// libs/logging/src/providers/ConsoleLogger.ts<br>import { ILogger } from &#39;../ILogger’;<br><br>export class ConsoleLogger implements ILogger {<br> logInfo(message: string, data?: any): void {<br> console.info(`[INFO]: ${message}`, data);<br> }<br><br> logError(message: string, error?: any): void {<br> console.error(`[ERROR]: ${message}`, error);<br> }<br><br> logWarning(message: string, data?: any): void {<br> console.warn(`[WARNING]: ${message}`, data);<br> }<br><br> logDebug(message: string, data?: any): void {<br> console.debug(`[DEBUG]: ${message}`, data);<br> }<br>}<br><br>LogLevel Logger Example:<br>typescript<br>Copy code<br>// libs/logging/src/providers/LogLevelLogger.ts<br>import { ILogger } from &#39;../ILogger’;<br>import log from &#39;loglevel’;<br><br>export class LogLevelLogger implements ILogger {<br> logInfo(message: string, data?: any): void {<br> log.info(message, data);<br> }<br><br> logError(message: string, error?: any): void {<br> log.error(message, error);<br> }<br><br> logWarning(message: string, data?: any): void {<br> log.warn(message, data);<br> }<br><br> logDebug(message: string, data?: any): void {<br> log.debug(message, data);<br> }<br>}<br><br>5. Create a Logger Provider Factory<br>The factory selects the appropriate logging provider based on configuration, ensuring that the selected provider is used throughout the application.<br>typescript<br>Copy code<br>// libs/logging/src/LogProviderFactory.ts<br>import { ILogger } from &#39;./ILogger’;<br>import { ConsoleLogger } from &#39;./providers/ConsoleLogger’;<br>import { LogLevelLogger } from &#39;./providers/LogLevelLogger’;<br>// Import other loggers as needed<br><br>export class LogProviderFactory {<br> static getLogger(): ILogger {<br> const loggerType = process.env.LOGGER_PROVIDER || &#39;console’;<br><br> switch (loggerType) {<br> case &#39;loglevel’:<br> return new LogLevelLogger();<br> case &#39;console’:<br> default:<br> return new ConsoleLogger();<br> }<br> }<br>}<br><br>6. Configuration for Logging Provider<br>Configuration can be done via environment variables, a configuration file, or directly in the code.<br>typescript<br>Copy code<br>// libs/logging/src/LogConfig.ts<br>export const LogConfig = {<br> provider: process.env.LOGGER_PROVIDER || &#39;console’,<br>};<br><br>7. Usage in the Application<br>In any part of your application, you can import the LoggerService and start logging without worrying about the underlying implementation.<br>typescript<br>Copy code<br>// apps/my-app/src/App.tsx<br>import React, { useEffect } from &#39;react’;<br>import { LoggerService } from &#39;@my-org/logging’;<br><br>const logger = new LoggerService();<br><br>const App = () =&gt; {<br> useEffect(() =&gt; {<br> logger.logInfo(’App mounted’);<br> }, []);<br><br> return &lt;div&gt;Hello, World!&lt;/div&gt;;<br>};<br><br>export default App;<br><br>8. Testing and Extending<br>•	Testing: You can mock ILogger in tests to verify logging behavior without relying on a specific implementation.<br>•	Extending: To add a new logging provider, simply implement the ILogger interface and add it to the LogProviderFactory.<br>Summary<br>This plan provides a robust, centralized, and flexible logging solution within an Nx monorepo. By abstracting the logging implementation behind an interface and using a factory to select the appropriate logger, you ensure that the logging can be easily changed or extended without affecting the consuming code. This approach promotes reusability and maintainability across the entire monorepo.<br><br>Frontend - Logging Library in TypeScript (Nx Monorepo):<br>•	Error Classes (errors/):<br>o	Define custom error classes to represent various types of client-side errors (e.g., ComponentRenderingError, NetworkRequestFailedError).<br>•	Logger (logger.ts):<br>o	Central logging utility that can be imported and used across different applications within the monorepo. This module can handle different logging levels (e.g., info, error, debug).<br>•	API Service (services/apiService.ts):<br>o	Wrap API calls with error handling logic. Use try-catch blocks to capture errors and log them using the logging library.<br>Backend - Logging Project in .NET Core:<br>•	Grafana Integration (GrafanaConfiguration.cs):<br>o	Set up Grafana configuration for visualizing logs and metrics. Ensure that logs from Serilog can be visualized and monitored in Grafana.<br>•	Prometheus Integration (PrometheusMetricsMiddleware.cs):<br>o	Create a middleware to capture and expose metrics to Prometheus. These metrics can then be visualized in Grafana.<br>•	Serilog Configuration (SerilogConfiguration.cs):<br>o	Configure Serilog to handle logging in .NET Core, integrating it with sinks that forward logs to files, Elasticsearch, or directly to Grafana.<br>•	Error Handling Middleware (ErrorHandlingMiddleware.cs):<br>o	Middleware that catches all unhandled exceptions, logs them using Serilog, and returns standardized error responses.<br>•	Logging Service (LoggingService.cs):<br>o	Centralize logging logic in a service that other parts of the application can use. This service will use Serilog for logging and will be configurable to send logs to various sinks (e.g., file, console, Elasticsearch).<br>Explanation:<br>•	Frontend - Logging Library (TypeScript in Nx Monorepo):<br>o	libs/logging: Centralized logging library shared across the monorepo.<br>o	errors/: Contains all custom error classes specific to the frontend.<br>o	services/apiService.ts: Handles API-related errors and uses the logging library for consistent logging.<br>•	Backend - Logging Project (.NET Core):<br>o	Grafana/: Configuration for integrating logs and metrics with Grafana.<br>o	Prometheus/: Middleware to expose metrics to Prometheus.<br>o	Serilog/: Configuration for handling logging in .NET Core.<br>o	ErrorHandling/: Middleware that catches and logs errors, standardizing the error response.<br>o	LoggingService.cs: A central service that handles all logging tasks, configurable to send logs to various sinks (e.g., file, console, Elasticsearch).<br>4. Implementation and Deployment<br>•	Frontend (Nx Monorepo):<br>o	Implement the logging library as a shared Nx library to be used across all frontend applications.<br>o	Ensure that API services and error boundaries are properly integrated with the logging library.<br>•	Backend (.NET Core):<br>o	Implement the separate logging project, integrating it with the existing backend services.<br>o	Configure Serilog to send logs to your chosen sinks (file, Elasticsearch, etc.) and expose metrics through Prometheus.<br>5. Monitoring and Maintenance<br>•	Grafana and Prometheus:<br>o	Use Grafana to visualize both logs and metrics collected by Prometheus, ensuring a comprehensive monitoring solution.<br>o	Regularly review and update the logging configuration to ensure it meets the evolving needs of the system.<br><br>Explanation:<br>•	Frontend Components:<br>o	ErrorBoundary.jsx: Catches rendering errors and logs them using ComponentRenderingError.js.<br>o	apiService.js: Handles and logs errors from API calls using NetworkRequestFailedError.js.<br>o	logger.js: Central logging utility that sends logs to a centralized logging service.<br>•	Backend Components:<br>o	ErrorHandlingMiddleware.cs: Middleware that catches all exceptions, creates corresponding error objects, and logs them.<br>o	LoggingService.cs: Service responsible for logging exceptions, integrating with centralized log storage.<br>o	Models/: Contains custom error classes like AppError.cs, DatabaseConnectionError.cs, and ValidationError.cs.<br>•	Centralized Log Storage and Monitoring:<br>o	Centralized Logging Service: Receives logs from both frontend and backend and stores them in a centralized log storage system.<br>o	Monitoring Dashboard: Analyzes logs for insights and alerts.<br><br><br>Comparison of Logging Tools<br>Below is a comparison table that outlines the key features, benefits, and considerations for different logging tools, helping the CTO make an informed decision.<br><br><br><br><br>Key Considerations<br>•	Ease of Setup vs. Customization: Datadog and Azure Application Insights are easier to set up but offer less customization compared to open-source tools like Grafana + Prometheus + Loki or the ELK Stack.<br>•	Scalability: All tools are scalable, but the level of management required varies. Azure and Datadog provide managed services, while open-source solutions require manual scaling and management.<br>•	Cost: Open-source tools have lower upfront costs but may require more resources to manage. Datadog and Azure offer managed services at a higher price, which may be more cost-effective depending on the organization’s needs.<br>•	Integration: All tools integrate with .NET Core and TypeScript, but the level of effort varies. Datadog and Azure offer the easiest integration, while open-source tools require more setup.<br>•	Vendor Lock-in: Datadog and Azure involve higher vendor lock-in, while open-source tools provide more flexibility and control.<br>Recommended Approach<br>•	Datadog is recommended for organizations seeking a comprehensive, easy-to-use platform that integrates logs, metrics, and monitoring in one tool. It’s ideal if the team wants minimal setup and management overhead, though it comes at a higher cost.<br>•	Grafana + Prometheus + Loki is ideal for teams that need a customizable solution with strong visualization capabilities. It’s suitable for those with the expertise to manage and configure the stack.<br>•	ELK Stack is best for organizations that need advanced log analysis and full control over their logging infrastructure. It’s powerful but requires significant setup and management.<br>•	Azure Application Insights is perfect for applications already hosted on Azure, providing seamless integration with Azure services and easy setup, though with a dependency on the Azure ecosystem.<br>•	Custom Tool is suitable when specific requirements cannot be met by existing tools. It offers the highest level of customization but requires significant development and maintenance effort.<br>This comparison should help the CTO make an informed decision based on the organization’s specific needs, priorities, and resources.<br><br>Comparison of Logging Tools<br>Below is a comparison table that outlines the key features, benefits, and considerations for different logging tools, helping the CTO make an informed decision.<br>Feature	Datadog	Grafana + Prometheus + Loki	ELK Stack (Elasticsearch, Logstash, Kibana)	Azure Application Insights	Custom Tool<br>Type	Full-stack Monitoring Platform	Open-source Metrics &amp; Logging Stack	Open-source Log Management &amp; Analysis Stack	Cloud-based Monitoring &amp; Application Insights	Tailored Solution<br>Logging Capabilities	Advanced (logs, metrics, traces)	Logs &amp; Metrics	Logs, Metrics &amp; Full-text Search	Logs, Metrics, Traces	Customizable<br>Ease of Setup	Easy, Minimal Setup Required	Moderate, Requires Manual Configuration	Complex, Requires Detailed Setup	Easy, Integrated with Azure Ecosystem	Variable, Depends on Implementation<br>Customization	Limited to Platform Capabilities	High, Highly Customizable	High, Highly Customizable	Moderate, Integrated with Azure	Very High, Fully Tailored to Needs<br>Scalability	High, Auto-Scaling Available	High, Requires Management	High, Requires Management	High, Managed by Azure	Variable, Depends on Implementation<br>Visualization	Built-in Dashboards, Real-time	Grafana Dashboards	Kibana Dashboards	Built-in, Integrated with Azure Services	Custom Dashboards<br>Alerting	Integrated Alerts, AI-based Anomaly Detection	Prometheus Alerts, Grafana Alerts	Elasticsearch Alerts, Kibana Alerts	Integrated Alerts	Customizable Alerts<br>Cost	Starts at $15/host/month + $1.27/million log events	Free (Open-source), Grafana Cloud starts at $49/month	Free (Open-source), Elastic Cloud starts at $16/month	$2.76/GB of data ingested	Variable, Development &amp; Infrastructure Costs<br>Data Retention	Configurable, Limited by Plan	Configurable, Depends on Storage Backend	Configurable, Elasticsearch Storage Policies	Configurable, Azure-based	Customizable<br>Security &amp; Compliance	Built-in Security Features, SOC 2, GDPR, HIPAA	Dependent on Deployment, Can Be Secured	Dependent on Deployment, Can Be Secured	Integrated with Azure Security	Fully Customizable, Requires Custom Implementation<br>Integration with .NET Core	Strong, Native SDKs Available	Moderate, Requires Configuration	Moderate, Requires Configuration	Strong, Native SDKs and Azure Integration	Fully Customizable, Requires Development<br>Integration with TypeScript	Strong, Native SDKs Available	Moderate, Requires Configuration	Moderate, Requires Configuration	Moderate, Requires Azure SDK Integration	Fully Customizable, Requires Development<br>Vendor Lock-in	High, Proprietary Platform	Low, Open-source	Low, Open-source	High, Tied to Azure Ecosystem	None, Fully Controlled by the Organization<br>Support &amp; Community	Commercial Support, Strong Community	Open-source Community, Optional Paid Support	Open-source Community, Optional Paid Support	Microsoft Support, Azure Community	Internal Support &amp; Community<br>Learning Curve	Low, User-friendly Interface	Moderate, Requires Familiarity with Grafana &amp; Prometheus	High, Requires Knowledge of Elasticsearch &amp; Kibana	Low, Azure Integration Simplifies Learning	High, Depends on the Complexity of Implementation<br><br>Key Considerations<br>•	Ease of Setup vs. Customization: Datadog and Azure Application Insights are easier to set up but offer less customization compared to open-source tools like Grafana + Prometheus + Loki or the ELK Stack.<br>•	Scalability: All tools are scalable, but the level of management required varies. Azure and Datadog provide managed services, while open-source solutions require manual scaling and management.<br>•	Cost: Open-source tools have lower upfront costs but may require more resources to manage. Datadog and Azure offer managed services at a higher price, which may be more cost-effective depending on the organization’s needs.<br>•	Integration: All tools integrate with .NET Core and TypeScript, but the level of effort varies. Datadog and Azure offer the easiest integration, while open-source tools require more setup.<br>•	Vendor Lock-in: Datadog and Azure involve higher vendor lock-in, while open-source tools provide more flexibility and control.<br>Recommended Approach<br>•	Datadog is recommended for organizations seeking a comprehensive, easy-to-use platform that integrates logs, metrics, and monitoring in one tool. It’s ideal if the team wants minimal setup and management overhead, though it comes at a higher cost.<br>•	Grafana + Prometheus + Loki is ideal for teams that need a customizable solution with strong visualization capabilities. It’s suitable for those with the expertise to manage and configure the stack.<br>•	ELK Stack is best for organizations that need advanced log analysis and full control over their logging infrastructure. It’s powerful but requires significant setup and management.<br>•	Azure Application Insights is perfect for applications already hosted on Azure, providing seamless integration with Azure services and easy setup, though with a dependency on the Azure ecosystem.<br>•	Custom Tool is suitable when specific requirements cannot be met by existing tools. It offers the highest level of customization but requires significant development and maintenance effort.<br>This comparison should help the CTO make an informed decision based on the organization’s specific needs, priorities, and resources.<br><br><br>Summary:<br>This plan integrates a robust logging and error handling solution across both the frontend and backend, utilizing TypeScript for the frontend library and .NET Core for the backend. The solution is designed to be scalable, maintainable, and aligned with industry best practices, ensuring that your applications are well-monitored and resilient to errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd26e610a354" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/integration-plan-logging-in-nx-monorepo-with-typescript-and-net-core-cd26e610a354">Integration Plan: Logging in Nx Monorepo with TypeScript and .NET Core</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Team Retrospective Template
Date:
[Insert Date]
Project/Sprint:
[Project Name or Sprint…]]></title>
            <link>https://medium.com/best-practise/team-retrospective-template-date-insert-date-project-sprint-project-name-or-sprint-number-0ef75da79f49?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/0ef75da79f49</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:41:01 GMT</pubDate>
            <atom:updated>2024-10-14T17:22:22.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Team Retrospective Template</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*uZ5HaL4WvGmZRZYGPvS7fQ.png" /></figure><p><strong>Date: </strong>[Insert Date]</p><p><strong>Project/Sprint: </strong>[Project Name or Sprint Number]</p><p><strong>Participants: </strong>[List team members]</p><p><strong>Duration:</strong></p><p>A 1-hour retrospective is a good starting point. Adjust based on team size and sprint complexity. Smaller teams or shorter sprints might need less time, while larger teams or more complex projects may benefit from 90 minutes.</p><p><strong>Essential Participants:</strong></p><ul><li>Development Team (including Scrum Master/Agile Coach and Product Owner)</li><li>Optional: Other stakeholders who offer valuable insights or are impacted by the team’s work.</li></ul><p><strong>Opening (5 minutes)</strong></p><ul><li><strong>Check-in:</strong> A quick round to share how everyone is feeling today. (One word or phrase)</li><li><strong>Review Purpose:</strong> Briefly reiterate the goal of the retrospective.</li></ul><p><strong>Data Gathering (15 minutes)</strong></p><ul><li><strong>Start, Stop, Continue:</strong></li><li><strong>Start:</strong> What should we start doing that we aren’t currently?</li><li><strong>Stop:</strong> What should we stop doing that isn’t working?</li><li><strong>Continue:</strong> What should we continue doing that is working well?</li><li><strong>Alternative Options:</strong> (Choose one or combine)</li><li><strong>Timeline:</strong> Map out key events from the sprint on a timeline. Discuss high/low points.</li><li><strong>Mad, Sad, Glad:</strong> Share things that made you feel these emotions during the sprint.</li><li><strong>Sailboat:</strong> Identify anchors (obstacles), wind (helping forces), and rocks (risks) to guide the discussion.</li></ul><p><strong>Discussion and Insights (20 minutes)</strong></p><ul><li><strong>Discuss the gathered data:</strong></li><li>Focus on common themes.</li><li>Prioritize areas for action.</li><li><strong>Key Questions to Consider:</strong></li><li>What did we learn?</li><li>What can we improve?</li><li>What went well that we should recognize and repeat?</li></ul><p><strong>Action Planning (15 minutes)</strong></p><ul><li><strong>Identify SMART Action Items:</strong></li><li><strong>Specific</strong></li><li><strong>Measurable</strong></li><li><strong>Achievable</strong></li><li><strong>Relevant</strong></li><li><strong>Time-bound</strong></li><li><strong>Assign Ownership:</strong> Set deadlines for each action item.</li></ul><p><strong>Closing (5 minutes)</strong></p><ul><li><strong>Appreciations:</strong> Share positive feedback or acknowledgments to team members.</li><li><strong>Review Action Items:</strong> Confirm understanding and commitment.</li><li><strong>Set Expectations:</strong> Agree on follow-up and tracking progress on the action items.</li></ul><p><strong>Additional Tips:</strong></p><ul><li><strong>Facilitation:</strong> Rotate facilitators to ensure everyone gets a chance to lead.</li><li><strong>Time Management:</strong> Keep the retrospective on track and within the allotted time.</li><li><strong>Visual Aids:</strong> Use whiteboards, sticky notes, or online collaboration tools for visual representation.</li><li><strong>Psychological Safety:</strong> Create a safe space for honest feedback and open communication.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ef75da79f49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/team-retrospective-template-date-insert-date-project-sprint-project-name-or-sprint-number-0ef75da79f49">Team Retrospective Template
Date:
[Insert Date]
Project/Sprint:
[Project Name or Sprint…</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Syncing Databases in a Microservices Architecture: When, Why, and How]]></title>
            <link>https://medium.com/best-practise/syncing-databases-in-a-microservices-architecture-when-why-and-how-4971468a9ff2?source=rss----54150f9dc243---4</link>
            <guid isPermaLink="false">https://medium.com/p/4971468a9ff2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Gregory Tzvi Kaidanov]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 09:40:50 GMT</pubDate>
            <atom:updated>2024-10-14T17:21:56.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVvv5nvne6SEY57mwsv_zg.png" /></figure><p>In the modern software landscape, <strong>microservices architecture</strong> has become the go-to solution for creating scalable, resilient, and maintainable systems. Microservices break down monolithic applications into smaller, independent services that handle specific business capabilities, each with its own logic and, often, its own database. While this separation offers immense flexibility and scalability, it introduces a key challenge: <strong>data synchronization</strong> across different microservices and databases.</p><p>In this article, we’ll explore the various methods for syncing databases in a microservices architecture and when it’s better to choose database synchronization over APIs. We’ll also discuss real-world examples from the industry and how companies handle cross-domain database sync challenges.</p><h3>The Role of Microservices in Modern Architecture</h3><p>At its core, <strong>microservices architecture</strong> involves breaking an application down into distinct services that each handle a specific function. Each service manages its own data and communicates with other services through well-defined APIs. This enables:</p><ul><li><strong>Scalability</strong>: Each service can be scaled independently based on traffic and resource needs.</li><li><strong>Flexibility</strong>: Each microservice can be developed, deployed, and maintained independently.</li><li><strong>Resilience</strong>: Failure in one service doesn’t necessarily affect the entire system.</li></ul><p>However, the distributed nature of microservices brings data consistency challenges. If each service has its own database, how do you ensure <strong>data synchronization</strong> between these isolated systems, especially when business processes span across multiple domains?</p><h3>Database Sync vs. APIs: What’s the Difference?</h3><p>Before diving into the use cases for database synchronization, it’s important to understand the distinction between <strong>syncing databases</strong> and <strong>using APIs</strong> for communication between microservices.</p><ul><li><strong>API-Based Sync</strong>: APIs (Application Programming Interfaces) are typically used to <strong>request data on-demand</strong>. For example, if a microservice needs to retrieve customer details from another service, it sends an API request and waits for the response.</li><li><strong>Pros</strong>: Real-time, decouples services, easy to apply security policies.</li><li><strong>Cons</strong>: Adds latency, can be inefficient for bulk data, can be error-prone in high-traffic environments.</li><li><strong>Database Sync</strong>: Database synchronization refers to <strong>automatically syncing data between databases</strong>, often in real time or on a scheduled basis, without relying on API calls.</li><li><strong>Pros</strong>: Efficient for large data transfers, low latency, strong data consistency, and performance.</li><li><strong>Cons</strong>: More complex to manage, requires specialized tools, may introduce tight coupling if not properly handled.</li></ul><h3>When is Database Synchronization the Best Choice?</h3><p>APIs are excellent for lightweight, real-time interactions, but there are cases where <strong>database synchronization</strong> is the better approach. Let’s explore some of these scenarios.</p><h4>1. Handling Large Volumes of Data Efficiently</h4><p>When you need to transfer large volumes of data between microservices, such as syncing customer orders, sales reports, or IoT device data across different domains, APIs quickly become inefficient. In this case, direct database synchronization is the better choice.</p><p><strong>Example</strong>: In <strong>e-commerce platforms</strong>, it’s common to have a dedicated service for handling product inventory. Multiple services (such as order management, shipping, and warehouse systems) rely on this inventory data. Instead of sending frequent API calls for large datasets, companies often sync databases between the inventory and warehouse systems using database synchronization tools.</p><p><strong>Best Practice</strong>: Use database synchronization tools such as <strong>Change Data Capture (CDC)</strong> or <strong>ETL</strong> (Extract, Transform, Load) processes. Tools like <strong>Debezium</strong> or <strong>SQL Server Integration Services (SSIS)</strong> can capture changes in the source database and sync them in bulk to the target database.</p><h4>2. Real-Time Synchronization for Mission-Critical Data</h4><p>In industries like <strong>finance</strong> or <strong>healthcare</strong>, real-time data synchronization between microservices is crucial. For instance, a financial system may need to sync transaction data across different services to ensure that all parts of the system reflect the latest state.</p><p><strong>Example</strong>: A <strong>stock trading platform</strong> processes thousands of transactions per second. In such an environment, APIs may struggle to handle the sheer volume of requests for syncing account balances between the transaction service and the customer service. Instead, <strong>real-time database replication</strong> using tools like <strong>Oracle GoldenGate</strong> ensures sub-second latency, enabling each service to have up-to-date information without the bottleneck of API requests.</p><p><strong>Best Practice</strong>: Use <strong>database replication</strong> for real-time updates, especially when high availability and immediate data consistency are required. Tools like <strong>GoldenGate</strong> or <strong>Apache Kafka with Debezium</strong> can replicate data changes instantly across microservices.</p><h4>3. Achieving Strong Data Consistency Across Microservices</h4><p>Ensuring <strong>data consistency</strong> between microservices is one of the most critical challenges in a distributed system. When multiple services rely on shared data (e.g., order fulfillment and billing services in an e-commerce platform), inconsistency can lead to critical issues.</p><p><strong>Example</strong>: In <strong>ride-sharing platforms</strong> like <strong>Uber</strong> or <strong>Lyft</strong>, various services (such as ride booking, driver management, and payments) need to share data about customer trips, driver availability, and billing. Inconsistent data could lead to overbooking or incorrect billing. To ensure <strong>eventual consistency</strong>, ride-sharing companies use a combination of <strong>database synchronization</strong> and <strong>event-driven architectures</strong> to ensure all systems eventually sync, without the need for complex API logic.</p><p><strong>Best Practice</strong>: Implement <strong>event-driven database synchronization</strong> with <strong>event streaming platforms</strong> like <strong>Kafka</strong>. By using event sourcing, each service can publish and subscribe to changes, ensuring eventual consistency across all services.</p><h4>4. Legacy System Integration</h4><p>Legacy systems are often tightly coupled with their databases and don’t expose modern APIs. When integrating legacy systems with modern microservices, direct database synchronization is often the only viable approach.</p><p><strong>Example</strong>: In the <strong>banking industry</strong>, many core systems are legacy mainframes with proprietary databases. Modernizing these systems by integrating them with new microservices (e.g., mobile banking) often requires direct database synchronization. For example, <strong>JP Morgan</strong> relies on <strong>GoldenGate</strong> to sync legacy core banking systems with modern payment gateways.</p><p><strong>Best Practice</strong>: Use <strong>ETL</strong> tools or <strong>CDC</strong> technologies like <strong>Oracle GoldenGate</strong> or <strong>Attunity Replicate</strong> to sync databases between legacy systems and microservices. This approach avoids API complexity and ensures that legacy systems are seamlessly integrated with modern services.</p><h4>5. High Availability and Disaster Recovery</h4><p>Database synchronization is essential for ensuring <strong>high availability</strong> and <strong>disaster recovery</strong> in microservices. Having synchronized databases allows you to maintain a secondary, failover system that can immediately take over if the primary system goes down.</p><p><strong>Example</strong>: <strong>Netflix</strong>, one of the largest users of microservices, leverages <strong>Cassandra</strong> and <strong>DynamoDB</strong> for its distributed database architecture. These databases are replicated across multiple regions to ensure that, if one data center goes down, another region can take over seamlessly.</p><p><strong>Best Practice</strong>: Use <strong>multi-region database replication</strong> tools like <strong>Cassandra</strong>, <strong>GoldenGate</strong>, or <strong>DynamoDB Streams</strong> to ensure high availability. These systems can automatically sync data across regions and provide failover capabilities.</p><h3>Common Tools for Database Synchronization</h3><ul><li><strong>Debezium</strong>: An open-source CDC (Change Data Capture) tool that integrates with Kafka for event-driven database synchronization. Ideal for capturing real-time changes in databases like MySQL, PostgreSQL, and SQL Server.</li><li><strong>Oracle GoldenGate</strong>: A high-performance tool for real-time data integration, replication, and transactional change data capture across heterogeneous environments.</li><li><strong>SQL Server Integration Services (SSIS)</strong>: A built-in Microsoft tool for ETL processes that allows you to extract, transform, and load data between SQL Server and other databases.</li><li><strong>Apache Kafka</strong>: A distributed streaming platform that can be used in combination with CDC tools like Debezium to provide real-time, event-driven sync between databases.</li></ul><h3>When to Use APIs Instead of Database Synchronization</h3><p>While database synchronization is powerful, there are situations where APIs make more sense:</p><ol><li><strong>Real-Time User Interactions</strong>: If a service needs immediate data for real-time user requests (e.g., search queries), APIs are more suitable.</li><li><strong>Microservice Communication</strong>: APIs help decouple services, allowing them to request data only when needed, reducing unnecessary data syncs.</li><li><strong>Security and Access Control</strong>: APIs allow for granular security policies, enabling authentication and authorization at a more detailed level.</li><li><strong>Dynamic Data</strong>: APIs are ideal for retrieving frequently changing data or small, dynamic data sets, where syncing entire databases would be inefficient.</li></ol><h3>Conclusion: Database Synchronization in a Microservices World</h3><p>In a microservices architecture, <strong>database synchronization</strong> offers an efficient and scalable way to handle large volumes of data, maintain real-time consistency, and ensure high availability. By using the right tools and strategies — such as <strong>Change Data Capture (CDC)</strong>, <strong>ETL</strong>, and <strong>database replication</strong> — you can overcome many of the data challenges that arise from distributed systems.</p><p>However, it’s essential to know when to use <strong>database synchronization</strong> and when to opt for <strong>API-based</strong> communication. In many cases, combining both approaches can yield the best results, ensuring data integrity while maintaining flexibility and scalability.</p><p>As the industry continues to evolve, finding the right balance between <strong>APIs</strong> and <strong>database synchronization</strong> will be key to building reliable and scalable microservices systems.</p><h3>Best Practices for Database Synchronization (Without APIs)</h3><p>When syncing tables between databases without using APIs, the approach typically depends on the use case, volume of data, and performance requirements. The following are <strong>best practices</strong> for synchronizing tables directly between databases:</p><h3>1. Asynchronous, Event-Driven Synchronization</h3><ul><li><strong>Best Practice</strong>: Use <strong>Change Data Capture (CDC)</strong> or <strong>event-driven architectures</strong> like <strong>Debezium</strong> or <strong>Kafka</strong> to track changes in the source database (e.g., SQL Server) and propagate them to the target database (e.g., Oracle).</li><li><strong>How It Works</strong>: Tools like Debezium capture data changes (inserts, updates, deletes) in real-time and propagate them to the target database.</li><li><strong>Benefits</strong>:</li><li><strong>Low Latency</strong>: Near real-time updates between databases.</li><li><strong>Scalability</strong>: Easily scales as more tables and services need syncing.</li><li><strong>Decoupling</strong>: Keeps the source and target databases loosely coupled, aligning with microservice principles.</li></ul><h3>2. Periodic Synchronization via ETL (Extract, Transform, Load)</h3><ul><li><strong>Best Practice</strong>: Use ETL tools (e.g., <strong>SQL Server Integration Services (SSIS)</strong>, <strong>Azure Data Factory</strong>) for periodic synchronization between databases.</li><li><strong>How It Works</strong>: Data is extracted from the source database, optionally transformed, and then loaded into the target database at regular intervals (e.g., hourly, daily).</li><li><strong>Benefits</strong>:</li><li><strong>Cost-Effective</strong>: Useful for syncing large volumes of data at scheduled intervals.</li><li><strong>Flexibility</strong>: Ideal for less time-sensitive data, such as warehouses or aggregated data.</li></ul><h3>3. Database Replication</h3><ul><li><strong>Best Practice</strong>: For high-availability or redundancy needs, use <strong>database replication</strong> (e.g., <strong>SQL Server Replication</strong> or <strong>Oracle GoldenGate</strong>) to synchronize tables between databases.</li><li><strong>How It Works</strong>: Replication keeps a near real-time copy of the data in the target database by propagating changes as they occur.</li><li><strong>Benefits</strong>:</li><li><strong>Real-Time Updates</strong>: Ensures real-time or near real-time replication of data.</li><li><strong>Fault Tolerance</strong>: Provides redundancy and failover capabilities.</li></ul><h3>4. Use Materialized Views (for Read-Only Data)</h3><ul><li><strong>Best Practice</strong>: For read-heavy, less frequently changing data, use <strong>materialized views</strong> in the target database.</li><li><strong>How It Works</strong>: Materialized views are periodically refreshed from the source database.</li><li><strong>Benefits</strong>:</li><li><strong>Performance</strong>: Reduces load on the source database by caching the data in the target system.</li><li><strong>Simple to Implement</strong>: Minimal configuration and management.</li></ul><h3>5. Conflict Handling and Idempotency</h3><ul><li><strong>Best Practice</strong>: Ensure conflict handling mechanisms are in place if both databases may make changes. Use <strong>idempotent operations</strong> to ensure that reapplying the same data does not cause issues (e.g., duplicate entries).</li><li><strong>Benefits</strong>:</li><li><strong>Data Consistency</strong>: Avoids issues like duplicate data or failed syncs.</li><li><strong>Stability</strong>: Ensures that retrying a failed sync does not introduce inconsistencies.</li></ul><h3>Explanation of Mermaid Diagram:</h3><ul><li><strong>Source DB (SQL Server)</strong>: This is where the data originates.</li><li><strong>Debezium + Kafka</strong>: Captures real-time changes in the source database and uses Kafka to broadcast these changes asynchronously.</li><li><strong>Target DB (Oracle)</strong>: The destination where the synchronized data resides.</li><li><strong>ETL (SSIS)</strong>: A periodic synchronization process that extracts and loads data at scheduled intervals.</li><li><strong>GoldenGate Replication</strong>: Real-time replication mechanism for high-availability use cases.</li><li><strong>Materialized View</strong>: Periodically refreshed view for less dynamic, read-heavy data.</li></ul><h3>Conclusion:</h3><p>For a best-practice database sync strategy without using APIs:</p><ol><li>Use <strong>Debezium with Kafka</strong> for real-time, event-driven sync.</li><li>Apply <strong>ETL jobs (SSIS)</strong> for periodic sync of non-critical data.</li><li>Use <strong>GoldenGate</strong> for high-availability or critical real-time replication.</li><li>Utilize <strong>materialized views</strong> for caching read-heavy, less frequently updated data.</li><li>Implement <strong>idempotent sync</strong> and conflict resolution mechanisms for data integrity.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4971468a9ff2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/best-practise/syncing-databases-in-a-microservices-architecture-when-why-and-how-4971468a9ff2">Syncing Databases in a Microservices Architecture: When, Why, and How</a> was originally published in <a href="https://medium.com/best-practise">Best practise</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>