cqrs-architecture
CQRS pattern implementation and query optimization
What this skill does
# CQRS Architecture Skill
Design and implement Command Query Responsibility Segregation patterns for scalable systems.
## MANDATORY: Documentation-First Approach
Before implementing CQRS:
1. **Invoke `docs-management` skill** for CQRS patterns
2. **Verify patterns** via MCP servers (perplexity, context7)
3. **Base guidance on established CQRS literature**
## CQRS Fundamentals
```text
Traditional vs CQRS:
TRADITIONAL (Single Model):
┌─────────────────────────────────┐
│ Application │
├─────────────────────────────────┤
│ Domain Model │
│ (Reads + Writes) │
├─────────────────────────────────┤
│ Database │
└─────────────────────────────────┘
CQRS (Separated Models):
┌───────────────┐ ┌───────────────┐
│ Command Side │ │ Query Side │
│ (Write Model) │ │ (Read Model) │
├───────────────┤ ├───────────────┤
│ Domain Logic │ │ DTO/Views │
│ Aggregates │ │ Projections │
├───────────────┤ ├───────────────┤
│ Write DB │───►│ Read DB │
└───────────────┘ └───────────────┘
```
## CQRS Levels
### Level 1: Logical Separation
```text
Same database, separate code paths:
┌─────────────────────────────────────┐
│ Application │
├──────────────────┬──────────────────┤
│ Command Handlers │ Query Handlers │
│ - Validation │ - Direct SQL │
│ - Domain Logic │ - Projections │
│ - Events │ - DTOs │
├──────────────────┴──────────────────┤
│ Single Database │
└─────────────────────────────────────┘
Benefits:
✓ Clean separation in code
✓ Simple deployment
✓ Single source of truth
✓ Good starting point
```
### Level 2: Separate Read Models
```text
Same write DB, separate read DB:
┌─────────────────┐ ┌─────────────────┐
│ Command Side │ │ Query Side │
├─────────────────┤ ├─────────────────┤
│ Command Handler │ │ Query Handler │
│ Domain Model │ │ DTOs │
├─────────────────┤ ├─────────────────┤
│ Write Database │───►│ Read Database │
│ (Normalized) │sync│ (Denormalized) │
└─────────────────┘ └─────────────────┘
Benefits:
✓ Optimized read performance
✓ Scale reads independently
✓ Different storage technologies
✓ Eventually consistent reads
```
### Level 3: Event-Sourced CQRS
```text
Event store as write model, projections as read:
┌─────────────────┐ ┌─────────────────┐
│ Command Side │ │ Query Side │
├─────────────────┤ ├─────────────────┤
│ Command Handler │ │ Query Handler │
│ Aggregate │ │ Read Models │
├─────────────────┤ ├─────────────────┤
│ Event Store │───►│ Multiple Read │
│ (Append-only) │ │ Databases │
└─────────────────┘ └─────────────────┘
Benefits:
✓ Complete audit trail
✓ Temporal queries
✓ Multiple projections
✓ Rebuild read models
```
## Command Side Design
### Command Structure
```csharp
// Command Definition
public record PlaceOrderCommand(
Guid CustomerId,
List<OrderItemDto> Items,
string ShippingAddress
) : ICommand<OrderId>;
// Command Handler
public class PlaceOrderHandler : ICommandHandler<PlaceOrderCommand, OrderId>
{
private readonly IOrderRepository _repository;
private readonly IEventPublisher _events;
public async Task<OrderId> HandleAsync(
PlaceOrderCommand command,
CancellationToken ct)
{
// Validation
if (!command.Items.Any())
throw new ValidationException("Order must have items");
// Domain logic
var order = Order.Create(
command.CustomerId,
command.Items.Select(i => new OrderItem(i.ProductId, i.Quantity)));
// Persistence
await _repository.SaveAsync(order, ct);
// Publish events
await _events.PublishAsync(order.GetDomainEvents(), ct);
return order.Id;
}
}
```
### Command Patterns
```text
Command Best Practices:
NAMING:
- Imperative: PlaceOrder, CancelOrder, UpdateAddress
- Include context: not just "Create" but "CreateOrder"
STRUCTURE:
- Immutable (records)
- Only data needed for operation
- No business logic in command
VALIDATION:
- Input validation in handler
- Business validation in domain
- Return meaningful errors
IDEMPOTENCY:
- Include idempotency key
- Handle duplicate submissions
- Return same result for retries
```
## Query Side Design
### Query Structure
```csharp
// Query Definition
public record GetOrderByIdQuery(Guid OrderId) : IQuery<OrderDetailsDto>;
// Query Handler
public class GetOrderByIdHandler : IQueryHandler<GetOrderByIdQuery, OrderDetailsDto>
{
private readonly IReadDbContext _db;
public async Task<OrderDetailsDto> HandleAsync(
GetOrderByIdQuery query,
CancellationToken ct)
{
var order = await _db.OrderDetails
.Where(o => o.OrderId == query.OrderId)
.Select(o => new OrderDetailsDto
{
OrderId = o.OrderId,
CustomerName = o.Customer.Name,
Items = o.Items.Select(i => new OrderItemDto
{
ProductName = i.ProductName,
Quantity = i.Quantity,
Price = i.Price
}).ToList(),
Status = o.Status,
TotalAmount = o.TotalAmount
})
.FirstOrDefaultAsync(ct);
return order ?? throw new NotFoundException("Order not found");
}
}
```
### Read Model Optimization
```text
Query Optimization Strategies:
1. DENORMALIZATION
- Pre-join data
- Store calculated values
- Flatten hierarchies
2. MATERIALIZED VIEWS
- Database-managed
- Automatically updated
- Query-optimized
3. CACHING
- In-memory for hot data
- Distributed for shared
- Invalidate on events
4. SPECIALIZED STORES
- ElasticSearch for search
- Redis for real-time
- ClickHouse for analytics
```
## Synchronization Patterns
### Projection from Events
```csharp
// Event-Driven Projection
public class OrderProjection : IEventHandler<OrderPlaced>, IEventHandler<OrderShipped>
{
private readonly IOrderViewRepository _views;
public async Task HandleAsync(OrderPlaced @event, CancellationToken ct)
{
var view = new OrderView
{
OrderId = @event.OrderId,
CustomerId = @event.CustomerId,
Status = "Placed",
PlacedAt = @event.Timestamp,
ItemCount = @event.Items.Count,
TotalAmount = @event.TotalAmount
};
await _views.InsertAsync(view, ct);
}
public async Task HandleAsync(OrderShipped @event, CancellationToken ct)
{
await _views.UpdateAsync(@event.OrderId, view =>
{
view.Status = "Shipped";
view.ShippedAt = @event.Timestamp;
view.TrackingNumber = @event.TrackingNumber;
}, ct);
}
}
```
### Consistency Patterns
```text
Consistency Options:
STRONG CONSISTENCY (Same Transaction):
┌──────────┐ ┌──────────┐
│ Command │───►│ Read │
│ DB │ │ Model │
│ │ │ Update │
└──────────┴────┴──────────┘
Same Transaction
EVENTUAL CONSISTENCY (Async):
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Command │───►│ Message │───►│ Read │
│ DB │ │ Queue │ │ Model │
└──────────┘ └──────────┘ └──────────┘
Async, Eventually Consistent
HYBRID (Read-Your-Writes):
- Immediate read from command side
- Eventually consistent for others
- Version checking in queries
```
## MediatR Implementation
### Setup with MediatR
```csharp
// Registration
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
});
// Command/Query Interfaces
public interface ICommand<TResult> : IRequest<TResult> { }
public interface IQuery<TResult> : IRequest<TResult> { }
// Handler Interfaces
public interface ICommandHandler<TCommand, TResult>
: IRequestHRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.