<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kharavela Jain on Medium]]></title>
        <description><![CDATA[Stories by Kharavela Jain on Medium]]></description>
        <link>https://medium.com/@kharavela.jain?source=rss-45162d69610------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LJkO4aYBirudVSU0</url>
            <title>Stories by Kharavela Jain on Medium</title>
            <link>https://medium.com/@kharavela.jain?source=rss-45162d69610------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:04:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kharavela.jain/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Quantum Intelligence: The Autonomous Future]]></title>
            <link>https://medium.com/@kharavela.jain/quantum-intelligence-the-autonomous-future-f6defe2f3ffd?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6defe2f3ffd</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[technology-leadership]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 13:52:42 GMT</pubDate>
            <atom:updated>2026-09-21T13:52:42.640Z</atom:updated>
            <content:encoded><![CDATA[<p>Navigating the Next Frontier: Quantum Intelligence and Autonomous Systems</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iu4a4Xugxrg7hDCorq_7QQ.jpeg" /></figure><blockquote>TL;DR;</blockquote><blockquote>The AI revolution will change how we work. <br>The Quantum revolution will change what is possible. <br>Together, they will redefine the very foundations of digital innovation.<br>Are we preparing our organizations, systems, and people to lead this transition?</blockquote><p>The technology landscape is entering another inflection point.</p><p>Over the past decade, cloud computing has reshaped infrastructure, data has become central to digital products, and Artificial Intelligence has moved from experimentation to a strategic business capability. Looking ahead, three areas are increasingly gaining attention: Quantum Computing, Agentic AI, and Trustworthy Autonomous Systems.</p><p>Each of these technologies has significant potential on its own. Together, they could influence how organizations innovate, make decisions, and create value.</p><p>While some developments are already reflected in industry trends, others are still emerging. This makes it important for technology leaders to stay informed, assess their relevance, and prepare for potential impact.</p><h3>Quantum Computing Is Moving from Scientific Curiosity to Strategic Imperative</h3><p>Quantum computing is moving from a research frontier toward an area of active technological exploration. Major technology companies, governments, and research institutions are investing heavily in quantum hardware, networking, and algorithms. Organizations including IBM, Microsoft, Google, Amazon, and Quantinuum are helping advance the ecosystem, while practical applications continue to emerge.</p><p>The near-term opportunity may not be broad quantum advantage across every business problem. Instead, one of the most relevant early implications is cybersecurity: sufficiently capable quantum systems could eventually challenge today’s widely used cryptographic standards.</p><p>This is driving growing interest in Post-Quantum Cryptography (PQC) and in understanding how quantum-safe approaches could be incorporated into existing technology landscapes.</p><h3>Leadership insight</h3><p>The first significant enterprise impact of quantum computing may be less about optimization or simulation — and more about security transformation.<br>Technology leaders can begin exploring questions such as:</p><ul><li>How long does our sensitive data need to remain secure?</li><li>Which products or systems will remain operational for more than 10 years?</li><li>What would a transition to quantum-safe architectures mean for connected-device ecosystems?</li><li>How could PQC affect digital identity, PKI, and secure software updates?</li></ul><p>For sectors with long product lifecycles — such as healthcare, medical devices, manufacturing, and critical infrastructure — early exploration can help inform future technology and security roadmaps.</p><h3>Agentic AI Will Transform How Work Gets Done</h3><p>The industry has moved beyond conversational AI.<br>Organizations are increasingly experimenting with autonomous agents capable of planning, reasoning, coordinating tasks, and interacting with other systems.</p><p>Analyst firms such as Gartner have predicted significant growth in Agentic AI capabilities within enterprise applications over the next several years.</p><h3>Leadership Insight</h3><p>Most organizations still think about AI as a productivity tool. The next wave will treat AI as a digital workforce.</p><p>Future enterprise platforms may include:</p><ul><li>Regulatory compliance agents</li><li>Clinical workflow agents</li><li>Research assistants</li><li>Software engineering agents</li><li>Supply-chain optimization agents</li><li>Customer journey orchestration agents</li></ul><p>The architectural challenge shifts from: <em>“How do we build AI features?” </em>to <em>“How do we govern thousands of autonomous decisions being made every day?”</em></p><p>Technology leaders must therefore focus equally on:</p><ul><li>AI capability</li><li>AI governance</li><li>AI observability</li><li>Human oversight</li><li>Accountability frameworks</li></ul><p>Autonomy without transparency will become unacceptable.</p><h3>The Rise of Quantum-AI Systems</h3><p>One of the most important technology trends of the next decade may not be Quantum Computing or AI individually. <br>It may be their convergence.<br>AI excels at prediction, pattern recognition, and decision-making. Quantum computing excels at exploring extraordinarily large solution spaces. Together they could enable entirely new categories of systems.<br>Potential examples include:</p><ul><li>Precision medicine optimization</li><li>Drug discovery acceleration</li><li>Molecular simulation</li><li>Healthcare resource allocation</li><li>Advanced manufacturing optimization</li><li>Large-scale logistics planning</li></ul><p>Although widespread commercial adoption remains uncertain, the convergence of AI and quantum optimization could become a defining innovation platform of the 2030s.<br>Organizations that develop foundational expertise early may gain a significant strategic advantage.</p><h3>Conclusion</h3><p>The next decade will be shaped by the convergence of intelligence, autonomy, security, and trust — not by a single technology.</p><p>Quantum Computing may expand what is computationally possible. Agentic AI may transform how work is done. Trustworthy Autonomous Systems will influence which innovations people and societies accept.</p><p>Success will depend not only on adopting these technologies, but on building the governance, architecture, and leadership to use them responsibly.</p><p>The key question is: <br>Are we preparing our organizations, systems, and people to lead this transition?</p><h4>References</h4><ul><li>NIST Post-Quantum Cryptography: <a href="https://www.nist.gov/pqc">https://www.nist.gov/pqc</a></li><li>NIST PQC Standards: <a href="https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards">https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards</a></li><li>AI and Future Healthcare reports: <a href="https://www.weforum.org/">https://www.weforum.org</a></li><li>IBM Quantum &amp; Supply Chain Optimization: <a href="https://www.ibm.com/thought-leadership/institute-business-value/en-us/report/quantum-computing-supplychain">https://www.ibm.com/thought-leadership/institute-business-value/en-us/report/quantum-computing-supplychain</a></li><li>IBM Quantum Optimization Research: <a href="https://research.ibm.com/projects/quantum-optimization">https://research.ibm.com/projects/quantum-optimization</a></li><li>Nature Scientific Reports (Quantum Drug Discovery): <a href="https://www.nature.com/articles/s41598-024-67897-8">https://www.nature.com/articles/s41598-024-67897-8</a></li><li>McKinsey Quantum in Pharma: <a href="https://www.mckinsey.com/industries/life-sciences/our-insights/the-quantum-revolution-in-pharma-faster-smarter-and-more-precise">https://www.mckinsey.com/industries/life-sciences/our-insights/the-quantum-revolution-in-pharma-faster-smarter-and-more-precise</a></li><li>OECD AI Principles : <a href="https://oecd.ai/en/ai-principles">https://oecd.ai/en/ai-principles</a></li><li>Stanford AI Index Report: <a href="https://aiindex.stanford.edu/">https://aiindex.stanford.edu</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6defe2f3ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Future Technology Landscape]]></title>
            <link>https://medium.com/@kharavela.jain/navigating-the-future-technology-landscape-8cd2ec0eb7bf?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd2ec0eb7bf</guid>
            <category><![CDATA[future-technology]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[technology-leadership]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Fri, 08 May 2026 13:01:51 GMT</pubDate>
            <atom:updated>2026-05-08T13:01:51.200Z</atom:updated>
            <content:encoded><![CDATA[<h4>Trends Shaping Our Future</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbUclV8SpVg9vY4G_aQS4A.png" /></figure><blockquote>TL;DR;</blockquote><blockquote>Several interconnected trends define our future direction:</blockquote><blockquote><strong>Sovereign Cloud Adoption</strong>: Hyperscalers now offer jurisdiction-specific deployments satisfying data localization requirements while maintaining global operational efficiency.</blockquote><blockquote><strong>AI Governance Frameworks</strong>: Organizations are establishing AI ethics boards and implementing Model Risk Management practices adapted from financial services.</blockquote><blockquote><strong>Quantum-Safe Migration</strong>: Crypto-agility — the ability to rapidly switch cryptographic algorithms — has become a core architectural requirement.</blockquote><blockquote><strong>Regulatory Technology (RegTech)</strong>: Automated compliance monitoring and reporting tools are essential infrastructure, not optional additions.</blockquote><p>As a technology enthusiast, I witness an unprecedented convergence of transformative technologies reshaping how enterprises operate, innovate, and compete. Three forces — <strong>Quantum Computing</strong>, <strong>Agentic AI</strong>, and <strong>Secure DevOps with Geofencing</strong> — are colliding with an increasingly complex regulatory environment, demanding a fundamental rethinking of our technology strategies.</p><h4>The Quantum Horizon: From Theory to Enterprise Reality</h4><p>Quantum computing has transitioned from laboratory curiosity to strategic imperative, powering hybrid systems that blend QPUs with CPUs and GPUs for tasks like materials simulation and risk modeling. In 2026, “quantum-centric supercomputing” emerges as the norm. IBM’s 1,000+ qubit processors and Google’s advances in error correction signal that quantum advantage for specific enterprise applications is no longer theoretical. Financial institutions are already deploying quantum algorithms for portfolio optimization, while pharmaceutical companies leverage quantum simulation for drug discovery.</p><p>However, quantum technology presents a dual challenge. Post-quantum cryptography has become urgent — current encryption standards face obsolescence as quantum systems mature. The National Institute of Standards and Technology (NIST) finalized post-quantum cryptographic standards in 2024, and organizations must now accelerate migration timelines. Companies ignoring this shift risk catastrophic data exposure when “harvest now, decrypt later” attacks materialize.</p><p>Export controls intensify this trend; nations like the US, Switzerland, and allies restrict quantum processors, cryogenics, and AI chips to China, accelerating domestic supply chains while prioritizing cryptographic agility.</p><h4>Agentic AI: Autonomous Systems Redefining Work</h4><p>The evolution from conversational AI to <strong>Agentic AI</strong> represents perhaps the most significant shift in enterprise technology. Unlike traditional AI assistants that respond to prompts, agentic systems autonomously plan, execute multi-step tasks, and adapt to changing conditions. Gartner predicts that by 2028, 33% of enterprise software applications will include agentic AI, up from less than 1% in 2024.</p><p>These systems are revolutionizing software development, customer service, and operational processes. AI agents now autonomously debug code, orchestrate complex workflows, and make real-time decisions within defined guardrails. Yet this autonomy introduces profound questions about accountability, transparency, and control. Human-in-the-loop architectures remain essential — not as bottlenecks, but as governance frameworks ensuring AI actions align with organizational values and regulatory requirements.</p><h4>Secure DevOps with Geofencing: Compliance by Design</h4><p>The regulatory landscape has grown extraordinarily complex. Organizations operating globally must simultaneously satisfy GDPR (European Union), DPDPA (India), HIPAA (United States healthcare), and various export control regimes including EAR and ITAR. These frameworks increasingly conflict, creating compliance contradictions that traditional approaches cannot resolve.</p><p>Secure DevOps, or DevSecOps, embeds security in pipelines with “policy as code,” automated compliance for ISO 27001/GDPR, and secret rotation via Vault. Modern Secure DevOps addresses this through geofencing-native architectures. Geofencing — policy-driven data placement — ensures residency via tagging, federated access, and encryption with localized keys, balancing multi-cloud agility and sovereignty.</p><p>Infrastructure-as-Code templates now include compliance guardrails, and policy-as-code frameworks like Open Policy Agent enable real-time enforcement of jurisdictional requirements. This approach transforms compliance from audit-driven checkbox exercise to continuous, automated assurance. Zero Trust architectures complement geofencing by assuming breach and verifying every access request regardless of origin. The convergence of DevSecOps practices with data sovereignty requirements represents a fundamental maturation of enterprise security.</p><h4>Focus for the New Technology Professionals</h4><p>For those entering this dynamic landscape, should master hybrid skills: Quantum basics (Qiskit, simulators) alongside agentic frameworks (narrow agents, orchestration). Dive into Secure DevOps — Ansible, Vault, GitOps — and compliance automation for GDPR/DPDPA/HIPAA, including geofencing tools. Prioritize PQC testing, policy-as-code, and observability; contribute to open-source pipelines. As agentic systems proliferate, professionals who can identify appropriate human oversight points and design effective human-AI collaboration models will prove indispensable.<br>Focus on interdisciplinary learning — AI ethics, quantum risks — to lead in this convergence.<br>The technology landscape rewards those who see connections others miss. The intersection of quantum security, autonomous AI systems, and compliance automation represents not just technical challenges, but opportunities to build trust, enable innovation, and create lasting competitive advantage.</p><h4>Conclusion</h4><p>In conclusion, the future technology landscape fuses quantum breakthroughs, agentic AI autonomy, and Secure DevOps resilience into a trust-engineered system, all geofenced against a complex web of regulations like GDPR, DPDPA, HIPAA, and export controls. This convergence promises 15–30% efficiency gains by 2030 through orchestrated automation and post-quantum safeguards, provided companies embed compliance as core architecture.</p><p>For new professionals entering this landscape, the message is clear: technical excellence alone is insufficient. The future belongs to those who can bridge disciplines, anticipate regulatory shifts, and design systems where autonomy and accountability coexist.</p><p>Ultimately, our mission remains unchanged — leveraging technology to solve meaningful problems and deliver superior value. What has changed is the sophistication required to do so responsibly. By embracing continuous learning, prioritizing security fundamentals, and maintaining human oversight over increasingly autonomous systems, we position ourselves not merely to survive disruption but to lead through it. The technology landscape of 2026 and beyond rewards adaptability, interdisciplinary thinking, and an unwavering commitment to building systems worthy of the trust our customers, colleagues, and communities place in us.</p><p><strong>References</strong></p><p><a href="https://www.idquantique.com/quantum-safe-security/migrating-to-quantum-safe-infrastructure/?gad_source=1&amp;gad_campaignid=23617568760&amp;gbraid=0AAAAADtPSyJKmu8ijgOY4oFt1H8_2IKb8&amp;gclid=Cj0KCQjwk_bPBhDXARIsACiq8R2mfu4Mz9qQigC_SEwGInNcAb5h5MF6gmzdrs6eQ9okKAm5OC7EYncaAqNvEALw_wcB">NIST Post-Quantum Cryptography Standards (2024)<br></a><a href="https://www.domo.com/learn/report/gartner-market-guide-for-agentic-analytics">Gartner “Agentic AI” Market Analysis (2025)</a><br><a href="https://www.edpb.europa.eu/our-work-tools/general-guidance/guidelines-recommendations-best-practices_en">European Data Protection Board Guidelines</a><br><a href="https://www.ibm.com/roadmaps/quantum/">IBM Quantum Roadmap </a><br><a href="https://www.spherity.com/post/q-day-and-agentic-ai-the-ultimate-nightmare-in-cybersecurity">Q-Day and Agentic AI: The Ultimate Nightmare in Cybersecurity</a><br><a href="https://cybersecurityasia.net/ai-quantum-and-web-4-0-collide-cybersecurity/">The 2026 Tech Tsunami: AI, Quantum, and Web 4.0 Collide in Cybersecurity</a><br><a href="https://www.cisa.gov/zero-trust-maturity-model">CISA Zero Trust Maturity Model</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd2ec0eb7bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential System Design Concepts]]></title>
            <link>https://medium.com/@kharavela.jain/essential-system-design-concepts-437e9a719ccf?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/437e9a719ccf</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 11:25:37 GMT</pubDate>
            <atom:updated>2026-04-10T11:25:37.204Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>System design concepts serve as the foundational blueprint for building software systems that are not only functional, but also scalable, reliable, and maintainable over time. By mastering these concepts early, you can design applications that gracefully handle increasing user traffic, evolving feature requirements, unexpected failures, and high-volume workloads — without having to constantly patch issues or rebuild core components from scratch. Thoughtful system design helps you make better architectural decisions, choose the right technologies, and anticipate bottlenecks before they become critical production problems, ultimately saving significant time, effort, and cost in the long run.</p><p>In this article, I will explore 12 essential system design concepts that every software engineer and architect should understand. I will walk through what each concept means, why it matters in real-world systems, and how it influences the way you design and operate modern applications at scale.</p><h3>1. Scalability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*BKWYyqG-foaQcHXn9zAm7A.png" /></figure><p>Scalability enables systems to handle growing workloads by adding resources without performance loss. It comes in vertical (upgrading single server hardware like CPU/RAM) and horizontal (adding more servers) forms.</p><p>Horizontal scaling suits distributed systems, using techniques like auto-scaling groups in AWS. Netflix scales its streaming service horizontally across thousands of microservices to manage peak loads from millions of users, ensuring smooth playback during events like award shows.</p><p>Use it effectively for high-traffic apps like e-commerce (Black Friday sales) or social media, where user growth is unpredictable. Principles include modularity, statelessness, and CAP theorem trade-offs for consistency vs. availability.</p><p><strong>Data Privacy &amp; Cybersecurity Impact</strong>: Scalability supports GDPR/CCPA compliance through data residency (geo-specific scaling) and encryption at scale. Horizontal scaling enables robust cybersecurity via micro-segmentation, zero-trust networks across regions, and distributed threat detection without single points of failure. However, it increases attack surface — proper RBAC, audit logging, and compliance monitoring across all nodes are essential.</p><h3>2. Load Balancer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*sU9VZqdTaHCXJIIkWwqTxA.png" /></figure><p>A load balancer distributes incoming traffic across multiple servers to prevent overload, improve availability, and ensure fault tolerance.</p><p>Types include hardware (F5), software (NGINX, HAProxy), and cloud-based (AWS ELB). Google uses global load balancers for Search and YouTube, routing billions of requests to optimal data centers based on location and health checks.</p><p>Ideal for web apps facing traffic spikes, like Amazon’s storefront during Prime Day. It supports algorithms like round-robin or least connections, with redundancy to avoid single points of failure.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Enables WAF integration, TLS termination, DDoS mitigation. Routes to compliant regions (GDPR); health checks isolate compromised nodes. Encrypt inter-server traffic.</p><h3>3. Caching</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*QhCe4JnA8cIPd9aPUnT37g.png" /></figure><p>Caching stores frequently accessed data in fast-access layers (e.g., Redis, Memcached) to reduce database load and latency.</p><p>Strategies include cache-aside (app manages) and write-through. Facebook caches user profiles and news feeds in TAO (graph cache), serving billions of reads per second.</p><p>Perfect for read-heavy apps like video streaming (your HLS.js work) or e-commerce product pages. Eviction policies like LRU handle memory limits; use for sessions, APIs, reducing costs in cloud setups.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: TTL enforces data minimization (GDPR); cache encryption, key rotation. Anonymization for PII; eviction prevents stale sensitive data leaks.</p><h3>4. Sharding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*O0yN9sBf6GuCeCeyOKrE8g.png" /></figure><p>Sharding partitions large databases horizontally across multiple servers using a shard key (e.g., user_id), distributing load.</p><p>Range or hash-based strategies ensure even distribution. Instagram shards feeds by user_id across MySQL clusters, handling 1B+ users without single-table bottlenecks.</p><p>Effective for massive datasets in social apps or IoT (your cloud platforms), like Uber’s trip data. Challenges include rebalancing and cross-shard queries; Vitess or Spanner mitigate these.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Shard by region/user for residency compliance. Encryption per shard; reduces blast radius of breaches. Cross-shard queries risk aggregation attacks — access controls essential.</p><h3>5. Replication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*yW5LtyeJtNlz6nbCZ22UmQ.png" /></figure><p>Replication copies data across servers for high availability, read scaling, and fault tolerance. Master-slave (writes to master, reads from slaves) is common.</p><p>MongoDB uses replica sets for eBay’s auctions, syncing data asynchronously. During outages, slaves promote to master seamlessly.</p><p>Vital for read-intensive apps like your video streaming (RTSP/HLS), ensuring geo-redundancy. Multi-master suits collaborative tools (Google Docs); trade-offs include eventual consistency.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Async replication risks consistency for PII (GDPR eventual ok); encrypt replicas, geo-fence for sovereignty. Failover preserves audit logs.</p><h3>6. Message Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*n76e5_b3o2Pmv8hiC7Lo8Q.png" /></figure><p>Message queues decouple services, enabling async communication via brokers like Kafka, RabbitMQ, or SQS.</p><p>Producers send messages; consumers process reliably. Uber queues ride requests for matching, scaling independently during surges.</p><p>Great for your microservices/IoT, like order processing or event streaming. Benefits: scalability via partitioning, durability, load leveling; use for notifications, ETL pipelines.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Encrypt messages in-flight/at-rest; TTL for ephemeral data (GDPR). Audit trails for compliance; idempotency prevents replay attacks.</p><h3>7. Circuit Breaker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*xuxz1W77AnQO94gaSaovDQ.png" /></figure><p>Circuit breaker prevents cascading failures by monitoring external service calls, “opening” on errors to fail fast.</p><p>States: closed (normal), open (block calls), half-open (test recovery). Netflix Hystrix/ Resilience4j protects its API gateway from downstream outages.</p><p>Essential in microservices (your React/Electron apps calling backends), like payment gateways. Pairs with timeouts/retries; use during Black Friday for e-commerce stability.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Fail-fast prevents data leaks from faulty services; timeout avoids session hijacks. Logs errors without PII for compliance audits.</p><h3>8. Monitoring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*k63kNkP_KHrGgslX_qiAVw.png" /></figure><p>Monitoring tracks system health via metrics (CPU, latency), logs, and traces for proactive issue detection.</p><p>Tools like Prometheus/Grafana visualize dashboards. Datadog monitors Slack’s 10M+ users, alerting on anomalies. Critical for production ops in your streaming platforms, alerting on latency spikes. Use APM (New Relic) for distributed tracing; effective in cloud (Kubernetes) for autoscaling decisions.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Anonymized logs (GDPR); SIEM integration for threats. Alerts on anomalies like unusual access patterns; compliance dashboards.</p><h3>9. Fallback</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*FBkBi3_8rrXLm7_CD2xlNQ.png" /></figure><p>Fallback provides alternative logic when primary fails, ensuring partial functionality (graceful degradation).</p><p>E.g., cached data if DB down. Spotify falls back to local playlists on network issues.</p><p>Useful in your real-time video apps (fallback to lower quality HLS). Implement via Polly (.NET) or try-catch; ideal for UIs (static content) or APIs during outages.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Fallback to cached/anonymized data avoids breaches; no new PII fetches. Ensures availability without violating consent rules.</p><h3>10. Service Discovery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*frPVglgx_aFYR5m1U93oOA.png" /></figure><p>Service discovery dynamically finds microservices locations via registries (Consul, etcd, Kubernetes). Clients query registry for IPs/ports. Airbnb uses SmartStack for 1000s of services.</p><p>Key for containerized setups (your Docker / Podman), auto-registering pods. Handles scaling; use in dynamic clouds vs. static DNS.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: mTLS auth in registry; RBAC for service access. Health checks quarantine compromised instances; encrypts service metadata.</p><h3>11. CDN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*Igwpp3iMFseusY8KV5ZK9Q.png" /></figure><p>CDNs distribute content globally via edge servers, reducing latency and origin load.</p><p>Cloudflare/AWS CloudFront cache Netflix static assets. During Oscars, it handles traffic surges. Perfect for your video streaming (HLS delivery), static sites. Caches HTML/JS; effective for geo-users, DDoS protection.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Caches non-PII; geo-routing for residency. HTTPS enforcement, token auth; DDoS scrubbing. Purge sensitive content quickly.</p><h3>12. Rate Limiter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*hmohbi-J3gwfOOwHvk1huQ.png" /></figure><p>Rate limiting caps requests per user/IP to prevent abuse, ensuring fairness.</p><p>Token bucket algorithm (fixed window). Twitter limits API calls, avoiding overload. Use Redis for counters; effective in public services like login endpoints.</p><p><strong>Data Privacy &amp; Cybersecurity</strong>: Thwarts scraping (PII exposure), DDoS. Per-user/IP limits with anon tokens (GDPR); logs for forensics without storing PII.</p><h3>Common Pitfalls</h3><p>Avoid these frequent system design errors to build robust products.</p><ul><li>Jumping straight to diagrams without clarifying requirements (functional/non-functional like QPS, latency).</li><li>Overlooking scalability early, causing bottlenecks; always estimate load and plan horizontal growth.</li><li>Neglecting fault tolerance — no redundancy, circuit breakers, or failover leads to outages.</li><li>Over-engineering complex solutions upfront; start simple and modular.</li><li>Ignoring trade-offs (e.g., consistency vs. availability) and alternatives.</li><li>Skipping monitoring, security, data evolution, and ops (e.g., no logging).</li></ul><h3>Conclusion</h3><p>Integrate these 12 concepts iteratively, avoiding pitfalls like poor planning. They enable resilient products like Netflix’s platform. Prioritize requirements, trade-offs, and monitoring for success in scalable architectures.</p><h3>References</h3><ol><li><a href="https://www.designgurus.io/blog/grokking-system-design-scalability">Grokking Scalability in System Design: Techniques, Principles, and Best Practices</a></li><li><a href="https://dev.to/karanpratapsingh/system-design-load-balancing-1k41">System Design: Load Balancing — DEV Community</a></li><li><a href="https://www.jobaajlearnings.com/blog/caching-strategies-in-system-design">Caching Strategies in System Design</a></li><li><a href="https://planetscale.com/blog/database-sharding">Database Sharding — PlanetScale</a></li><li><a href="https://www.geeksforgeeks.org/system-design/message-queues-system-design/">Message Queues — System Design — GeeksforGeeks</a></li><li><a href="https://www.almabetter.com/bytes/articles/importance-of-system-design-in-software-development">Importance of system design in software development</a></li><li><a href="https://www.linkedin.com/pulse/10-common-system-design-interview-mistakes-how-avoid-them-29a7c">10 Common System Design Interview Mistakes (and How to Avoid Them)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=437e9a719ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event-Driven Audit Logging in .NET 8]]></title>
            <link>https://medium.com/@kharavela.jain/event-driven-audit-logging-in-net-8-ffe8892f06c6?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe8892f06c6</guid>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 19:44:45 GMT</pubDate>
            <atom:updated>2026-03-19T19:44:45.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CLkSAYEpMaFAgJfnsmjY6g.png" /><figcaption>System Design</figcaption></figure><h3>Designing a Compliant, Traceable, and Scalable Microservices Audit Trail</h3><h4>Introduction</h4><p>Modern digital systems are increasingly distributed, regulated, and security‑sensitive. In such environments, knowing <strong>who</strong> did <strong>what</strong>, <strong>when</strong>, <strong>where</strong>, and <strong>how</strong> is not optional; it is a core requirement for governance, risk management, and compliance. A robust audit logging solution provides this visibility by recording security‑relevant events across services and infrastructure components.</p><p>In this article I will describe an event‑based audit logging solution built on .NET 8, Azure Service Bus, SQL Server, and OpenTelemetry / Jaeger for distributed tracing. The design focuses on minimal friction for developers (via attributes), strong separation of concerns (publisher vs. consumer), and regulatory‑grade audit trails suitable for frameworks such as GDPR and ISO 27001.</p><h4>The Business Need for Audit Logging</h4><p><strong>Regulatory and Compliance Drivers:</strong></p><p>Many industries are required by law or standard to maintain detailed, tamper‑resistant audit trails:</p><ul><li><strong>GDPR (EU)</strong> requires organizations to demonstrate accountability, track access to personal data, and support data subject rights (e.g., “who accessed or changed my data?”).</li><li><strong>ISO 27001</strong> explicitly calls for event logging and monitoring controls to detect and investigate security incidents, with emphasis on recording user activities, exceptions, and information security events.​</li><li>Other regulations (HIPAA, PCI DSS, SOX, SOC 2) similarly mandate retention and review of audit logs as evidence of compliant behavior.</li></ul><p>Without structured audit logging, organizations struggle to answer basic compliance questions, such as:</p><ul><li>Which user modified this customer’s record?</li><li>When was this configuration changed and by whom?</li><li>Can we prove that only authorized staff accessed sensitive fields?</li></ul><p>An event‑driven, centralized audit logging system makes these answers precise, repeatable, and demonstrable to auditors.</p><p>Security, Forensics, and Incident Response:<br>Audit logs are a primary forensic data source for detecting and reconstructing security incidents.</p><p><strong>Key security use cases include:</strong></p><ol><li>Threat detection: Spot unusual patterns such as repeated failed logins or mass updates to high‑value entities.</li><li>Intrusion forensics: Reconstruct a breach by following the sequence of events that led to data exfiltration or privilege escalation.</li><li>Fraud detection: Trace who changed financial or HR data, and when, with enough context to support disciplinary or legal actions.</li></ol><p>A well‑designed audit trail acts as a detective control, complementing preventive controls like access control and encryption.</p><p><strong>Operational and Business Intelligence:</strong></p><p>Beyond security and compliance, audit logs provide rich operational and business insights:</p><ul><li>Change tracking &amp; troubleshooting: When something breaks, audit logs help pinpoint the last changes made and their origin.</li><li>Usage analytics: Understanding which features, entities, or workflows are used most heavily can guide product and UX decisions.</li><li>Accountability and governance: Transparent visibility into actions supports better internal governance and clarifies responsibility for critical changes.</li></ul><p>In this sense, a robust audit trail is not just a defensive cost, but an asset that can improve decision‑making and operational maturity.</p><h3>Real‑World Use Cases</h3><p><strong>1. Financial Services — Transaction and Limit Changes</strong></p><p>In banking or fintech systems, every money movement and every change to transaction limits, beneficiary lists, or KYC data must be traceable:</p><ul><li>Who created or approved a high‑value transfer?</li><li>Who changed the daily withdrawal limit from ₹50,000 to ₹5,00,000?</li><li>Who updated a beneficiary account number just before a suspicious transfer?</li></ul><p>An audit event for a limit change might capture: EntityType = &quot;AccountLimit&quot;, EntityId = &quot;ACC123&quot;, Action = &quot;UPDATE&quot;, OldValues = {&quot;DailyLimit&quot;:50000}, NewValues = {&quot;DailyLimit&quot;:500000}, along with user, timestamp, and correlation ID to tie multiple actions together.</p><p><strong>2. Healthcare — Access to Patient Records</strong></p><p>Healthcare providers must track access and changes to electronic health records to satisfy privacy regulations and support investigations:</p><ul><li>Identify which clinician viewed or edited a patient’s record.</li><li>Detect patterns of inappropriate access (e.g., looking up VIPs or celebrities).</li><li>Provide evidence for patient complaints or regulatory inquiries.</li></ul><p>Audit logs here become a key tool for demonstrating that PHI (Protected Health Information) is handled according to policy.</p><p><strong>3. SaaS / Multi‑Tenant Platforms — Config and Data Changes</strong></p><p>In a multi‑tenant SaaS application (e.g., subscription billing, HR, CRM):</p><ul><li>Track admin changes to tenant configuration and permissions.</li><li>Record cross‑tenant impact changes such as pricing rules or global feature toggles.</li><li>Provide customers with their own audit trail (a differentiating feature and revenue driver).</li></ul><p>The event‑based architecture described below is particularly well suited to multi‑tenant contexts, because it scales horizontally and can filter or partition logs per tenant.</p><h3>Solution Overview</h3><p>The proposed solution consists of:</p><ol><li>AuditPublisher library: a reusable .NET 8 class library which:</li></ol><ul><li>Defines a standard AuditEvent contract.</li><li>Provides an [Audit] attribute for controllers or methods.</li><li>Implements an AuditActionFilter to intercept HTTP actions and publish events.</li><li>Publishes audit events to a Service Bus queue with tracing context.</li></ul><p>2. Microservices (producers): multiple .NET 8 Web APIs (e.g., SampleMicroservice1) that:</p><ul><li>Reference AuditPublisher.</li><li>Configure the filter globally.</li><li>Emit audit events with almost zero boilerplate.</li></ul><p>3. AuditLoggingService (consumer): a .NET 8 Web API that:</p><ul><li>Subscribes to the audit-events queue.</li><li>Persists events into a SQL Server database (AuditDbContext).</li><li>Exposes query APIs for audit log search.</li></ul><p>4. Distributed tracing: OpenTelemetry + Jaeger visualizing end‑to‑end flows:</p><ul><li>HTTP request → audited method → Service Bus publish → Audit consumer → SQL insert.</li></ul><h3>Key Design Decisions</h3><p><strong>1. Event‑Based Architecture via Service Bus</strong></p><p>Instead of writing audit rows directly from each microservice to a central database, events are published to a message bus (e.g., Azure Service Bus). This offers several advantages:</p><ul><li><strong>Loose coupling:</strong> Services only need to know how to emit AuditEvent, not how storage is implemented.</li><li><strong>Resilience and buffering:</strong> Bursty audit traffic is smoothed by the queue, and the consumer can be scaled independently.</li><li><strong>Evolution:</strong> Storage schema and retention policies can evolve without touching every producer service.</li></ul><p><strong>2. Attribute‑Driven Audit Triggering</strong></p><p>To minimize friction, we use an attribute and an ASP.NET Core action filter, not custom middleware or source generators. The attribute describes <em>what</em> to audit; the filter handles <em>how</em>.<br>AuditAttribute:</p><pre>namespace AuditPublisher;<br><br>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]<br>public class AuditAttribute : Attribute<br>{<br>    public string EntityType { get; }<br>    public string[] Actions { get; }<br>    public bool CaptureRequestBody { get; }<br><br>    public AuditAttribute(string entityType, bool captureRequestBody = false, params string[] actions)<br>    {<br>        EntityType = entityType;<br>        CaptureRequestBody = captureRequestBody;<br>        Actions = actions.Length &gt; 0 ? actions : new[] { &quot;*&quot; };<br>    }<br>}</pre><p>Usage in a controller:</p><pre>using AuditPublisher;<br>using Microsoft.AspNetCore.Mvc;<br><br>namespace SampleMicroservice1.Controllers;<br><br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>[Audit(&quot;Order&quot;, captureRequestBody: true)]<br>public class OrdersController : ControllerBase<br>{<br>    [HttpPost]<br>    public IActionResult Create([FromBody] object body)<br>    {<br>        return Ok(new { status = &quot;created&quot;, body });<br>    }<br>}</pre><p>Developers simply add [Audit(&quot;EntityName&quot;)] and the plumbing is handled centrally.</p><p><strong>3. Centralized Publisher with Tracing Context</strong></p><p>AuditPublisherService encapsulates Service Bus interaction and propagates trace data:</p><pre>using System.Diagnostics;<br>using System.Text.Json;<br>using Azure.Messaging.ServiceBus;<br><br>namespace AuditPublisher;<br><br>public class AuditPublisherService : IAuditPublisher<br>{<br>    private readonly ServiceBusSender _sender;<br>    private readonly ILogger&lt;AuditPublisherService&gt; _logger;<br><br>    public AuditPublisherService(ServiceBusClient client, ILogger&lt;AuditPublisherService&gt; logger)<br>    {<br>        _sender = client.CreateSender(&quot;audit-events&quot;);<br>        _logger = logger;<br>    }<br><br>    public async Task PublishAsync(AuditEvent auditEvent, CancellationToken cancellationToken = default)<br>    {<br>        using var activity = AuditTracing.ActivitySource.StartActivity(&quot;audit.publish.servicebus&quot;, ActivityKind.Producer);<br><br>        var enriched = auditEvent.WithTracing();<br>        var json = JsonSerializer.Serialize(enriched);<br>        var message = new ServiceBusMessage(json)<br>        {<br>            CorrelationId = enriched.CorrelationId<br>        };<br><br>        if (enriched.TraceContext.TryGetValue(&quot;traceparent&quot;, out var tp))<br>        {<br>            message.ApplicationProperties[&quot;traceparent&quot;] = tp;<br>        }<br><br>        await _sender.SendMessageAsync(message, cancellationToken);<br>        _logger.LogInformation(&quot;Published audit event {EventId}&quot;, enriched.EventId);<br>    }<br>}</pre><p>This ensures every event contains enough context for cross‑service tracing and correlation.</p><p><strong>4. Action Filter for Automatic Capture</strong></p><p>The AuditActionFilter intercepts controller actions, constructs an AuditEvent, and delegates publishing:</p><pre>using System.Diagnostics;<br>using System.Reflection;<br>using Microsoft.AspNetCore.Mvc.Filters;<br><br>namespace AuditPublisher;<br><br>public class AuditActionFilter : IAsyncActionFilter<br>{<br>    private readonly IServiceProvider _serviceProvider;<br>    private readonly ILogger&lt;AuditActionFilter&gt; _logger;<br><br>    public AuditActionFilter(IServiceProvider serviceProvider, ILogger&lt;AuditActionFilter&gt; logger)<br>    {<br>        _serviceProvider = serviceProvider;<br>        _logger = logger;<br>    }<br><br>    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)<br>    {<br>        var descriptor = context.ActionDescriptor;<br>        var auditAttr = descriptor.EndpointMetadata.OfType&lt;AuditAttribute&gt;().FirstOrDefault()<br>                        ?? descriptor.GetType().GetCustomAttribute&lt;AuditAttribute&gt;();<br><br>        if (auditAttr == null)<br>        {<br>            await next();<br>            return;<br>        }<br><br>        using var activity = AuditTracing.ActivitySource.StartActivity(&quot;audit.event.create&quot;, ActivityKind.Internal);<br>        var http = context.HttpContext;<br><br>        var auditEvent = new AuditEvent<br>        {<br>            CorrelationId = http.TraceIdentifier,<br>            ServiceName = http.Request.Headers[&quot;X-Service-Name&quot;].FirstOrDefault() ?? &quot;SampleMicroservice1&quot;,<br>            EntityType = auditAttr.EntityType,<br>            EntityId = http.Request.RouteValues.Values.LastOrDefault()?.ToString() ?? string.Empty,<br>            Action = $&quot;{http.Request.Method}_{descriptor.DisplayName}&quot;,<br>            UserId = http.User?.Identity?.Name ?? &quot;Anonymous&quot;,<br>            TenantId = http.User?.FindFirst(&quot;tenant&quot;)?.Value ?? &quot;default&quot;,<br>            IpAddress = http.Connection.RemoteIpAddress?.ToString() ?? &quot;unknown&quot;,<br>            Timestamp = DateTime.UtcNow<br>        };<br><br>        if (auditAttr.CaptureRequestBody)<br>        {<br>            auditEvent.NewValues[&quot;Request&quot;] = context.ActionArguments;<br>        }<br><br>        var executed = await next();<br><br>        auditEvent.Details = executed.Exception == null ? &quot;SUCCESS&quot; : $&quot;ERROR: {executed.Exception.Message}&quot;;<br><br>        using var scope = _serviceProvider.CreateScope();<br>        var publisher = scope.ServiceProvider.GetRequiredService&lt;IAuditPublisher&gt;();<br>        await publisher.PublishAsync(auditEvent);<br>    }<br>}</pre><p>This keeps business logic clean while ensuring consistent audit behavior.</p><p><strong>5. Centralized Storage and Query Service</strong></p><p>The consumer (AuditLoggingService) processes events and persists them to SQL Server for querying and retention:</p><pre>public class AuditLog<br>{<br>    public Guid Id { get; set; }<br>    public string EventId { get; set; } = string.Empty;<br>    public string CorrelationId { get; set; } = string.Empty;<br>    public string ServiceName { get; set; } = string.Empty;<br>    public string EntityType { get; set; } = string.Empty;<br>    public string EntityId { get; set; } = string.Empty;<br>    public string Action { get; set; } = string.Empty;<br>    public string UserId { get; set; } = string.Empty;<br>    public string TenantId { get; set; } = string.Empty;<br>    public string IpAddress { get; set; } = string.Empty;<br>    public DateTime Timestamp { get; set; }<br>    public string Details { get; set; } = string.Empty;<br>    public string OldValuesJson { get; set; } = string.Empty;<br>    public string NewValuesJson { get; set; } = string.Empty;<br>}</pre><p>Combined with a search API (e.g., filter by correlation ID, service, user, or date range), this becomes the main interface for auditors, security operations, and developers.</p><p><strong>6. Distributed Tracing with OpenTelemetry and Jaeger</strong></p><p>To understand how requests flow through the system, we add OpenTelemetry instrumentation and export traces to Jaeger.</p><p>In a microservice Program.cs:</p><pre>using AuditPublisher;<br>using Azure.Messaging.ServiceBus;<br>using OpenTelemetry.Resources;<br>using OpenTelemetry.Trace;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddControllers(options =&gt;<br>{<br>    options.Filters.Add&lt;AuditActionFilter&gt;();<br>});<br><br>builder.Services.AddHttpContextAccessor();<br><br>builder.Services.AddSingleton(_ =&gt; new ServiceBusClient(<br>    builder.Configuration.GetConnectionString(&quot;ServiceBus&quot;) ?? &quot;Endpoint=sb://...&quot;));<br><br>builder.Services.AddScoped&lt;IAuditPublisher, AuditPublisherService&gt;();<br>builder.Services.AddScoped&lt;AuditActionFilter&gt;();<br><br>builder.Services.AddOpenTelemetry()<br>    .WithTracing(tracer =&gt;<br>    {<br>        tracer<br>            .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(&quot;SampleMicroservice1&quot;))<br>            .AddAspNetCoreInstrumentation()<br>            .AddSource(AuditTracing.ServiceName)<br>            .AddOtlpExporter(o =&gt;<br>            {<br>                o.Endpoint = new Uri(&quot;http://localhost:4318/v1/traces&quot;);<br>            });<br>    });<br><br>var app = builder.Build();<br>app.MapControllers();<br>app.Run();</pre><p>This creates a single, consistent timeline for each request across HTTP, Service Bus, and the audit consumer.</p><h3>Benefits and Business Value</h3><ol><li>Compliance and Risk Reduction</li></ol><ul><li>Demonstrable compliance: Detailed, searchable audit trails support GDPR, ISO 27001, and other frameworks by providing evidence of access, changes, and policy enforcement.</li><li>Lower breach impact: Faster forensic analysis reduces the duration and scope of incidents, limiting regulatory fines and reputational damage.</li></ul><p>2. Security and Operational Insight</p><ul><li>Early anomaly detection: Correlating audit events with tracing data helps identify suspicious behavior and performance anomalies.</li><li>Root‑cause analysis: Reconstructing “what happened” across services is significantly easier with centralized logs and Jaeger traces.</li></ul><p>3. Developer Productivity and Maintainability</p><ul><li>Low friction: Attribute‑based auditing means developers only add [Audit(&quot;Entity&quot;)] and let infrastructure handle the rest.</li><li>Consistency: Centralized logic and schema reduce the risk of partial or inconsistent audit coverage across a microservice landscape.</li><li>Extensibility: Adding new sinks (e.g., data lake, SIEM) or analytics pipelines is straightforward because all events follow the same contract.</li></ul><p>4. Strategic Value</p><ul><li>Customer trust: Being able to show customers a complete, reliable audit trail can be a key differentiator, especially in regulated markets.</li><li>Data‑driven decisions: Audit data becomes a form of “activity telemetry” that can feed into product and business analytics, unlocking new insights.</li></ul><h3>Conclusion</h3><p>A robust audit logging system is no longer a “nice to have”; it is a foundational capability for any serious digital platform. Regulations like GDPR and ISO 27001 expect organizations to track user activity and system changes, and security reality demands forensic‑grade visibility into how data is accessed and modified.</p><p>The design presented here — an attribute‑driven, event‑based audit logging solution with centralized persistence and Jaeger‑backed distributed tracing — balances compliance, performance, and developer experience. It makes it easy to:</p><ul><li>Capture meaningful audit events from any .NET 8 microservice with minimal code.</li><li>Transport them reliably via Service Bus to a dedicated audit service.</li><li>Persist them in a structured way in SQL Server.</li><li>Correlate them end‑to‑end across services with OpenTelemetry and Jaeger.</li></ul><p>Implemented correctly, such a system not only satisfies auditors and security teams, but also becomes a strategic asset for operations and product leadership. It turns compliance and observability from a cost center into a competitive advantage.</p><p><strong>References</strong></p><ul><li><a href="https://www.fortra.com/blog/what-audit-logging-how-it-works-why-you-need-it">Fortra</a> — <em>What Is Audit Logging? How It Works &amp; Why You Need It</em> (compliance, security, and use cases).​</li><li><a href="https://www.splunk.com/en_us/blog/learn/audit-logs.html">Splunk </a>— <em>Audit Logging: A Comprehensive Guide</em> (benefits, ISO 27001 mention, and best practices).​</li><li><a href="https://www.datadoghq.com/knowledge-center/audit-logging/">Datadog </a>— <em>Audit Logging: What It Is &amp; How It Works</em> (security forensics, legal evidence, operational insights).​</li><li><a href="https://www.digicert.com/blog/the-security-benefits-of-audit-logging">DigiCert </a>— <em>The Security Benefits of Audit Logging</em> (security and incident reconstruction benefits).​</li><li><a href="https://www.crowdstrike.com/en-au/cybersecurity-101/next-gen-siem/audit-logs/">CrowdStrike </a>— <em>What are Audit Logs? Use Cases and Challenges</em> (security and SIEM context).​</li><li><a href="https://www.twilio.com/en-us/blog/developers/community/propagate-opentelemetry-context-via-azure-service-bus-for-async-dotnet-services">OpenTelemetry </a>&amp; <a href="https://docs.particular.net/samples/open-telemetry/jaeger/?version=core_8">Jaeger examples</a> (Microsoft, NServiceBus, Twilio blogs) — distributed tracing in .NET with OTLP and context propagation.</li><li><a href="https://www.contentful.com/blog/audit-logging-for-enterprise-scale-content-platforms/">Articles on using audit logs</a> as a business and compliance advantage in modern enterprises.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe8892f06c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Undo & Redo features]]></title>
            <link>https://medium.com/@kharavela.jain/designing-undo-redo-features-7c57b5902779?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c57b5902779</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 07:18:47 GMT</pubDate>
            <atom:updated>2026-03-11T07:18:47.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxeHCFKl7_qh9D4xGU4Bzw.png" /><figcaption>System Architecture View</figcaption></figure><p>In the era of modern cloud-native application design, many powerful and time-tested design patterns are often overlooked due to the focus on newer paradigms and technologies. One such underrated yet highly effective pattern is the <strong>Memento Design Pattern</strong>. Despite its simplicity, this pattern provides a robust solution for managing state in applications, especially in scenarios requiring undo/redo functionality or state restoration.</p><p>In this discussion, I aim to highlight the importance of the Memento Design Pattern and demonstrate how it can be effectively applied to solve real-world problems. By exploring its structure, benefits, and practical applications, we can better understand how this pattern can enhance the design and functionality of modern software systems.</p><p>For instance, consider a video editing application where users frequently make changes to video clips, such as trimming, adding effects, or rearranging segments. These actions often require the ability to revert to previous states or redo changes, ensuring flexibility and user control. The Memento Design Pattern provides an elegant solution by enabling the application to capture snapshots of the video’s state at different points in time, allowing seamless restoration without compromising encapsulation or data integrity.</p><p>Through this example, I will explain how the Memento Design Pattern can be leveraged to address such challenges, ensuring that state management remains efficient, scalable, and aligned with the principles of modern application design. By revisiting and embracing this pattern, developers can unlock its potential to solve complex problems in a straightforward and maintainable way.</p><p>The Memento design pattern is used to capture and restore an object’s internal state without violating encapsulation, making it particularly suitable for implementing undo/redo functionality in applications such as video editors. <br>This pattern is valuable when you need to preserve the state of an object at a specific point in time and restore it later, without exposing the object’s internal details to external components.<br>The Memento pattern allows the application to save snapshots of the video’s state at different points, enabling users to revert to previous states without compromising the integrity of the underlying data.</p><p><strong>The Memento pattern consists of three key components</strong>:</p><ol><li><strong>Memento</strong>: Serves as a container for storing the internal state of an object. It provides a way to save and retrieve the state without exposing the internal structure of the object.</li><li><strong>Originator</strong>: Represents the object whose state needs to be saved and restored. The originator creates mementos to capture its state and uses them to restore itself when needed.</li><li><strong>Caretaker</strong>: Manages the mementos, typically by maintaining a stack or list of saved states. The caretaker does not inspect or modify the mementos but facilitates undo/redo operations by storing and retrieving them.</li></ol><p>By separating the concerns of state management (handled by the caretaker) and state creation/restoration (handled by the originator), the Memento pattern ensures that encapsulation is maintained, while providing a robust mechanism for state management.</p><p><strong>Video Editor Context</strong></p><p>I am using a React app video editor with .NET Core backend, the state includes timeline clips (position, duration, effects), tracks, and preview data — too large for full client snapshots alone. Use Memento for client-side immediate undo (e.g., drag clips) and sync deltas to backend Caretaker for persistence/multi-device support. Limit stack to 20–50 mementos to manage memory.</p><h4>Backend Implementation using .NET Core</h4><p>Define serializable Memento for video project deltas (e.g., added clip ID, changes).</p><pre>public class VideoMemento {<br>  public Guid ProjectId { get; set; } <br>  // ClipDelta: {Id, StartTime, Effects}  <br>  public List&lt;ClipDelta&gt; Changes { get; set; } = new(); <br>} <br><br>public class VideoProjectOriginator { <br>  // Holds full project; creates memento of deltas <br>  public VideoMemento CreateMemento() =&gt; new() { /* capture changes */ }; <br>  public void Restore(VideoMemento m) { /* apply deltas */ } <br>}<br><br>public class UndoCaretaker { <br>  private Stack&lt;VideoMemento&gt; _undoStack = new(); <br>  private Stack&lt;VideoMemento&gt; _redoStack = new(); <br>  <br>  public void Save(VideoProjectOriginator originator, Guid projectId) { <br>    _undoStack.Push(originator.CreateMemento()); <br>    _redoStack.Clear(); <br>  } <br><br>  // Expose via API: POST /api/project/{id}/undo<br>  public VideoMemento Undo() =&gt; _undoStack.Count &gt; 0 ? _undoStack.Pop() : null; <br>  public void Redo() =&gt; _redoStack.Count &gt; 0 ? _redoStack.Pop() : null; <br><br>} </pre><p>Store stacks per project in Redis/DB for persistence. <br>API endpoints: /undo, /redo, /save-state</p><h4>Frontend Implementation using React</h4><p>Use useReducer with Memento-inspired history array for timeline state (array of clips with timestamps, effects)<br>A Custom hook would look like this:</p><pre>const useVideoUndo = (initialState) =&gt; {<br>  const [history, setHistory] = useState([initialState]);<br>  const [pointer, setPointer] = useState(0);<br><br>  const saveState = (newState) =&gt; {<br>    setHistory(prev =&gt; {<br>      const newHistory = prev.slice(0, pointer + 1);<br>      newHistory.push(newState);<br>      return newHistory.slice(-50); // Limit stack<br>    });<br>    setPointer(p =&gt; p + 1);<br>  };<br><br>  const undo = () =&gt; setPointer(p =&gt; Math.max(0, p - 1));<br>  const redo = () =&gt; setPointer(p =&gt; Math.min(history.length - 1, p + 1));<br><br>  return { state: history[pointer], saveState, undo, redo, canUndo: pointer &gt; 0, canRedo: pointer &lt; history.length - 1 };<br>};</pre><p>In editor component: <br>const { state: timeline, saveState, undo } = useVideoUndo([]); <br>Call saveState(newTimeline) on actions like addClip, debounced for performance.</p><h4>Integration Steps</h4><p>1. <strong>Model State</strong>: Define serializable VideoState (timeline[], selectedClip, zoomLevel). Memento holds deltas or full shallow copy.​<br>2. <strong>Backend Setup</strong>: Implement Originator / Caretaker classes. <br>Add API controllers for save / undo / redo, using SignalR for real-time sync.<br>3. <strong>Frontend Hook</strong>: Create useVideoUndo as above. <br>Wrap editor in context provider.<br>4. <strong>Capture Changes</strong>: On user actions (drag, trim, effect), compute delta, call saveState(delta) locally and POST to backend.<br>5. <strong>Sync Mechanism</strong>: On undo / redo, apply locally then PATCH backend. <br>Poll or use WebSockets for multi-tab sync.<br>6. <strong>UI Controls</strong>: Add buttons / keybindings (Ctrl + Z / Y). <br>Disable when !canUndo / canRedo.​<br>7. <strong>Optimize</strong>: Debounce saves (300ms), compress mementos (JSON diffs), limit stack size. Test with 100+ clips.</p><h4>Conclusion</h4><p>Implementing the Memento pattern in a React video editor with .NET Core backend delivers a robust, encapsulation-preserving undo/redo system tailored for complex timeline states.</p><p>By combining client-side history stacks (via useReducer hooks) for instant feedback, backend delta persistence (with Redis / DB), and optimizations like debouncing and stack limits, you achieve responsive UX while handling real-world challenges like memory bloat and concurrency.</p><p>Future enhancements could integrate diffs for even leaner mementos or WebSockets’ for collaborative editing, ensuring scalability as video projects grow.</p><h4>Reference</h4><ol><li><a href="https://dotnetcorecentral.com/blog/memento-pattern/">Memento Pattern — .Net Core Central</a></li><li><a href="https://www.linkedin.com/posts/djokic-stefan_memento-design-pattern-activity-7348678120918368258-o4Co">How to implement Undo feature using Memento Design Pattern | Stefan Đokić posted on the topic | LinkedIn</a></li><li><a href="https://www.c-sharpcorner.com/article/understanding-the-memento-design-pattern-in-c-sharp-with-a-practical-example/">Understanding the Memento Design Pattern in C# with a Practical Example</a></li><li><a href="https://www.momentslog.com/development/design-pattern/memento-pattern-in-video-editing-software-undo-redo-functionality">Memento Pattern in Video Editing Software: Undo/Redo Functionality — Moments Log</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c57b5902779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python flavor in C# 12.0]]></title>
            <link>https://medium.com/@kharavela.jain/python-flavor-in-c-12-0-8f7c1472b44?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7c1472b44</guid>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 08:59:41 GMT</pubDate>
            <atom:updated>2023-08-14T08:59:41.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulrI4O6oyweixL82uVwcSg.png" /><figcaption>Dynamic C#12</figcaption></figure><p>Initializing in C# has been a bit of a headache, ask any developer they will resonate the same when it comes to List, Dictionary, etc.</p><blockquote>There is a good amount of changes have been brought in, in the recent past with C# 10, and 11, however, it is still not uniform across multiple data types. Typically this is how we are declaring and initializing our Lists</blockquote><pre>//Handling Collections in C# 10/11<br>using System;<br>using System.Collections.Generic;<br><br>List&lt;int&gt; lstNum = new()<br>{ <br>  1,2,3 <br>};</pre><p>Despite this being just for initializing, you can see with a pretty print and better readability, you will end up having three lines. This will get even more complicated with Span and Dictionaries.</p><pre>//Handling Collections in C# 10/11<br>using System;<br>using System.Collections.Generic;<br>Dictionary &lt;int, string&gt; keyValuePairs = new()<br>{<br>    {1,&quot;Mr ABC&quot;},<br>    {2, &quot;Ms DEF&quot;}<br>};</pre><p>So, come to C# 12, we are getting brand new Collection initializers which will not just make your code look simpler but also keeps it uniform with multiple data types making it much easier to read and understand. I am using <a href="https://sharplab.io/">www.sharplab.io</a> to test these features as the new C# compiler is yet to be released. This website will allow you to write and explore C# code with a list of available compilers. From this website, I am using <strong>Collection Literals from the 28 June 2023</strong> branch to test this upcoming feature. The code will look much simpler with this small but effective feature.</p><pre>//Handling Collections in C# 12<br>using System;<br>using System.Collections.Generic;<br><br>List&lt;int&gt; lstNum = [1,2,3];<br><br>int[] arr = [4,5,6];</pre><pre>// For the Dictionary, this simplified syntax is not yet available <br>// in the Collection Literals branch(28 June 2023), and this syntax may <br>// change in the released C# 12 version.<br><br>using System;<br>using System.Collections.Generic;<br>Dictionary &lt;int, string&gt; keyValuePairs =   [ 1: &quot;Mr ABC&quot;, 2: &quot;Ms DEF&quot;];</pre><h3>Conclusion</h3><p>That&#39;s it! The same syntax works with arrays as well, simple and clean. Do you like this feature? Let me know what you think in the comments section.</p><h3>References</h3><ol><li>C# Repo — <a href="https://github.com/dotnet/csharplang">https://github.com/dotnet/csharplang</a></li><li>C# 12 Guide — <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12">https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7c1472b44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bad Enumerations!]]></title>
            <link>https://medium.com/@kharavela.jain/bad-enumerations-281c50063517?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/281c50063517</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[net6]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 06:10:00 GMT</pubDate>
            <atom:updated>2022-09-02T06:49:03.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktrqIyEIwt-Akt5CRINdqg.jpeg" /><figcaption>Under the hood!</figcaption></figure><p><strong>Introduction</strong></p><p>The enumeration interface helps to obtain a collection on demand, allowing developers to loop over collections of anonymous types, with read-only access. This allows the application to lazy load items from the source and improve the performance.</p><p>NOTE: You can refer to the complete code from my<em> </em><a href="https://github.com/TheCSharpGuy/IEnumerableDemo"><em>GitHub</em></a></p><blockquote><em>Referring to </em><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerable?view=net-6.0"><em>Microsoft’s </em></a><em>documentation, </em>IEnumerable Exposes an enumerator, which supports a simple iteration over a non-generic collection.</blockquote><p>Let&#39;s analyze this code, here I am filling up a dynamic list<em> </em>with 500 products and displaying a couple of details from the same list. This is how we typically load, process, and send responses from our APIs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdac61a97b46842b8f85d0ee91a3d241/href">https://medium.com/media/bdac61a97b46842b8f85d0ee91a3d241/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc499961b9a7b1acf0e399024191c0b/href">https://medium.com/media/8bc499961b9a7b1acf0e399024191c0b/href</a></iframe><p>Let us evaluate the first three lines from the <em>Sample 1 </em>code now;</p><p>Create a reference <strong><em>ManageProduct</em></strong><em>, </em>considering that as our logical container, then call the <strong><em>GetProducts()</em> </strong>method and store the result in the <strong><em>catalogue</em></strong>, and from the <strong><em>catalogue </em></strong>get the total count of the products. This is how you would interpret those three lines. However, that is not how the system processes these statements.</p><p>As you would have noticed during the debugging, even though we are using a result stored in the <strong><em>catalogue,</em></strong> the actual items from the <em>GetProducts() </em>only get called when it is used in the <em>for loop</em>. The system re-computes when you call the <strong><em>catalogue.Count() </em></strong>method. So, we are introducing performance degradation through our code, this is also known as the <strong><em>Multiple Enumeration </em></strong>issue.</p><p>Assuming you want to use the three statements from <em>Sample 1, </em>as we generally interpret, then we must use a <em>ToList() </em>method<em> </em>to convert the result to a strict type<em> </em><strong><em>List&lt;Product&gt;</em></strong><em> </em>and<em> </em>obtain the <em>Count() </em>as shown below. The memory for the result will be allocated once, and the same list will be used throughout the scope of the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71946c550739e976555b17a60cdac2b4/href">https://medium.com/media/71946c550739e976555b17a60cdac2b4/href</a></iframe><p><strong>Conclusion</strong></p><p>Understanding how the enumeration process takes place in the CLR helps us to extract the best performance for our applications. One needs to realize the execution cost behind the scenes to avoid any such compute or memory-intensive operations introduced by a developer due to the wrong approach.</p><p><strong>References</strong></p><p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerable?view=net-6.0">IEnumerable Interface</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281c50063517" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own CLI!]]></title>
            <link>https://medium.com/@kharavela.jain/make-your-own-cli-4f5d585e4b20?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5d585e4b20</guid>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 10:12:20 GMT</pubDate>
            <atom:updated>2021-12-27T10:53:44.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction</p><p>Being a developer, each one of us must have used multiple CLI’s to compile our code in .NET, Java, or going back to the times of Turbo C/C++, Fortran or BASIC. All of these used to have one thing in common, the CLI.</p><p>This article explains how with .NET Core 3.1 onwards developers can build their own CLIs with ease unlike the earlier versions of the .NET framework. Let’s get to it and see how exactly we can achieve that.</p><p>Here are the simple steps;</p><ol><li>Create a new console project with target framework as net5.0</li><li>From the Solution Explorer window double click and open the .csproj file (typically your project name)</li><li>Add the following lines to &lt;PropertyGroup&gt;;</li></ol><pre>&lt;PackAsTool&gt;true&lt;/PackAsTool&gt;&lt;ToolCommandName&gt;clidemo&lt;/ToolCommandName&gt;&lt;PackageOutputPath&gt;./nupkg&lt;/PackageOutputPath&gt;</pre><ol><li>Setting <strong>PackAsTool</strong> tag to true converts your executable into a NuGet package which can be shared and used among your teams.</li><li>The <strong>ToolCommandName </strong>tag defines the name of your CLI tool or how you can invoke it from the command prompt (similar to git, dotnet, docker, etc.)</li><li>The <strong>PackageOutputPath</strong> tag is used to copy the compiled NuGet package file, upon the successful build.</li><li>Now go ahead and add your required logic to the tool you are creating.</li></ol><blockquote>You can refer to the sample code from my<em> </em><a href="https://github.com/TheCSharpGuy/CLIDemo"><em>GitHub</em></a></blockquote><p>Once you add your required functionality to the CLI tool, it’s time to deploy it on your system. <br>First, navigate to your project folder in the command line, and type the below statement</p><pre>dotnet tool install --global --add-source ./nupkg CLIDemo</pre><p>Notice that, NuGet package which will be created always uses your project name followed by the assembly version from the project properties. In my case <em>CLIDemo.1.0.0.nupkg</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvkFVCXbo3QCVca9SPCXAw.jpeg" /><figcaption>Figure 1 — Tool Installation</figcaption></figure><p>Once the tool installation is successful, you should see a message similar to the above Figure 1, and you can access it from anywhere in your command prompt. Refer to Figure 2 for the sample execution of the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z39PBRh7wfbFOCh2u-UZ6Q.jpeg" /><figcaption>Figure 2 — Sample output</figcaption></figure><p>However, if you omit the <em>global </em>keyword, the tool will be installed locally in the root folder of the application.</p><p>Similarly, if we made any changes to our CLI and we want to update the latest version, use the following command to achieve that.</p><pre>dotnet tool update --global CLIDemo</pre><p>For any reason, if we decide to remove a specific CLI we have added to our system, we can use the following command.</p><pre>dotnet tool uninstall -- global CLIDemo</pre><p>Conclusion</p><p>That’s it! The creation of a custom tool is very handy when you need to perform repetitive tasks such as the creation of service from a standard boilerplate code or basic system cleanup activities. For further reading, very elaborate documentation can be found on Microsoft docs.</p><p>Happy tooling!!</p><p>References<br><a href="https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools-how-to-create">Tutorial: Create a .NET tool using the .NET CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5d585e4b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Yield the best iterator?]]></title>
            <link>https://medium.com/@kharavela.jain/is-yield-the-best-iterator-54dcb9a5189b?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/54dcb9a5189b</guid>
            <category><![CDATA[yiled-csharp]]></category>
            <category><![CDATA[yield-keyword]]></category>
            <category><![CDATA[ienumerable]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[net5]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Tue, 26 Oct 2021 03:24:33 GMT</pubDate>
            <atom:updated>2021-10-26T04:27:08.949Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR;</strong></p><blockquote>Referring to <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield">Microsoft’s </a>documentation, when you use yield in a method, operator, or get accessors it indicates that it is an iterator, with the only difference of having implicit state management for the iterator!<br><em>You can refer to the complete code from my</em> <a href="https://github.com/TheCSharpGuy/YieldDemo">GitHub</a></blockquote><p><strong>Introduction</strong></p><p>The <em>yield </em>keyword was part of the C# 2.0 (November 2005) release, however, it was either misunderstood or not being used to its full potential in my opinion. <br>What we are going to try and find out is that, Is it the best iterator? If yes, what makes it so? Let me try and explain to you with a couple of examples and perform a benchmark comparison.</p><p>In this code sample, as we can see, I am filling up the products to a list<em> </em>and displaying 500 products with a couple of details from the same list. This is how typically we load, display and process the data from our APIs.</p><p>However, things get really bad when we have to transfer more than 10 million records! Imagine the list being built in the memory, and when it reaches the requestor, only a bunch of data is being used. Making it costlier on the server where it is being created as well as increasing your HTTP payload.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fb3ad53be3bae75da2a3d54cd388fca/href">https://medium.com/media/2fb3ad53be3bae75da2a3d54cd388fca/href</a></iframe><p>This is where the <em>Yield </em>keyword outperforms the usual approach. Sample 2 performs the same operation as in the above code, but when you debug you would see that until the process hits the <em>catalogue </em>variable inside the <em>foreach </em>loop nothing is loaded on the memory. This is where the magic happens with <em>yield</em>. Every product item is built on the fly and sent back to the main <em>foreach by </em>maintaining its state and sending one item at a time!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/291d6b5c123f9f841f64ae0e3c2c4819/href">https://medium.com/media/291d6b5c123f9f841f64ae0e3c2c4819/href</a></iframe><p>Let us look at the benchmark results for these two approaches for a better understanding. Here in the below example, we are obtaining 100,000 product items from <em>ListProducts</em> &amp; <em>ListProductsYield</em> methods. The Allocated memory and processing data comparison give a clear indication that who is the hands-down winner here. <br>This also clearly indicates the impact on the performance in the data loading and responsiveness aspects of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82iCq5OZV8NwzZkUhzSMjg.jpeg" /><figcaption>100,000 Products Benchmark</figcaption></figure><p>Let us look at another example here. We are using only 1000 product items this time, as you can see in the below result, Allocated memory or other parameters hardly makes any difference between the two methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MA7s5dYPnneRJLVLLRB-aA.jpeg" /><figcaption>1000 Products Benchmark</figcaption></figure><p><strong>Conclusion</strong></p><p>Even though the <em>yield </em>enables loading of the iteration with its state management, as you have seen in the benchmark examples, as with all other situations, you need to analyze the use-case before implementing the <em>yield</em>. The impact of the right design of your application should be based on the data loading and its consumption and how quickly it has to be rendered for the end-user.</p><p><strong>References</strong></p><p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield">Yield keyword</a><br><a href="https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/june/essential-net-custom-iterators-with-yield">Custom Iterators</a><br><a href="https://benchmarkdotnet.org/articles/overview.html">Performance Benchmarking</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54dcb9a5189b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strings and Performances!]]></title>
            <link>https://medium.com/@kharavela.jain/strings-and-performances-a11dccf8a010?source=rss-45162d69610------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11dccf8a010</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[net5]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[string-performance]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Kharavela Jain]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 12:50:42 GMT</pubDate>
            <atom:updated>2021-10-04T08:53:00.707Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR;</strong></p><blockquote>Why we should try and use StringBuilder / String.Create methods to improve the performance of our application and get the best memory management results.</blockquote><blockquote>You can refer to the complete code from my <a href="https://github.com/TheCSharpGuy/StringsDemo">GitHub</a><br>Note: Benchmarks can only be run in release mode</blockquote><p><strong>Introduction</strong></p><p>We have been warned as developers throughout our C# career to carefully use string manipulations or anything related to strings in general. Mainly because of the way it consumes the memory to store and process the information. The easiest way of storing the string does cause more harm than you can imagine.</p><p>Let me explain this with simple string manipulation and check the performance of those and how we are going to do it. All I will be doing is trying to find a piece of string and replace them with some repeated characters.</p><p>Before we start, we need to include a <em>BenchmarkDotNet</em> package</p><blockquote>dotnet add package BenchmarkDotNet — version 0.13.1</blockquote><p>Now we are ready with creating our benchmark performance application.</p><p>All you would need to do is, add the following lines to your Main method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ed5d30aa3bd8ab14165f536cee65cbc/href">https://medium.com/media/3ed5d30aa3bd8ab14165f536cee65cbc/href</a></iframe><p>Now create a<em> StringBenchmarks</em> class with three methods as listed below, each having <strong>[Benchmark]</strong> attribute on top of the methods.<br>Let us start with Native strings</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3208f227c2b3e052c26c7bc982d849f8/href">https://medium.com/media/3208f227c2b3e052c26c7bc982d849f8/href</a></iframe><p>Next with a StringBuilder approach</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e8c3484c5d6f00201186201e847377d/href">https://medium.com/media/7e8c3484c5d6f00201186201e847377d/href</a></iframe><p>And finally with <em>String.Create Span&lt;T&gt;</em>, <em>which makes the string mutable!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2854f292139060b65442c88f47370c58/href">https://medium.com/media/2854f292139060b65442c88f47370c58/href</a></iframe><p>Here is the result from our string benchmark;<br>When you look at the <strong>Allocated</strong> column below, you can see that our <em>StringCreatorCase</em> used very little memory space when compared to the other two scenarios.</p><figure><img alt="The result from the Benchmarks" src="https://cdn-images-1.medium.com/max/1024/1*8FOSiSaytNtDtJFb52w0pw.jpeg" /><figcaption>The result from the Benchmarks</figcaption></figure><p><strong>Conclusion</strong></p><p>Despite being the best performer <em>String.Create</em> can only be used in high-performance scenarios. It increases the code complexity and can be confusing with <em>Span&lt;T&gt;</em> unless you know what exactly you are doing. It is worth considering the benchmark result to use in your code, as these small performance improvements help you with large data manipulation.</p><p><strong>References</strong></p><p><a href="https://benchmarkdotnet.org/articles/overview.html">Performance Benchmarking</a> <br><a href="https://docs.microsoft.com/en-us/dotnet/api/system.string.create?view=net-5.0">String.Create Method</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11dccf8a010" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>