Understanding CQRS: Command Query Responsibility Segregation

Understanding CQRS: Command Query Responsibility Segregation Command Query Responsibility Segregation (CQRS) is an architectural pattern that separates read and write operations into distinct models. This separation allows for optimization of each model independently, addressing different requirements and scaling needs. Core Components of CQRS flowchart TD Client[Client Application] --> Commands[Commands] Client --> Queries[Queries] Commands --> CommandHandler[Command Handler] Queries --> QueryHandler[Query Handler] CommandHandler --> WriteModel[Write Model/Domain Model] WriteModel --> EventStore[Event Store] EventStore --> ReadModelProjection[Read Model Projection] ReadModelProjection --> ReadModel[Read Model] QueryHandler --> ReadModel ReadModel --> QueryResults[Query Results] QueryResults --> Client Key Components and Their Responsibilities: Commands: Instructions to change state (e.g., CreateOrder, UpdateCustomer). Queries: Requests for information without state changes. Command Handler: Processes commands and applies them to the write model. Write Model: The domain model with rich business logic. Event Store: Records all state-changing events as the source of truth. Read Model Projection: Processes events to update the read model. Read Model: Optimized for querying, often denormalized for performance. Query Handler: Retrieves data from the Read Model in response to queries. The separation of write and read models allows for independent optimization, scalability, and security for both operations. ...

March 28, 2025 · 2 min · Taner

Complete Implementation of a Message Envelope Using Newtonsoft.Json

Complete Implementation using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; // For serialization and deserialization public abstract class MessageEnvelope<T> { // Immutable properties public string EventType { get; private init; } public string SourceService { get; private init; } public DateTime Timestamp { get; private init; } public Guid TraceId { get; private init; } public T Payload { get; private init; } // Private constructor to enforce the use of the builder private MessageEnvelope() { } // Static method to start building the envelope public static Builder CreateBuilder() => new Builder(); // Nested Builder class public class Builder { private readonly MessageEnvelope<T> _envelope = new ConcreteMessageEnvelope(); public Builder WithEventType(string eventType) { if (string.IsNullOrWhiteSpace(eventType)) throw new ArgumentException("EventType cannot be null or empty"); _envelope.EventType = eventType; return this; } public Builder WithSourceService(string sourceService) { if (string.IsNullOrWhiteSpace(sourceService)) throw new ArgumentException("SourceService cannot be null or empty"); _envelope.SourceService = sourceService; return this; } public Builder WithPayload(T payload) { _envelope.Payload = payload; return this; } public Builder WithTimestamp(DateTime timestamp) { _envelope.Timestamp = timestamp; return this; } public Builder WithTraceId(Guid traceId) { _envelope.TraceId = traceId; return this; } public Builder WithoutPayload() { _envelope.Payload = default; return this; } public MessageEnvelope<T> Build() { // Set defaults if not already set _envelope.EventType ??= "Unknown"; _envelope.Timestamp = _envelope.Timestamp == default ? DateTime.UtcNow : _envelope.Timestamp; _envelope.TraceId = _envelope.TraceId == default ? Guid.NewGuid() : _envelope.TraceId; return _envelope; } } // Clone method to replicate an envelope with modifications public MessageEnvelope<T> Clone() { return CreateBuilder() .WithEventType(this.EventType) .WithSourceService(this.SourceService) .WithPayload(this.Payload) .WithTimestamp(this.Timestamp) .WithTraceId(this.TraceId) .Build(); } // Serialization to JSON public string ToJson() { return JsonConvert.SerializeObject(this); } // Deserialization from JSON public static MessageEnvelope<T> FromJson(string json) { return JsonConvert.DeserializeObject<ConcreteMessageEnvelope>(json); } // Batch creation for multiple payloads public static IEnumerable<MessageEnvelope<T>> CreateBatch(IEnumerable<T> payloads, string eventType, string sourceService) { return payloads.Select(payload => CreateBuilder() .WithEventType(eventType) .WithSourceService(sourceService) .WithPayload(payload) .Build()); } // Example of a concrete implementation private class ConcreteMessageEnvelope : MessageEnvelope<T> { } } Examples 1. Basic Envelope Creation var envelope = MessageEnvelope<Reservation> .CreateBuilder() .WithEventType("ReservationExpiry") .WithSourceService("ReservationService") .WithPayload(new Reservation { ReservationId = "res-001", SlotId = "slot-123", ExpiryTime = DateTime.UtcNow }) .Build(); Console.WriteLine(envelope.ToJson()); 2. Creating an Envelope Without Payload var metadataOnlyEnvelope = MessageEnvelope<object> .CreateBuilder() .WithEventType("SystemEvent") .WithSourceService("MonitoringService") .WithoutPayload() .Build(); 3. Cloning an Envelope var clonedEnvelope = envelope.Clone(); Console.WriteLine(clonedEnvelope.ToJson()); 4. Batch Creation var reservations = new List<Reservation> { new Reservation { ReservationId = "res-001", SlotId = "slot-123", ExpiryTime = DateTime.UtcNow }, new Reservation { ReservationId = "res-002", SlotId = "slot-456", ExpiryTime = DateTime.UtcNow.AddHours(1) } }; var envelopes = MessageEnvelope<Reservation>.CreateBatch(reservations, "ReservationExpiry", "ReservationService"); foreach (var env in envelopes) { Console.WriteLine(env.ToJson()); } 5. Serialization and Deserialization string serialized = envelope.ToJson(); var deserialized = MessageEnvelope<Reservation>.FromJson(serialized); Console.WriteLine($"Deserialized TraceId: {deserialized.TraceId}"); Conclusion This implementation leverages Newtonsoft.Json to serialize and deserialize objects efficiently. The inclusion of batch creation, cloning, and flexibility makes this envelope a robust solution for designing reliable messaging systems in distributed architectures. ...

March 15, 2025 · 3 min · Taner

Getting Started with Scrutor for Dependency Injection in .NET Core

Scrutor: Enhancing Dependency Injection in .NET Core Scrutor is a lightweight library for .NET Core that enhances dependency injection (DI) by enabling automated assembly scanning and registration of services. With Scrutor, you can reduce manual configuration by automatically discovering and registering services based on conventions or attributes. How It Works Scrutor builds on top of .NET Core’s built-in Dependency Injection (DI) framework. It simplifies service registration by: Scanning Assemblies: It scans through your project’s assemblies for classes or interfaces that match certain patterns or conventions. Auto-Registering Services: It automatically registers discovered classes with the DI container, specifying their lifetimes (e.g., Transient, Scoped, or Singleton). Applying Filters: You can use predicates to include or exclude specific types during registration. How to Set It Up 1. Install Scrutor Add the NuGet package to your project: ...

March 15, 2025 · 2 min · Taner

Mastering the Retry Pattern: Enhancing Application Resiliency

Mastering the Retry Pattern: Enhancing Application Resiliency The retry pattern is a crucial design technique for improving the resiliency of applications, especially when dealing with transient faults in external systems. Let’s explore its purpose, implementation, and how it contributes to robust architecture. Purpose of the Retry Pattern Automatic Retries: Enables applications to automatically retry a failed operation due to transient faults. Graceful Error Handling: Improves user experience by addressing errors seamlessly. Increased Reliability: Allows applications to recover from temporary issues, ensuring dependable performance. Key Concepts of the Retry Pattern Transient Faults: Temporary issues like network glitches, timeouts, or service throttling that are likely to succeed upon retry. Retry Interval: The delay between attempts, which can follow a fixed interval, exponential backoff, or a custom logic. Max Retry Attempts: Specifies the maximum number of retries before declaring the operation as failed. Implementation Example in C# Here’s how to implement a retry pattern using C#: ...

March 15, 2025 · 3 min · TC

Message Envelopes in Message-Based Software Development

Message Envelopes in Message-Based Software Development In message-based software development, message envelopes are a design pattern used to wrap the core message with additional metadata. This metadata helps the messaging system process, route, or interpret the message without needing to understand its actual content. Key Features of Message Envelopes Header and Body Separation: The header contains metadata like routing information, encryption details, or timestamps. The body holds the actual message payload. Flexibility: ...

March 15, 2025 · 2 min · Taner

Two-Phase Commit (2PC) vs Outbox Pattern: Ensuring Data Consistency

Two-Phase Commit (2PC) vs Outbox Pattern: Ensuring Data Consistency The Two-Phase Commit (2PC) Pattern and the Outbox Pattern are two prominent strategies for achieving data consistency in distributed systems. While they both solve similar problems, they employ different approaches. Let’s dive into these patterns to help you determine which is best suited for your application needs. Two-Phase Commit (2PC) Pattern The 2PC Pattern is a distributed protocol designed to ensure that all participants in a distributed transaction either commit or rollback their changes, maintaining data consistency across systems. ...

March 15, 2025 · 4 min · Taner

Updated Implementation Using `System.Text.Json`

Updated Implementation Using System.Text.Json using System; using System.Text.Json; using System.Text.Json.Serialization; public abstract class MessageEnvelope<T> { // Properties remain immutable public string EventType { get; private init; } public string SourceService { get; private init; } public DateTime Timestamp { get; private init; } public Guid TraceId { get; private init; } public T Payload { get; private init; } // Private constructor for builder use only private MessageEnvelope() { } public static Builder CreateBuilder() => new Builder(); // Serialization to JSON public string ToJson() { var options = new JsonSerializerOptions { WriteIndented = true // Makes the output JSON easier to read }; return JsonSerializer.Serialize(this, options); } // Deserialization from JSON public static MessageEnvelope<T> FromJson(string json) { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true // Handles case differences in JSON properties }; return JsonSerializer.Deserialize<ConcreteMessageEnvelope>(json, options); } // Concrete implementation example for proper deserialization private class ConcreteMessageEnvelope : MessageEnvelope<T> { } public class Builder { private readonly MessageEnvelope<T> _envelope = new ConcreteMessageEnvelope(); public Builder WithEventType(string eventType) { _envelope.EventType = eventType; return this; } public Builder WithSourceService(string sourceService) { _envelope.SourceService = sourceService; return this; } public Builder WithPayload(T payload) { _envelope.Payload = payload; return this; } public Builder WithTimestamp(DateTime timestamp) { _envelope.Timestamp = timestamp; return this; } public Builder WithTraceId(Guid traceId) { _envelope.TraceId = traceId; return this; } public MessageEnvelope<T> Build() { _envelope.Timestamp = _envelope.Timestamp == default ? DateTime.UtcNow : _envelope.Timestamp; _envelope.TraceId = _envelope.TraceId == default ? Guid.NewGuid() : _envelope.TraceId; return _envelope; } } } Example Usage 1. Serialize a MessageEnvelope to JSON var envelope = MessageEnvelope<Reservation> .CreateBuilder() .WithEventType("ReservationExpiry") .WithSourceService("ReservationService") .WithPayload(new Reservation { ReservationId = "res-001", SlotId = "slot-123", ExpiryTime = DateTime.UtcNow }) .Build(); string serialized = envelope.ToJson(); Console.WriteLine($"Serialized Envelope:\n{serialized}"); 2. Deserialize a JSON String to MessageEnvelope string json = "{\"EventType\":\"ReservationExpiry\",\"SourceService\":\"ReservationService\",\"Timestamp\":\"2025-03-25T17:00:00Z\",\"TraceId\":\"8a1db2c2-ec3e-45f7-a3eb-bd9dfb351245\",\"Payload\":{\"ReservationId\":\"res-001\",\"SlotId\":\"slot-123\",\"ExpiryTime\":\"2025-03-25T17:00:00Z\"}}"; var deserializedEnvelope = MessageEnvelope<Reservation>.FromJson(json); Console.WriteLine($"Deserialized EventType: {deserializedEnvelope.EventType}"); Console.WriteLine($"Deserialized Reservation ID: {deserializedEnvelope.Payload.ReservationId}"); Benefits of Serialization Portability: You can transmit envelopes as JSON over APIs, message brokers, or store them in databases. Interoperability: Many systems can parse JSON, making serialized envelopes easy to integrate across platforms. Flexibility: Deserialization lets you reconstruct envelopes when receiving messages. Advantages of System.Text.Json Performance: Faster than Newtonsoft.Json, especially for large-scale applications. Built-in Support: No need for external dependencies; it’s natively part of .NET Core and .NET 5+. Configuration Options: Flexible JSON options like camel casing, case insensitivity, and indented formatting.

March 15, 2025 · 2 min · Taner