Moonglade

Modern Markdown blogging with AI-powered localization and search.

All Posts


Have you been using C# records from 3 years ago?

Have you been using C# records from 3 years ago?

In C#, the `record` type is essentially a class with additional features, including immutability, value semantics, and deconstruction, making it suitable for scenarios such as DTOs, domain events, and value objects. The article provides an in-depth analysis of the differences between `record`, `class`, and `struct` at the memory level, pointing out that although `record` is a reference type, it exhibits value semantics and is managed by the garbage collector. Despite the fact that `record` can significantly enhance code quality, safety, and maintainability, it has been largely overlooked in the current market environment, which prioritizes rapid iteration, because it does not directly alleviate the pressure of business delivery. The author reflects that this neglect of code quality reflects a deviation in the industry's values. Finally, using the rise of AI tools such as ChatGPT as a starting point, the article expresses concern about the future career prospects of programmers, suggesting that in a context where AI efficiently produces code, traditional attention to code details such as `record` features may become irrelevant.

Views 127
.NET C# Data Modeling Immutability Record Value Semantics

A Postgres vs. MySQL Selection Guide Even Goldfish Can Understand

A Postgres vs. MySQL Selection Guide Even Goldfish Can Understand

Through concise guides, engaging analogies, and detailed analysis, this article provides an in-depth comparison of Postgres and MySQL, two major open-source relational databases. Although both support SQL and JSON, they differ significantly in their core features: Postgres is powerful and highly extensible, supporting complex queries, custom types, and advanced encryption, with superior data integrity and concurrency control, making it suitable for handling large-scale datasets and complex enterprise-level business scenarios; MySQL, on the other hand, excels in simplicity, ease of use, and rapid deployment, offering excellent read-operation performance and a mature ecosystem, making it an ideal choice for small-to-medium-sized web applications and high-concurrency, read-intensive scenarios. The article points out that if you prioritize advanced features, security, and complex data analysis, Postgres is the better solution; if you focus on quick startup, ease of use, and high-speed transaction processing, MySQL holds the advantage. Ultimately, the choice should be based on specific business needs, balancing feature depth against deployment efficiency to achieve the best fit.

Views 130
ACID Compliance Advanced Features DB MySQL OLTP PostgreSQL

Struggling to debug production microservices? Get to know OpenTelemetry. ★

Struggling to debug production microservices? Get to know OpenTelemetry.

This article provides an in-depth introduction to the concept of observability and the application of OpenTelemetry in .NET microservice systems. It begins with a practical case study running on K8s, demonstrating how to leverage OpenTelemetry and Jaeger to implement distributed tracing. This allows for visual analysis of request latency and paths across various services, enabling precise identification of performance bottlenecks. Subsequently, the article elaborates on the three pillars of OpenTelemetry: Traces, Metrics, and Logs. Traces associate dispersed request contexts through Spans, providing a full-chain view. Metrics serve as aggregated numerical data for monitoring infrastructure status, service performance, and business metrics, supporting various instrument types and aggregation methods. Logs address the pain points of traditional logging in distributed systems, such as lack of context correlation, inconsistent data models, and integration difficulties, thereby achieving seamless association between logs, traces, and metrics. Through a unified data model and standardized protocols, OpenTelemetry helps developers collect telemetry data cross-platform and cross-language, quickly diagnose production issues, optimize system performance, and enhance overall system observability and stability, providing robust support for fault troubleshooting and business analysis in microservice architectures.

Views 136
.NET Distributed Tracing Jaeger Microservices Observability OpenTelemetry

Why Is My API Slow as a Snail? Series Table of Contents and Guide ★

This series of articles aims to address the challenges of slow API response times and difficult fault debugging in production environments, systematically introducing methods for analyzing and handling online issues. The first part focuses on how to use Serilog to configure comprehensive structured logging, capturing critical timing and diagnostic information, and leveraging Seq for centralized log management, thereby helping developers easily analyze logs and quickly pinpoint performance bottlenecks. The second part delves into the application of OpenTelemetry, demonstrating how to achieve correlated analysis of distributed tracing, metrics, and logs through a unified framework, thereby enhancing the reliability and operational efficiency of software systems. This series is suitable for developers and operations personnel who wish to optimize system performance, monitor runtime status, and rapidly identify root causes. All articles are simultaneously published on WeChat Official Accounts and both domestic and international blog platforms, facilitating multi-platform reading and learning for readers.

Views 173
.NET OpenTelemetry Performance Serilog performance analysis structured logging

Why is my API as slow as a snail? - 3. Seq Centralized Structured Logging Service

This article is the third in the "Why Is My API as Slow as a Snail?" series, focusing on how to use Seq for centralized collection and analysis of logs from multiple instances. The article first compares Seq with ELK, noting that Seq is more lightweight and easier to deploy, making it suitable for quickly setting up a logging center. It then provides a detailed demonstration of how to quickly deploy the Seq service using Docker and explains the meaning of key configuration parameters. Next, the author shows how to integrate `Serilog.Sinks.Seq`, requiring only a few lines of code in the configuration file to push application logs to Seq in real time. Finally, using Seq's Web interface and a SQL-like query syntax, it is easy to filter out request logs with a duration exceeding 1000ms, thereby precisely locating the code causing performance bottlenecks. This solution addresses the challenge of cross-instance analysis associated with traditional local logs, providing a data-driven basis for performance optimization rather than relying on guesswork, and laying the foundation for subsequent in-depth Tracing analysis.

Views 184
.NET Logging Performance Seq Web API performance analysis

Why Is My API Slow as a Snail? - 2. Serilog Timing and Diagnostic Logging

This article introduces how to leverage Serilog in ASP.NET Core to achieve efficient performance measurement and diagnostics. First, by integrating the SerilogTimings package, you can use the Operation.Time context manager to easily record the execution time of code snippets, transforming vague performance guesses into precise structured data, which helps quickly pinpoint performance bottlenecks in database queries or I/O tasks. Second, by enabling the UseSerilogRequestLogging middleware, the system can automatically log each HTTP request's method, path, status code, and total duration, and generate a unique RequestId, facilitating the correlation and analysis of a single request's complete lifecycle in the logs. Additionally, the article demonstrates how to customize the message template for request logs, as well as how to inject IDiagnosticContext to append business metadata such as UserId and Username to the logs, thereby enabling precise tracking of specific user behavior trajectories. These practices greatly simplify the process of troubleshooting production issues, allowing teams to shift from passive guessing to data-driven precise optimization, significantly enhancing the quality of software services and operational efficiency.

Views 151
.NET Diagnostic Information HTTP Request Logging Performance Serilog Timing Metrics

Why is my API slow as a snail? - 1. Using Serilog Structured Logging

This article introduces the complete process of integrating Serilog into ASP.NET Core 7 to implement structured logging. First, install the Serilog.AspNetCore package and utilize its built-in Console, Debug, and File Sinks; for monolithic applications, configuring file logging alone is sufficient to meet the requirements. Second, modify the configuration file to define log levels, output destinations, and formatters. Use a compact JSON format for logging and enable contextual information such as machine name and thread ID. Next, take over the default logging system in Program.cs by using Host.UseSerilog, and output logs in the controller for verification. For exceptions during the application startup phase, configure a Bootstrap Logger using Serilog's global static Log class, combined with a Try-Catch-Finally structure to ensure that startup errors are fully recorded. Finally, the article demonstrates that the generated structured logs contain key tracking data such as ActionId and RequestId, and recommends choosing to store logs in a database or using tools like Seq for centralized analysis and management based on team needs.

Views 151
.NET ASP.NET Core C# Performance Serilog Web API

.NET Performance Tips: Why You Should Avoid Using Finalizers?

This article provides an in-depth exploration of why developers should avoid using finalizers in .NET and their performance impact. It points out that finalizers cause objects to be promoted to a higher generation, preventing them from being quickly reclaimed in Generation 0, and requiring them to wait for a dedicated finalizer thread to execute. This significantly increases memory usage and garbage collection cycles, leading to uncontrollable performance overhead. Benchmark test data shows that when creating and releasing the same number of objects, classes with finalizers take approximately 18 times longer, or even more, than regular classes, with the specific gap depending on the environment. The article advises developers to avoid using finalizers and instead adopt the standard pattern of implementing the `IDisposable` interface in conjunction with the `GC.SuppressFinalize` method to release resources. This approach not only offers controlled execution time and superior performance but also effectively avoids potential resource leaks and unpredictable program behavior, making it the best practice for ensuring stability in .NET applications under high-concurrency scenarios.

Views 142
.NET Finalizer IDisposable Performance garbage collection performance optimization

Do You Really Need Autofac? Scrutor: A Lighter Container Companion

The article first dissects the ServiceLocator anti-pattern, pointing out that accessing services through global static instances in ASP.NET Core leads to high code coupling, difficulty in testing, and poor scalability. It recommends switching to the standard dependency injection container. Subsequently, the article introduces Scrutor, a lightweight extension library, as an effective alternative to Autofac. Scrutor supports batch service registration through assembly scanning and provides various flexible configuration methods, including registration based on name matching or implemented interfaces, restricting to specific namespaces, uniformly setting lifetimes, and precisely controlling the lifetimes of different service instances (Transient, Scoped, Singleton) via marker interfaces or custom Attributes. Additionally, Scrutor simplifies the implementation of the decorator pattern, requiring only two lines of code to complete decorator registration. In summary, if a project primarily relies on Autofac for batch registration or implementing decorators, and does not deeply utilize the ServiceLocator, Scrutor can serve as an ideal lightweight alternative with less code and higher readability, helping developers simplify dependency management while maintaining best practices.

Views 147
.NET BatchRegistration DecoratorPattern DependencyInjection LightweightLibrary ServiceLocator

Which One Is Right for You? A Guide to Choosing Between IEnumerable, IQueryable, and ICollection

Which One Is Right for You? A Guide to Choosing Between IEnumerable, IQueryable, and ICollection

This article provides an in-depth analysis of the selection strategies for collection interfaces in C#, with a focus on the characteristics and application scenarios of `IEnumerable<T>`, `IQueryable<T>`, and `IReadOnlyCollection<T>`. The article points out that blindly using `IEnumerable<T>` can easily lead to performance issues or logical errors caused by multiple iterations, such as the repeated execution of asynchronous tasks. Although `IQueryable<T>` can improve ORM query efficiency, it carries the risk of abstraction leakage and should not be used as the return type of public methods. It is recommended to use it internally within the Repository layer and convert it using `AsEnumerable()`. To enhance code maintainability and prevent callers from inadvertently modifying the data source, it is recommended that methods return `IReadOnlyCollection<T>` or `IReadOnlyList<T>`. This not only clarifies the contract of collection immutability but also avoids resource release anomalies caused by deferred evaluation. Summary recommendation: Prioritize `IEnumerable<T>` for input parameters, while preferring read-only interfaces when returning collections, to balance flexibility, performance, and security.

Views 196
.NET C# Code Quality IEnumerator IQueryable Lazy Evaluation