Full Lifecycle -- One Service, All 22 DSLs
Part 23 showed the complete composition. This part walks through building it. One attribute group at a time, with commentary on what each group generates and why it exists. By the end, a single C# class produces every operational artifact OrderService needs -- deployment manifests, migration plans, health checks, alerts, chaos experiments, load tests, compliance evidence, cost budgets, and more.
The rule is absolute: every file in the output is generated. Docker Compose, Kubernetes manifests, Terraform modules, Prometheus alert rules, Grafana dashboards, k6 scripts, Litmus experiments, Polly policies, ASP.NET middleware, xUnit fixtures, compliance matrices, bash orchestration scripts. All of it comes from dotnet build. The developer writes C# attributes and nothing else. dotnet ops run --tier inprocess|container|cloud executes the generated artifacts at the chosen tier.
The Starting Point
An empty partial class:
// OrderServiceV3Ops.cs
public partial class OrderServiceV3Ops { }// OrderServiceV3Ops.cs
public partial class OrderServiceV3Ops { }We will add attributes in four phases. Each phase is a logical group of concerns. The order follows the lifecycle of a service: first you deploy it, then you observe it, then you stress-test it, then you govern it.
Phase 1: Core Operations
The attributes that get a service running, observable, and recoverable.
Deployment (Part 5)
[DeploymentOrchestrator("order-platform", Version = "3.0",
Apps = new[] { "order-api", "order-worker", "order-scheduler" },
DependsOn = new[] { "postgres-16", "redis-7", "rabbitmq-3" })]
[DeploymentApp("order-api",
Image = "order-api",
Port = 8080,
Replicas = 3,
ReadinessPath = "/health/ready",
LivenessPath = "/health/live")]
[DeploymentApp("order-worker",
Image = "order-worker",
Replicas = 2)]
[DeploymentApp("order-scheduler",
Image = "order-scheduler",
Replicas = 1,
CronSchedule = "*/5 * * * *")]
[CanaryStrategy(
InitialWeight = 5,
StepWeight = 15,
StepInterval = "5m",
ErrorRateThreshold = 1.0,
LatencyP99Threshold = "500ms")][DeploymentOrchestrator("order-platform", Version = "3.0",
Apps = new[] { "order-api", "order-worker", "order-scheduler" },
DependsOn = new[] { "postgres-16", "redis-7", "rabbitmq-3" })]
[DeploymentApp("order-api",
Image = "order-api",
Port = 8080,
Replicas = 3,
ReadinessPath = "/health/ready",
LivenessPath = "/health/live")]
[DeploymentApp("order-worker",
Image = "order-worker",
Replicas = 2)]
[DeploymentApp("order-scheduler",
Image = "order-scheduler",
Replicas = 1,
CronSchedule = "*/5 * * * *")]
[CanaryStrategy(
InitialWeight = 5,
StepWeight = 15,
StepInterval = "5m",
ErrorRateThreshold = 1.0,
LatencyP99Threshold = "500ms")]Five attributes. The generator produces: Kubernetes Deployment manifests for each app, a Flagger Canary CRD for the canary strategy, a Helm values file, and a deployment ordering DAG that respects the DependsOn chain. The analyzer validates that every DependsOn reference matches a known infrastructure component.
Migration (Part 6)
[SchemaMigration("047_add_order_metadata",
Up = "ALTER TABLE orders ADD COLUMN metadata jsonb;",
Down = "ALTER TABLE orders DROP COLUMN metadata;",
Timeout = "30s")]
[IndexMigration("048_idx_order_metadata",
Table = "orders",
Columns = new[] { "metadata" },
Type = IndexType.GIN,
Concurrent = true,
DependsOn = "047_add_order_metadata")]
[DataMigration("backfill_order_metadata",
DependsOn = "048_idx_order_metadata",
BatchSize = 1000,
EstimatedRows = 5_000_000)]
[SeedMigration("seed_order_statuses",
Table = "order_statuses",
Data = "pending,processing,completed,cancelled,refunded")][SchemaMigration("047_add_order_metadata",
Up = "ALTER TABLE orders ADD COLUMN metadata jsonb;",
Down = "ALTER TABLE orders DROP COLUMN metadata;",
Timeout = "30s")]
[IndexMigration("048_idx_order_metadata",
Table = "orders",
Columns = new[] { "metadata" },
Type = IndexType.GIN,
Concurrent = true,
DependsOn = "047_add_order_metadata")]
[DataMigration("backfill_order_metadata",
DependsOn = "048_idx_order_metadata",
BatchSize = 1000,
EstimatedRows = 5_000_000)]
[SeedMigration("seed_order_statuses",
Table = "order_statuses",
Data = "pending,processing,completed,cancelled,refunded")]Four migration steps with explicit dependencies. The generator produces a migration runner that executes them in dependency order, with parallel execution where the DAG allows. The concurrent index creation runs without locking the table. The data migration runs in batches of 1000 to avoid locking 5 million rows.
Observability (Part 7)
[HealthCheck("database",
Type = HealthCheckType.Dependency,
Interval = "10s",
Timeout = "3s",
FailureThreshold = 3)]
[HealthCheck("redis-cache",
Type = HealthCheckType.Dependency,
Interval = "10s",
Timeout = "2s")]
[HealthCheck("rabbitmq",
Type = HealthCheckType.Dependency,
Interval = "15s",
Timeout = "5s")]
[MetricDefinition("order_created_total",
Type = MetricType.Counter,
Description = "Total orders created",
Labels = new[] { "payment_method", "region" })]
[MetricDefinition("order_processing_duration_seconds",
Type = MetricType.Histogram,
Description = "Order processing duration",
Buckets = new[] { 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0 })]
[MetricDefinition("order_queue_depth",
Type = MetricType.Gauge,
Description = "Current order processing queue depth")]
[MetricDefinition("payment_gateway_request_duration_seconds",
Type = MetricType.Histogram,
Description = "Payment gateway response time",
Buckets = new[] { 0.05, 0.1, 0.25, 0.5, 1.0, 2.5 })]
[MetricDefinition("order_total_amount",
Type = MetricType.Histogram,
Description = "Order monetary value distribution",
Buckets = new[] { 10, 50, 100, 500, 1000, 5000 })]
[AlertRule("HighErrorRate",
Condition = "rate(http_requests_total{status=~'5..'}[5m]) > 0.05",
Severity = AlertSeverity.Critical,
NotifyChannel = "ops-critical")]
[AlertRule("SlowQueries",
Condition = "histogram_quantile(0.99, order_processing_duration_seconds) > 5",
Severity = AlertSeverity.Warning,
NotifyChannel = "ops-warnings")]
[AlertRule("QueueBackpressure",
Condition = "order_queue_depth > 1000",
Severity = AlertSeverity.Warning,
NotifyChannel = "ops-warnings")]
[GrafanaDashboard("order-service-overview",
Rows = new[] { "throughput", "latency", "errors", "dependencies" })][HealthCheck("database",
Type = HealthCheckType.Dependency,
Interval = "10s",
Timeout = "3s",
FailureThreshold = 3)]
[HealthCheck("redis-cache",
Type = HealthCheckType.Dependency,
Interval = "10s",
Timeout = "2s")]
[HealthCheck("rabbitmq",
Type = HealthCheckType.Dependency,
Interval = "15s",
Timeout = "5s")]
[MetricDefinition("order_created_total",
Type = MetricType.Counter,
Description = "Total orders created",
Labels = new[] { "payment_method", "region" })]
[MetricDefinition("order_processing_duration_seconds",
Type = MetricType.Histogram,
Description = "Order processing duration",
Buckets = new[] { 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0 })]
[MetricDefinition("order_queue_depth",
Type = MetricType.Gauge,
Description = "Current order processing queue depth")]
[MetricDefinition("payment_gateway_request_duration_seconds",
Type = MetricType.Histogram,
Description = "Payment gateway response time",
Buckets = new[] { 0.05, 0.1, 0.25, 0.5, 1.0, 2.5 })]
[MetricDefinition("order_total_amount",
Type = MetricType.Histogram,
Description = "Order monetary value distribution",
Buckets = new[] { 10, 50, 100, 500, 1000, 5000 })]
[AlertRule("HighErrorRate",
Condition = "rate(http_requests_total{status=~'5..'}[5m]) > 0.05",
Severity = AlertSeverity.Critical,
NotifyChannel = "ops-critical")]
[AlertRule("SlowQueries",
Condition = "histogram_quantile(0.99, order_processing_duration_seconds) > 5",
Severity = AlertSeverity.Warning,
NotifyChannel = "ops-warnings")]
[AlertRule("QueueBackpressure",
Condition = "order_queue_depth > 1000",
Severity = AlertSeverity.Warning,
NotifyChannel = "ops-warnings")]
[GrafanaDashboard("order-service-overview",
Rows = new[] { "throughput", "latency", "errors", "dependencies" })]Thirteen attributes. The generator produces: ASP.NET health check registrations, IMeterFactory metric declarations, Prometheus alerting rules, and a Grafana dashboard JSON model. The analyzer cross-references: every [MetricDefinition] used in an [AlertRule] must exist. Every dependency in [HealthCheck] must match a [DependsOn] target in the deployment.
Configuration and Resilience (Part 8)
[EnvironmentTransform("Development",
Setting = "ConnectionStrings:Orders", Value = "Host=localhost;Port=5432;Database=orders_dev")]
[EnvironmentTransform("Staging",
Setting = "ConnectionStrings:Orders", Value = "Host=pg-staging;Database=orders_stg")]
[EnvironmentTransform("Production",
Setting = "ConnectionStrings:Orders", Source = SecretSource.KeyVault,
SecretName = "order-db-connection-string")]
[EnvironmentTransform("Production",
Setting = "PaymentGateway:ApiKey", Source = SecretSource.KeyVault,
SecretName = "payment-api-key")]
[SecretRotation("order-db-connection-string",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "90d",
GracePeriod = "7d")]
[SecretRotation("payment-api-key",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "30d",
GracePeriod = "3d")]
[CircuitBreaker(typeof(IPaymentGateway),
FailureThreshold = 5,
BreakDuration = "30s",
SamplingWindow = "60s")]
[RetryPolicy(typeof(IRabbitMqPublisher),
MaxRetries = 3,
BackoffType = BackoffType.Exponential,
InitialDelay = "100ms")]
[RollbackPlan(
Trigger = "error_rate > 5%",
Strategy = RollbackStrategy.Canary,
AutoRollback = true)][EnvironmentTransform("Development",
Setting = "ConnectionStrings:Orders", Value = "Host=localhost;Port=5432;Database=orders_dev")]
[EnvironmentTransform("Staging",
Setting = "ConnectionStrings:Orders", Value = "Host=pg-staging;Database=orders_stg")]
[EnvironmentTransform("Production",
Setting = "ConnectionStrings:Orders", Source = SecretSource.KeyVault,
SecretName = "order-db-connection-string")]
[EnvironmentTransform("Production",
Setting = "PaymentGateway:ApiKey", Source = SecretSource.KeyVault,
SecretName = "payment-api-key")]
[SecretRotation("order-db-connection-string",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "90d",
GracePeriod = "7d")]
[SecretRotation("payment-api-key",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "30d",
GracePeriod = "3d")]
[CircuitBreaker(typeof(IPaymentGateway),
FailureThreshold = 5,
BreakDuration = "30s",
SamplingWindow = "60s")]
[RetryPolicy(typeof(IRabbitMqPublisher),
MaxRetries = 3,
BackoffType = BackoffType.Exponential,
InitialDelay = "100ms")]
[RollbackPlan(
Trigger = "error_rate > 5%",
Strategy = RollbackStrategy.Canary,
AutoRollback = true)]Nine attributes. The generator produces: appsettings.{Environment}.json transforms, Key Vault secret references, Polly resilience pipelines wrapping the target interfaces as Injectable decorators, and a rollback script triggered by the canary error threshold.
Phase 1 total: 31 attributes. The service deploys, migrates, is observable, configurable, and resilient. Every generated artifact is consistent with every other because they share the same source declarations.
Phase 2: Performance and Reliability
The attributes that prove the service works under stress and attack.
Performance (Part 9)
[ServiceLevelIndicator("availability",
Metric = "1 - (rate(http_requests_total{status=~'5..'}[5m]) / rate(http_requests_total[5m]))")]
[ServiceLevelIndicator("latency",
Metric = "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))")]
[ServiceLevelObjective("availability", Target = 99.9, Window = "30d",
BurnRateAlert = true, BurnRateThreshold = 14.4)]
[ServiceLevelObjective("latency", Target = 99.0, Window = "30d",
ThresholdMs = 500)]
[EndpointBudget("POST /api/orders", P95 = "200ms", P99 = "500ms", MaxRPS = 500)]
[EndpointBudget("GET /api/orders/{id}", P95 = "50ms", P99 = "200ms", MaxRPS = 2000)]
[EndpointBudget("GET /api/orders", P95 = "100ms", P99 = "300ms", MaxRPS = 1000)]
[CachePolicy("order-by-id",
TTL = "5m",
Strategy = CacheStrategy.ReadThrough,
InvalidateOn = new[] { "order.updated", "order.cancelled" })][ServiceLevelIndicator("availability",
Metric = "1 - (rate(http_requests_total{status=~'5..'}[5m]) / rate(http_requests_total[5m]))")]
[ServiceLevelIndicator("latency",
Metric = "histogram_quantile(0.99, rate(http_request_duration_seconds_bucket[5m]))")]
[ServiceLevelObjective("availability", Target = 99.9, Window = "30d",
BurnRateAlert = true, BurnRateThreshold = 14.4)]
[ServiceLevelObjective("latency", Target = 99.0, Window = "30d",
ThresholdMs = 500)]
[EndpointBudget("POST /api/orders", P95 = "200ms", P99 = "500ms", MaxRPS = 500)]
[EndpointBudget("GET /api/orders/{id}", P95 = "50ms", P99 = "200ms", MaxRPS = 2000)]
[EndpointBudget("GET /api/orders", P95 = "100ms", P99 = "300ms", MaxRPS = 1000)]
[CachePolicy("order-by-id",
TTL = "5m",
Strategy = CacheStrategy.ReadThrough,
InvalidateOn = new[] { "order.updated", "order.cancelled" })]Eight attributes. The generator produces: Prometheus recording rules for SLIs, multi-burn-rate alert rules for SLOs, and cache configuration with event-driven invalidation.
Load Testing (Part 10)
[LoadTest("Smoke", Tier = OpsExecutionTier.InProcess)]
[LoadProfile(ConcurrentUsers = 10, Duration = "60s")]
[LoadTestEndpoint("POST", "/api/orders")]
[LoadTestThreshold(P95 = "200ms", MaxErrorRate = 0.0)]
[LoadTest("Soak", Tier = OpsExecutionTier.Container)]
[LoadProfile(ConcurrentUsers = 100, Duration = "30m")]
[LoadTestEndpoint("POST", "/api/orders")]
[LoadTestEndpoint("GET", "/api/orders/{id}", Weight = 3)]
[LoadTestThreshold(P95 = "300ms", P99 = "1s", MaxErrorRate = 0.01)]
[LoadTest("Peak", Tier = OpsExecutionTier.Cloud)]
[LoadProfile(ConcurrentUsers = 500, RampUp = "120s", Duration = "15m")]
[LoadTestEndpoint("POST", "/api/orders")]
[LoadTestEndpoint("GET", "/api/orders/{id}", Weight = 3)]
[LoadTestThreshold(P95 = "300ms", P99 = "1s", MaxErrorRate = 0.01)][LoadTest("Smoke", Tier = OpsExecutionTier.InProcess)]
[LoadProfile(ConcurrentUsers = 10, Duration = "60s")]
[LoadTestEndpoint("POST", "/api/orders")]
[LoadTestThreshold(P95 = "200ms", MaxErrorRate = 0.0)]
[LoadTest("Soak", Tier = OpsExecutionTier.Container)]
[LoadProfile(ConcurrentUsers = 100, Duration = "30m")]
[LoadTestEndpoint("POST", "/api/orders")]
[LoadTestEndpoint("GET", "/api/orders/{id}", Weight = 3)]
[LoadTestThreshold(P95 = "300ms", P99 = "1s", MaxErrorRate = 0.01)]
[LoadTest("Peak", Tier = OpsExecutionTier.Cloud)]
[LoadProfile(ConcurrentUsers = 500, RampUp = "120s", Duration = "15m")]
[LoadTestEndpoint("POST", "/api/orders")]
[LoadTestEndpoint("GET", "/api/orders/{id}", Weight = 3)]
[LoadTestThreshold(P95 = "300ms", P99 = "1s", MaxErrorRate = 0.01)]Three load test profiles across all three tiers. Smoke runs in-process for fast feedback. Soak runs in Docker for 30 minutes to catch memory leaks. Peak runs in the cloud with distributed k6 for real scale.
Chaos (Part 11)
[ChaosExperiment("PaymentTimeout", Tier = OpsExecutionTier.InProcess,
Hypothesis = "Order placement degrades gracefully when payment times out")]
[TargetService(typeof(IPaymentGateway))]
[FaultInjection(FaultKind.Timeout, Probability = 0.5, Delay = "5s")]
[SteadyStateProbe(Metric = "order.placement.success_rate", Expected = "> 80%")]
[ChaosExperiment("DatabaseLatency", Tier = OpsExecutionTier.Container,
Hypothesis = "Order queries complete within 2s with 500ms DB latency")]
[Container("postgres", Image = "postgres:16", Port = 5432)]
[ToxiProxy("postgres-proxy", Upstream = "postgres:5432", ListenPort = 15432)]
[FaultInjection(FaultKind.Latency, Duration = "500ms", Target = "postgres-proxy")]
[ChaosExperiment("AzFailover", Tier = OpsExecutionTier.Cloud,
Hypothesis = "OrderService recovers within 60s after AZ failure")]
[CloudProvider(CloudProvider.Azure, Region = "westeurope")]
[FaultInjection(FaultKind.AvailabilityZoneFailure, Duration = "5m")]
[AbortCondition(Metric = "order.api.error_rate", Threshold = "30%")][ChaosExperiment("PaymentTimeout", Tier = OpsExecutionTier.InProcess,
Hypothesis = "Order placement degrades gracefully when payment times out")]
[TargetService(typeof(IPaymentGateway))]
[FaultInjection(FaultKind.Timeout, Probability = 0.5, Delay = "5s")]
[SteadyStateProbe(Metric = "order.placement.success_rate", Expected = "> 80%")]
[ChaosExperiment("DatabaseLatency", Tier = OpsExecutionTier.Container,
Hypothesis = "Order queries complete within 2s with 500ms DB latency")]
[Container("postgres", Image = "postgres:16", Port = 5432)]
[ToxiProxy("postgres-proxy", Upstream = "postgres:5432", ListenPort = 15432)]
[FaultInjection(FaultKind.Latency, Duration = "500ms", Target = "postgres-proxy")]
[ChaosExperiment("AzFailover", Tier = OpsExecutionTier.Cloud,
Hypothesis = "OrderService recovers within 60s after AZ failure")]
[CloudProvider(CloudProvider.Azure, Region = "westeurope")]
[FaultInjection(FaultKind.AvailabilityZoneFailure, Duration = "5m")]
[AbortCondition(Metric = "order.api.error_rate", Threshold = "30%")]Three chaos experiments, one per tier. The analyzer validates: the InProcess experiment targets IPaymentGateway, which has a [CircuitBreaker] -- CHS001 passes. The Container experiment targets PostgreSQL, which is in the DependsOn list -- CHS002 passes. The Cloud experiment has an abort condition -- CHS003 passes.
Security (Part 12)
[RbacPolicy("order-admin",
Roles = new[] { "admin" },
Operations = new[] { "orders:*" })]
[RbacPolicy("order-reader",
Roles = new[] { "support", "analytics" },
Operations = new[] { "orders:read", "orders:list" })]
[RbacPolicy("order-processor",
Roles = new[] { "worker" },
Operations = new[] { "orders:process", "orders:update-status" })]
[RbacPolicy("order-refund",
Roles = new[] { "admin", "finance" },
Operations = new[] { "orders:refund" })]
[AuditPolicy(
LogEvents = new[] { "orders:create", "orders:refund", "orders:cancel" },
RetentionDays = 365)]
[SecretRotation("order-db-connection-string",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "90d")]
[SecretRotation("payment-api-key",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "30d")]
[DastScan(Target = "/api/orders", Profile = DastProfile.Standard)][RbacPolicy("order-admin",
Roles = new[] { "admin" },
Operations = new[] { "orders:*" })]
[RbacPolicy("order-reader",
Roles = new[] { "support", "analytics" },
Operations = new[] { "orders:read", "orders:list" })]
[RbacPolicy("order-processor",
Roles = new[] { "worker" },
Operations = new[] { "orders:process", "orders:update-status" })]
[RbacPolicy("order-refund",
Roles = new[] { "admin", "finance" },
Operations = new[] { "orders:refund" })]
[AuditPolicy(
LogEvents = new[] { "orders:create", "orders:refund", "orders:cancel" },
RetentionDays = 365)]
[SecretRotation("order-db-connection-string",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "90d")]
[SecretRotation("payment-api-key",
Provider = SecretProvider.AzureKeyVault,
RotationInterval = "30d")]
[DastScan(Target = "/api/orders", Profile = DastProfile.Standard)]Eight attributes. The generator produces: Kubernetes RBAC manifests, OPA policies, audit log schema, and a DAST scan configuration for the CI pipeline.
Phase 2 total: ~27 attributes. The service is performance-baselined, load-tested at three tiers, chaos-tested at three tiers, and secured with RBAC, audit logging, and DAST scanning.
Phase 3: Infrastructure and Data
The attributes that define where the service runs and how its data is managed.
Infrastructure (Part 15)
[ContainerSpec("order-api",
CPU = "500m", Memory = "512Mi",
CPULimit = "1000m", MemoryLimit = "1Gi")]
[ContainerSpec("order-worker",
CPU = "250m", Memory = "256Mi",
CPULimit = "500m", MemoryLimit = "512Mi")]
[ContainerSpec("order-scheduler",
CPU = "100m", Memory = "128Mi")]
[PersistentStorage("order-attachments",
StorageClass = "azure-managed-premium",
Size = "50Gi",
AccessMode = AccessMode.ReadWriteOnce)]
[TlsCertificate("orders.example.com",
Issuer = CertIssuer.LetsEncrypt,
RenewalDays = 30)]
[DnsRecord("orders.example.com", Type = DnsType.CNAME, Target = "lb.example.com")]
[DnsRecord("orders-internal.example.com", Type = DnsType.A, Target = "10.0.1.100")][ContainerSpec("order-api",
CPU = "500m", Memory = "512Mi",
CPULimit = "1000m", MemoryLimit = "1Gi")]
[ContainerSpec("order-worker",
CPU = "250m", Memory = "256Mi",
CPULimit = "500m", MemoryLimit = "512Mi")]
[ContainerSpec("order-scheduler",
CPU = "100m", Memory = "128Mi")]
[PersistentStorage("order-attachments",
StorageClass = "azure-managed-premium",
Size = "50Gi",
AccessMode = AccessMode.ReadWriteOnce)]
[TlsCertificate("orders.example.com",
Issuer = CertIssuer.LetsEncrypt,
RenewalDays = 30)]
[DnsRecord("orders.example.com", Type = DnsType.CNAME, Target = "lb.example.com")]
[DnsRecord("orders-internal.example.com", Type = DnsType.A, Target = "10.0.1.100")]Seven attributes. The generator produces: Kubernetes resource requests/limits in the deployment manifests, PersistentVolumeClaim, cert-manager Certificate CRD, and ExternalDNS annotations.
Networking (Part 16)
[IngressRule("orders.example.com",
Path = "/api/orders",
Backend = "order-api:8080",
TlsSecret = "orders-tls")]
[MtlsPolicy(Mode = MtlsMode.Strict,
PeerAuthentication = "order-system")]
[FirewallRule("allow-payment-provider",
Source = "203.0.113.0/24",
Port = 443,
Protocol = Protocol.TCP)]
[FirewallRule("allow-internal",
Source = "10.0.0.0/8",
Port = 8080,
Protocol = Protocol.TCP)]
[NetworkPolicy(
IngressFrom = new[] { "order-api", "order-worker" },
EgressTo = new[] { "postgres-16", "redis-7", "rabbitmq-3" })][IngressRule("orders.example.com",
Path = "/api/orders",
Backend = "order-api:8080",
TlsSecret = "orders-tls")]
[MtlsPolicy(Mode = MtlsMode.Strict,
PeerAuthentication = "order-system")]
[FirewallRule("allow-payment-provider",
Source = "203.0.113.0/24",
Port = 443,
Protocol = Protocol.TCP)]
[FirewallRule("allow-internal",
Source = "10.0.0.0/8",
Port = 8080,
Protocol = Protocol.TCP)]
[NetworkPolicy(
IngressFrom = new[] { "order-api", "order-worker" },
EgressTo = new[] { "postgres-16", "redis-7", "rabbitmq-3" })]Five attributes. The generator produces: Kubernetes Ingress resource, Istio PeerAuthentication, Azure NSG rules, and a Kubernetes NetworkPolicy that restricts traffic to only the declared dependencies.
Data Governance (Part 17)
[BackupPolicy(
Schedule = "0 2 * * *",
Retention = "30d",
Type = BackupType.Incremental)]
[RetentionPolicy("orders", Retention = "7y",
Reason = "Financial records retention requirement")]
[RetentionPolicy("order_events", Retention = "90d",
Reason = "Event replay window")]
[RetentionPolicy("order_logs", Retention = "30d",
Reason = "Debugging window")]
[GdprDataMap(
PersonalDataFields = new[] { "customer_name", "email", "shipping_address" },
LawfulBasis = LawfulBasis.Contract,
DataSubjectType = "customer",
RightToErasure = true)]
[RecoveryObjective(RPO = "1h", RTO = "4h")][BackupPolicy(
Schedule = "0 2 * * *",
Retention = "30d",
Type = BackupType.Incremental)]
[RetentionPolicy("orders", Retention = "7y",
Reason = "Financial records retention requirement")]
[RetentionPolicy("order_events", Retention = "90d",
Reason = "Event replay window")]
[RetentionPolicy("order_logs", Retention = "30d",
Reason = "Debugging window")]
[GdprDataMap(
PersonalDataFields = new[] { "customer_name", "email", "shipping_address" },
LawfulBasis = LawfulBasis.Contract,
DataSubjectType = "customer",
RightToErasure = true)]
[RecoveryObjective(RPO = "1h", RTO = "4h")]Six attributes. The generator produces: CronJob for backups, pg_dump scripts with retention-based cleanup, GDPR data map documentation, and a disaster recovery runbook with RPO/RTO targets.
Phase 3 total: 18 attributes. The service has defined infrastructure, network boundaries, and data management policies.
Phase 4: Governance and Lifecycle
The attributes that keep the service compliant, cost-effective, and maintainable over its lifetime.
Testing (Part 13)
[TestStrategy(
Categories = new[] {
"unit", "integration", "contract", "chaos",
"load", "security", "smoke", "acceptance" })][TestStrategy(
Categories = new[] {
"unit", "integration", "contract", "chaos",
"load", "security", "smoke", "acceptance" })]Quality (Part 14)
[QualityGate(
MaxCyclomaticComplexity = 15,
MinCodeCoverage = 80,
MinMutationScore = 60,
MaxTechDebtHours = 200)][QualityGate(
MaxCyclomaticComplexity = 15,
MinCodeCoverage = 80,
MinMutationScore = 60,
MaxTechDebtHours = 200)]Compliance (Part 18)
[ComplianceFramework(Framework.SOC2)]
[ComplianceControl("CC6.1", Description = "Logical access security",
Evidence = "RBAC policies, audit logs")]
[ComplianceControl("CC7.2", Description = "System monitoring",
Evidence = "Health checks, alert rules, dashboards")]
[ComplianceControl("CC8.1", Description = "Change management",
Evidence = "Canary deployments, rollback plans")]
[ComplianceControl("CC9.1", Description = "Risk mitigation",
Evidence = "Chaos experiments, circuit breakers")][ComplianceFramework(Framework.SOC2)]
[ComplianceControl("CC6.1", Description = "Logical access security",
Evidence = "RBAC policies, audit logs")]
[ComplianceControl("CC7.2", Description = "System monitoring",
Evidence = "Health checks, alert rules, dashboards")]
[ComplianceControl("CC8.1", Description = "Change management",
Evidence = "Canary deployments, rollback plans")]
[ComplianceControl("CC9.1", Description = "Risk mitigation",
Evidence = "Chaos experiments, circuit breakers")]Supply Chain (Part 18)
[SupplyChainPolicy(
MaxCriticalVulnerabilities = 0,
MaxHighVulnerabilities = 3,
SbomFormat = SbomFormat.CycloneDX,
AllowedLicenses = new[] { "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" })][SupplyChainPolicy(
MaxCriticalVulnerabilities = 0,
MaxHighVulnerabilities = 3,
SbomFormat = SbomFormat.CycloneDX,
AllowedLicenses = new[] { "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" })]Cost (Part 19)
[CostBudget(
Monthly = 500,
Currency = "USD",
AlertThreshold = 80,
RightSizingReview = "quarterly")][CostBudget(
Monthly = 500,
Currency = "USD",
AlertThreshold = 80,
RightSizingReview = "quarterly")]Capacity (Part 20)
[HorizontalPodAutoscaler(
MinReplicas = 2,
MaxReplicas = 20,
TargetCPU = 70,
TargetMemory = 80,
ScaleUpStabilization = "60s",
ScaleDownStabilization = "300s")]
[RateLimit(
RequestsPerSecond = 1000,
BurstSize = 1500,
KeyStrategy = RateLimitKey.ClientIP)][HorizontalPodAutoscaler(
MinReplicas = 2,
MaxReplicas = 20,
TargetCPU = 70,
TargetMemory = 80,
ScaleUpStabilization = "60s",
ScaleDownStabilization = "300s")]
[RateLimit(
RequestsPerSecond = 1000,
BurstSize = 1500,
KeyStrategy = RateLimitKey.ClientIP)]Incident (Part 21)
[OnCallRotation(
Schedule = "weekly",
Team = "order-team",
EscalationTimeout = "15m")]
[EscalationPolicy(
Level1 = "on-call-engineer",
Level2 = "team-lead",
Level3 = "engineering-director",
Level1Timeout = "15m",
Level2Timeout = "30m")][OnCallRotation(
Schedule = "weekly",
Team = "order-team",
EscalationTimeout = "15m")]
[EscalationPolicy(
Level1 = "on-call-engineer",
Level2 = "team-lead",
Level3 = "engineering-director",
Level1Timeout = "15m",
Level2Timeout = "30m")]API Contract (Part 22)
[ApiVersion(Current = "v3", Minimum = "v1",
SunsetDate = "2027-01-01")][ApiVersion(Current = "v3", Minimum = "v1",
SunsetDate = "2027-01-01")]Environment Parity (Part 22)
[FeatureFlag("new-payment-flow",
EnabledIn = new[] { "Development", "Staging" },
RolloutPercentage = 25)]
[FeatureFlag("async-order-processing",
EnabledIn = new[] { "Development" })]
[EnvironmentParityRule(
Rule = "staging-matches-production",
Exceptions = new[] { "FeatureFlags", "Replicas", "SecretValues" })][FeatureFlag("new-payment-flow",
EnabledIn = new[] { "Development", "Staging" },
RolloutPercentage = 25)]
[FeatureFlag("async-order-processing",
EnabledIn = new[] { "Development" })]
[EnvironmentParityRule(
Rule = "staging-matches-production",
Exceptions = new[] { "FeatureFlags", "Replicas", "SecretValues" })]Lifecycle (Part 22)
[SunsetPlan("legacy-auth-endpoint",
DeprecationDate = "2026-06-01",
RemovalDate = "2026-12-01",
MigrationGuide = "/docs/auth-migration")]
[TechDebtItem("payment-retry-hardcoded",
Effort = "40h",
Priority = TechDebtPriority.Medium,
Description = "Replace hardcoded retry delays with Polly configuration")][SunsetPlan("legacy-auth-endpoint",
DeprecationDate = "2026-06-01",
RemovalDate = "2026-12-01",
MigrationGuide = "/docs/auth-migration")]
[TechDebtItem("payment-retry-hardcoded",
Effort = "40h",
Priority = TechDebtPriority.Medium,
Description = "Replace hardcoded retry delays with Polly configuration")]Phase 4 total: ~19 attributes. The service is tested, quality-gated, compliant, supply-chain-secured, cost-managed, capacity-planned, incident-ready, API-versioned, environment-consistent, and lifecycle-tracked.
The Complete Class
All four phases together: 95 attributes on one partial class. The complete OrderServiceV3Ops.cs is approximately 250 lines of attribute declarations. No implementation code. No configuration files. No wiki pages. Just typed, compiler-validated attribute declarations.
The Generated Artifact Inventory
Every attribute produces something. Here is the complete inventory:
InProcess Tier (15 generated .g.cs files)
| File | Source DSL | Purpose |
|---|---|---|
HealthCheckRegistration.g.cs |
Observability | ASP.NET health check setup |
MetricDefinitions.g.cs |
Observability | IMeterFactory metric declarations |
PaymentGatewayChaosDecorator.g.cs |
Chaos | DI decorator with fault injection |
ChaosRegistration.g.cs |
Chaos | Chaos experiment DI wiring |
CircuitBreakerDecorator.g.cs |
Resilience | Polly circuit breaker decorator |
RetryPolicyDecorator.g.cs |
Resilience | Polly retry decorator |
RateLimiterMiddleware.g.cs |
Capacity | Rate limiting middleware |
CacheInterceptor.g.cs |
Performance | Read-through cache decorator |
RbacAuthorizationHandler.g.cs |
Security | ASP.NET authorization handler |
AuditLogMiddleware.g.cs |
Security | Audit event logging |
FeatureFlagConfiguration.g.cs |
Env Parity | Feature flag registrations |
EnvironmentTransforms.g.cs |
Configuration | appsettings overrides |
LoadTestSmoke.g.cs |
LoadTesting | InProcess load test runner |
QualityGateAnalyzer.g.cs |
Quality | Roslyn analyzer for quality rules |
ApiVersionMiddleware.g.cs |
ApiContract | Version negotiation middleware |
Container Tier (20 generated YAML/JSON files)
| File | Source DSL | Purpose |
|---|---|---|
docker-compose.chaos.yaml |
Chaos | Toxiproxy chaos environment |
toxiproxy-config.json |
Chaos | Proxy upstream mappings |
docker-compose.soak.yaml |
LoadTesting | Soak test environment |
k6-soak-test.js |
LoadTesting | k6 soak test script |
docker-compose.migration.yaml |
Migration | Migration test environment |
docker-compose.integration.yaml |
Testing | Integration test environment |
dast-scan-config.yaml |
Security | OWASP ZAP scan configuration |
backup-test-config.yaml |
DataGovernance | Backup restore verification |
network-test-config.yaml |
Networking | mTLS and firewall verification |
parity-check-config.yaml |
Env Parity | Environment drift detection |
.env.staging.g |
Configuration | Non-secret env values from [ConfigTransform] |
docker-compose.config.yaml |
Configuration | Vault-secret mounts + env-file binding |
conftest-policies/soc2.rego |
Compliance | Local OPA rules from [ComplianceControl] |
trivy-compliance.yaml |
Compliance | Per-framework Trivy scan profile |
docker-compose.canary.yaml |
Resilience | Traefik weighted routing canary |
prometheus-canary-rules.yaml |
Resilience | Local SLI rules mirroring AnalysisTemplate |
docker-compose.scale.yaml |
Capacity | Replicas + resource limits/reservations |
docker-compose.security.yaml |
Security | Hardening overlay (cap_drop, read_only, no-new-privileges) |
seccomp-profile.json |
Security | Syscall allow-list per [SecurityPolicy] |
apparmor-profile |
Security | AppArmor profile mounted by the overlay |
Cloud Tier (25 generated Terraform/k8s files)
| File | Source DSL | Purpose |
|---|---|---|
terraform/deployment/main.tf |
Deployment | AKS deployment module |
terraform/chaos-az-failover/main.tf |
Chaos | Azure Chaos Studio experiment |
terraform/load-test/main.tf |
LoadTesting | k6 operator and test run |
k8s/deployment.yaml |
Deployment | Kubernetes Deployment manifests |
k8s/canary.yaml |
Deployment | Flagger Canary CRD |
k8s/hpa.yaml |
Capacity | HorizontalPodAutoscaler |
k8s/network-policy.yaml |
Networking | NetworkPolicy |
k8s/ingress.yaml |
Networking | Ingress resource |
k8s/mtls.yaml |
Networking | Istio PeerAuthentication |
k8s/certificate.yaml |
Infrastructure | cert-manager Certificate |
k8s/pvc.yaml |
Infrastructure | PersistentVolumeClaim |
k8s/litmus-az-failover.yaml |
Chaos | LitmusChaos CRD |
k6-peak-traffic.js |
LoadTesting | k6 peak load test script |
prometheus/alerts.yaml |
Observability | Helm-wrapped alert rules |
grafana/dashboard.json |
Observability | Grafana dashboard model |
k8s/configmap.yaml |
Configuration | Non-secret env values from [ConfigTransform] |
k8s/external-secret.yaml |
Configuration | Key Vault refs from [Secret] |
gatekeeper/constraint-template.yaml |
Compliance | OPA template from [ComplianceControl] |
gatekeeper/constraint.yaml |
Compliance | Residency constraint from [DataResidency] |
monitoring/servicemonitor.yaml |
Observability | Prometheus Operator scrape target (CRD) |
monitoring/prometheusrule.yaml |
Observability | Prometheus Operator alert rules (CRD) |
k8s/analysistemplate.yaml |
Resilience | Argo AnalysisTemplate for canary metrics |
k8s/vpa.yaml |
Capacity | VerticalPodAutoscaler (CRD) |
k8s/keda-scaledobject.yaml |
Capacity | KEDA ScaledObject (CRD) |
k8s/serviceaccount.yaml + k8s/role.yaml + k8s/rolebinding.yaml |
Security | RBAC trio per [SecurityPolicy] |
Total: 60 generated files from 1 C# class.
The Analyzer Report
During dotnet build, every cross-DSL validation runs:
Build started...
info DEP001: Deployment orchestrator 'order-platform' has 3 apps, all with health checks
info DEP002: Canary strategy references error rate metric 'http_requests_total' -- metric exists
info MIG001: Migration DAG is acyclic: 047 -> 048 -> backfill -> seed
info OBS001: All 3 health check dependencies match deployment DependsOn targets
info OBS002: All alert rules reference defined metrics
info OBS003: Dashboard 'order-service-overview' has panels for all defined metrics
info CFG001: All 3 environments have connection string transforms
info CFG002: Production secrets have rotation policies
info RES001: CircuitBreaker on IPaymentGateway -- timeout matches chaos experiment delay
info CHS001: CircuitBreaker on IPaymentGateway has chaos experiment 'PaymentTimeout'
info CHS002: Database dependency 'postgres-16' has chaos experiment 'DatabaseLatency'
info CHS003: Cloud chaos experiment 'AzFailover' has abort condition
info PRF001: SLO 'availability' references defined SLI 'availability'
info PRF002: Endpoint budgets cover all deployment apps with HTTP ports
info SEC001: RBAC policies cover all API operations
info SEC002: Audit policy covers all write operations
info SEC003: Secret rotation intervals within compliance requirements
info NET001: NetworkPolicy egress matches deployment DependsOn
info NET002: Ingress TLS secret matches certificate definition
info DGV001: Backup schedule covers all data retention policies
info DGV002: RPO (1h) is achievable with backup schedule (daily) + WAL archiving
info COM001: SOC2 controls CC6.1, CC7.2, CC8.1, CC9.1 have supporting evidence
info SUP001: SBOM format CycloneDX configured
info CST001: Cost budget $500/month within cluster capacity
info CAP001: HPA min replicas (2) >= deployment replicas floor
info CAP002: Rate limit (1000 rps) matches endpoint budget MaxRPS
info INC001: Escalation policy has 3 levels with increasing timeouts
info API001: API version v3 current, v1 minimum -- sunset date 2027-01-01
info ENV001: Feature flags have environment restrictions
info ENV002: Parity rule 'staging-matches-production' validated
info LFC001: Sunset plan 'legacy-auth-endpoint' has deprecation and removal dates
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:04.21Build started...
info DEP001: Deployment orchestrator 'order-platform' has 3 apps, all with health checks
info DEP002: Canary strategy references error rate metric 'http_requests_total' -- metric exists
info MIG001: Migration DAG is acyclic: 047 -> 048 -> backfill -> seed
info OBS001: All 3 health check dependencies match deployment DependsOn targets
info OBS002: All alert rules reference defined metrics
info OBS003: Dashboard 'order-service-overview' has panels for all defined metrics
info CFG001: All 3 environments have connection string transforms
info CFG002: Production secrets have rotation policies
info RES001: CircuitBreaker on IPaymentGateway -- timeout matches chaos experiment delay
info CHS001: CircuitBreaker on IPaymentGateway has chaos experiment 'PaymentTimeout'
info CHS002: Database dependency 'postgres-16' has chaos experiment 'DatabaseLatency'
info CHS003: Cloud chaos experiment 'AzFailover' has abort condition
info PRF001: SLO 'availability' references defined SLI 'availability'
info PRF002: Endpoint budgets cover all deployment apps with HTTP ports
info SEC001: RBAC policies cover all API operations
info SEC002: Audit policy covers all write operations
info SEC003: Secret rotation intervals within compliance requirements
info NET001: NetworkPolicy egress matches deployment DependsOn
info NET002: Ingress TLS secret matches certificate definition
info DGV001: Backup schedule covers all data retention policies
info DGV002: RPO (1h) is achievable with backup schedule (daily) + WAL archiving
info COM001: SOC2 controls CC6.1, CC7.2, CC8.1, CC9.1 have supporting evidence
info SUP001: SBOM format CycloneDX configured
info CST001: Cost budget $500/month within cluster capacity
info CAP001: HPA min replicas (2) >= deployment replicas floor
info CAP002: Rate limit (1000 rps) matches endpoint budget MaxRPS
info INC001: Escalation policy has 3 levels with increasing timeouts
info API001: API version v3 current, v1 minimum -- sunset date 2027-01-01
info ENV001: Feature flags have environment restrictions
info ENV002: Parity rule 'staging-matches-production' validated
info LFC001: Sunset plan 'legacy-auth-endpoint' has deprecation and removal dates
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:04.21Thirty-one cross-DSL validations. Zero warnings. Zero errors. Every reference is resolved. Every dependency is satisfied. Every policy is consistent.
The dotnet ops report Output
A single command that summarizes the entire operational posture:
$ dotnet ops report
OrderService v3.0 -- Operational Posture Report
================================================
Deployment
Apps: 3 (order-api, order-worker, order-scheduler)
Strategy: Canary (5% -> 15% steps, 5m intervals)
Dependencies: postgres-16, redis-7, rabbitmq-3
Migrations
Pending: 4 steps (schema, index, data backfill, seed)
Estimated: ~45 minutes (5M row backfill at 1000/batch)
Observability
Health Checks: 3 (database, redis, rabbitmq)
Metrics: 5 (2 counters, 2 histograms, 1 gauge)
Alerts: 3 (1 critical, 2 warning)
Dashboard: order-service-overview (4 rows)
Resilience
Circuit Breaker: IPaymentGateway (5 failures / 30s break)
Retry Policy: IRabbitMqPublisher (3x exponential from 100ms)
Rollback: Auto on error_rate > 5%
Performance
SLOs: availability 99.9% / latency 99% < 500ms
Endpoints: 3 with budgets (POST 200ms, GET 50ms, LIST 100ms)
Cache: 1 policy (order-by-id, 5m TTL, event-invalidated)
Chaos Coverage
InProcess: 1 experiment (PaymentTimeout)
Container: 1 experiment (DatabaseLatency)
Cloud: 1 experiment (AzFailover)
Coverage: 100% of circuit breakers, 100% of dependencies
Security
RBAC: 4 policies (admin, reader, processor, refund)
Audit: 3 event types, 365d retention
Secrets: 2 with rotation (90d db, 30d payment key)
DAST: Standard profile on /api/orders
Infrastructure
CPU: 850m request / 1500m limit (across 3 containers)
Memory: 896Mi request / 1.75Gi limit
Storage: 50Gi premium SSD
TLS: orders.example.com (Let's Encrypt, 30d renewal)
Capacity
HPA: 2-20 replicas (CPU 70%, Memory 80%)
Rate Limit: 1000 rps (1500 burst)
Data Governance
Backup: Daily incremental, 30d retention
RPO/RTO: 1h / 4h
GDPR: 3 personal data fields, right to erasure enabled
Compliance
Framework: SOC2 (4 controls mapped)
Supply Chain: 0 critical CVE max, CycloneDX SBOM
Licenses: MIT, Apache-2.0, BSD-2, BSD-3
Cost
Budget: $500/month (alert at 80%)
Review: Quarterly right-sizing
Lifecycle
API: v3 current, v1 minimum, sunset 2027-01-01
Sunset Plans: 1 (legacy-auth, removal 2026-12)
Tech Debt: 1 item (40h, medium priority)
Feature Flags: 2 (new-payment-flow 25% rollout, async-processing dev-only)
Generated Artifacts: 40 files (15 InProcess, 10 Container, 15 Cloud)
Analyzer Results: 31 validations passed, 0 warnings, 0 errors
Last updated: 2026-04-06T10:15:32Z$ dotnet ops report
OrderService v3.0 -- Operational Posture Report
================================================
Deployment
Apps: 3 (order-api, order-worker, order-scheduler)
Strategy: Canary (5% -> 15% steps, 5m intervals)
Dependencies: postgres-16, redis-7, rabbitmq-3
Migrations
Pending: 4 steps (schema, index, data backfill, seed)
Estimated: ~45 minutes (5M row backfill at 1000/batch)
Observability
Health Checks: 3 (database, redis, rabbitmq)
Metrics: 5 (2 counters, 2 histograms, 1 gauge)
Alerts: 3 (1 critical, 2 warning)
Dashboard: order-service-overview (4 rows)
Resilience
Circuit Breaker: IPaymentGateway (5 failures / 30s break)
Retry Policy: IRabbitMqPublisher (3x exponential from 100ms)
Rollback: Auto on error_rate > 5%
Performance
SLOs: availability 99.9% / latency 99% < 500ms
Endpoints: 3 with budgets (POST 200ms, GET 50ms, LIST 100ms)
Cache: 1 policy (order-by-id, 5m TTL, event-invalidated)
Chaos Coverage
InProcess: 1 experiment (PaymentTimeout)
Container: 1 experiment (DatabaseLatency)
Cloud: 1 experiment (AzFailover)
Coverage: 100% of circuit breakers, 100% of dependencies
Security
RBAC: 4 policies (admin, reader, processor, refund)
Audit: 3 event types, 365d retention
Secrets: 2 with rotation (90d db, 30d payment key)
DAST: Standard profile on /api/orders
Infrastructure
CPU: 850m request / 1500m limit (across 3 containers)
Memory: 896Mi request / 1.75Gi limit
Storage: 50Gi premium SSD
TLS: orders.example.com (Let's Encrypt, 30d renewal)
Capacity
HPA: 2-20 replicas (CPU 70%, Memory 80%)
Rate Limit: 1000 rps (1500 burst)
Data Governance
Backup: Daily incremental, 30d retention
RPO/RTO: 1h / 4h
GDPR: 3 personal data fields, right to erasure enabled
Compliance
Framework: SOC2 (4 controls mapped)
Supply Chain: 0 critical CVE max, CycloneDX SBOM
Licenses: MIT, Apache-2.0, BSD-2, BSD-3
Cost
Budget: $500/month (alert at 80%)
Review: Quarterly right-sizing
Lifecycle
API: v3 current, v1 minimum, sunset 2027-01-01
Sunset Plans: 1 (legacy-auth, removal 2026-12)
Tech Debt: 1 item (40h, medium priority)
Feature Flags: 2 (new-payment-flow 25% rollout, async-processing dev-only)
Generated Artifacts: 40 files (15 InProcess, 10 Container, 15 Cloud)
Analyzer Results: 31 validations passed, 0 warnings, 0 errors
Last updated: 2026-04-06T10:15:32ZOne screen. The complete operational posture of OrderService. Every number is derived from the attribute declarations. Every number is compiler-validated. Change an attribute, and this report updates on the next build.