Skip to content

Bounded Contexts First: A Modular Monolith That Can Become Services

An AWS blueprint for a modular monolith with enforceable context boundaries, reliable events, context-owned data, and a practical extraction path that does not require an early microservices tax.

Ekanatha Reddy Urivakili17 min2,851 words

1. Context and scale

A modular monolith should buy simplicity without borrowing heavily against the future. The useful question is not whether its folders resemble services. It is whether one business capability can leave without taking half the database and release process with it.

Consider a B2B equipment-ordering platform. Customers browse equipment, submit orders, and track fulfillment. Two engineering teams own four bounded contexts:

  • Catalog: equipment descriptions and availability projections.
  • Ordering: customer intent and the order lifecycle.
  • Inventory: stock and reservations.
  • Fulfillment: shipment preparation and dispatch.

Payment processing, warehouse automation, and accounting remain outside this blueprint.

The stack is ASP.NET Core on .NET 10 LTS, PostgreSQL, Amazon ECS on AWS Fargate, Amazon SQS, and Amazon ElastiCache. Use supported, patched database and cache engine versions available in the deployment region; pin their exact versions during infrastructure validation rather than relying on provider defaults.

Planning assumptions

Every capacity and budget number below is an assumption, not a measured limit.

DimensionAssumption
Users40,000 daily active users across business tenants
Traffic120 requests/s sustained during business hours; 600 requests/s bursts
Write traffic15 order submissions/s at peak
Data volume250 GB PostgreSQL, growing by 15 GB/month
Team sizeTwo teams, eight engineers total; shared operational ownership
RuntimeTwo web tasks and one background-worker task initially
BudgetApproximately USD 1,500–2,500/month, excluding labor and external business systems
AvailabilitySingle AWS Region; database spans Availability Zones
RecoveryRegional-disaster RPO ≤15 minutes and RTO ≤4 hours, subject to restore drills

The API and worker run the same application image in different execution modes. This remains one application release, not a collection of prematurely independent services.

The initial deployment unit is deliberately coarse. The ownership model is not.

2. Requirements

Functional requirements

RequirementBoundary and behavior
Browse equipmentCatalog serves searchable descriptions and cached read models
Submit an orderOrdering durably accepts an idempotent request
Reserve stockInventory processes accepted orders asynchronously
Report rejectionInsufficient stock produces an explicit business outcome
Prepare fulfillmentFulfillment starts only after confirmed reservation
Track progressOrdering exposes a customer-facing status projection
Support operationsAuthorized operators can inspect failed workflows and request audited retries

An accepted order is not a promise that stock exists. The API returns 202 Accepted with a stable order identifier; reservation succeeds or fails afterward.

Non-functional requirements

RequirementInitial target or constraint
API availability99.9% successful eligible requests over a rolling 30-day window
Read latency95% of catalog requests complete within 300 ms
Acceptance latency95% of valid order submissions complete within 500 ms
Workflow freshness99% of accepted orders reach a reservation outcome within 60 seconds
ConsistencyACID within a context; eventual consistency between contexts
IsolationTenant scope enforced on every command and query
DeployabilityBackward-compatible schema changes and rolling releases
ExtractabilityNo cross-context table access, foreign keys, or shared ORM entities

A bounded context owns its model, writes, invariants, and language—not merely its namespace.

For example, Inventory owns whether ten units can be reserved. Ordering must not reconstruct that rule from inventory tables.

3. High-level design

flowchart LR
    Client["Web clients"] --> Edge["Amazon CloudFront and AWS WAF"]
    Edge --> Alb["Application Load Balancer"]
    Alb --> Api["Amazon ECS Fargate API"]
    Api --> Db["Amazon RDS for PostgreSQL Multi-AZ"]
    Api --> Cache["Amazon ElastiCache"]
    Worker["Amazon ECS Fargate worker"] --> Db
    Worker --> Queue["Amazon SQS queues and DLQs"]
    Queue --> Worker
    Api --> Obs["CloudWatch and AWS X-Ray"]
    Worker --> Obs
    Api --> Identity["Amazon Cognito"]
    Api --> Secrets["AWS Secrets Manager"]

The API and worker share one versioned application artifact while external infrastructure supports durability and operations.

CloudFront caches only explicitly public catalog responses. Tenant-specific responses are private and never shared through the CDN.

The API commits business changes and an outbox record in one PostgreSQL transaction. The worker publishes outbox events to SQS and consumes integration events through context-owned handlers.

Use a small number of queues, named for consuming contexts. They provide independent retry and backlog visibility without creating one queue per event type.

Do not assume SQS provides broadcast delivery. Initially, the outbox dispatcher routes each event to its required destination queues and tracks each delivery independently. An OrderAccepted event goes to Inventory; a reservation outcome goes to Ordering and, when successful, Fulfillment.

Start with:

  • Two API tasks spread across Availability Zones.
  • One worker task, with task replacement enabled.
  • Bounded database connection pools.
  • Autoscaling based on measured API demand and queue age.
  • No service mesh, Kubernetes cluster, or internal API gateway.

Cache catalog projections using tenant-aware keys and bounded TTLs. Never use a cached stock count to authorize reservations.

4. Cloud service mapping

These are capability mappings, not claims of identical semantics or pricing.

ComponentChosen AWS serviceAWS equivalentAzure equivalentGCP equivalent
Container runtimeECS with FargateECS with FargateAzure Container AppsCloud Run
HTTP ingressApplication Load BalancerApplication Load BalancerApplication GatewayApplication Load Balancer
CDN and filteringCloudFront and AWS WAFCloudFront and AWS WAFAzure Front Door and WAFCloud CDN and Cloud Armor
Relational databaseRDS for PostgreSQL Multi-AZRDS for PostgreSQLAzure Database for PostgreSQLCloud SQL for PostgreSQL
Distributed cacheElastiCacheElastiCacheAzure Managed RedisMemorystore
Work queueSQS and dead-letter queuesSQSAzure Service Bus queuesPub/Sub subscriptions
IdentityCognitoCognitoMicrosoft Entra External IDIdentity Platform
SecretsSecrets ManagerSecrets ManagerAzure Key VaultSecret Manager
ImagesECRECRAzure Container RegistryArtifact Registry
TelemetryCloudWatch and X-RayCloudWatch and X-RayAzure MonitorCloud Monitoring and Cloud Trace
Backup storageS3S3Azure Blob StorageCloud Storage

Keep application ports independent of cloud SDK types. An ordering handler should depend on an event writer, not IAmazonSQS. The infrastructure adapter owns serialization, delivery, and cloud-specific errors.

Portability is useful here primarily because it separates business decisions from operational mechanisms—not because moving clouds is expected.

5. Data design

Use one PostgreSQL database with one schema and runtime role per context. This avoids separate database operations while preserving enforceable ownership.

erDiagram
    ORDER ||--o{ ORDER_EVENT : records
    ORDER_EVENT ||--|{ OUTBOX_DELIVERY : routes
    STOCK ||--o{ RESERVATION : supplies
    ORDER {
        uuid order_id PK
        uuid tenant_id
        text status
    }
    ORDER_EVENT {
        uuid event_id PK
        uuid order_id FK
        text event_type
    }
    OUTBOX_DELIVERY {
        uuid event_id FK
        text destination
        timestamptz published_at
    }
    STOCK {
        uuid tenant_id PK
        text sku PK
        int available
    }
    RESERVATION {
        uuid reservation_id PK
        uuid order_id
        int quantity
    }
    INBOX {
        text consumer PK
        uuid event_id PK
        timestamptz processed_at
    }

Relationships shown as database constraints stay inside their owning context; Inventory stores order identifiers without a foreign key to Ordering.

The following schema supports the runnable order API later in the article.

CREATE SCHEMA ordering;
CREATE SCHEMA inventory;

CREATE TABLE ordering.orders (
    order_id uuid PRIMARY KEY,
    tenant_id uuid NOT NULL,
    idempotency_key text NOT NULL
        CHECK (length(idempotency_key) BETWEEN 1 AND 128),
    sku text NOT NULL CHECK (length(sku) BETWEEN 1 AND 80),
    quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 1000),
    status text NOT NULL DEFAULT 'Pending'
        CHECK (status IN ('Pending', 'Reserved', 'Rejected')),
    created_at timestamptz NOT NULL DEFAULT now(),
    UNIQUE (tenant_id, idempotency_key)
);

CREATE TABLE ordering.outbox_event (
    event_id uuid PRIMARY KEY,
    order_id uuid NOT NULL REFERENCES ordering.orders(order_id),
    event_type text NOT NULL,
    schema_version integer NOT NULL,
    payload jsonb NOT NULL,
    trace_parent text,
    trace_state text,
    occurred_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE ordering.outbox_delivery (
    event_id uuid NOT NULL REFERENCES ordering.outbox_event(event_id),
    destination text NOT NULL,
    published_at timestamptz,
    lease_until timestamptz,
    lease_token uuid,
    attempts integer NOT NULL DEFAULT 0,
    PRIMARY KEY (event_id, destination)
);

CREATE INDEX outbox_pending
    ON ordering.outbox_delivery (lease_until, event_id)
    WHERE published_at IS NULL;

CREATE TABLE ordering.inbox (
    consumer text NOT NULL,
    event_id uuid NOT NULL,
    processed_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer, event_id)
);

CREATE TABLE inventory.stock (
    tenant_id uuid NOT NULL,
    sku text NOT NULL,
    available integer NOT NULL CHECK (available >= 0),
    PRIMARY KEY (tenant_id, sku)
);

CREATE TABLE inventory.reservation (
    reservation_id uuid PRIMARY KEY,
    tenant_id uuid NOT NULL,
    order_id uuid NOT NULL,
    sku text NOT NULL,
    quantity integer NOT NULL CHECK (quantity > 0),
    UNIQUE (tenant_id, order_id),
    FOREIGN KEY (tenant_id, sku)
        REFERENCES inventory.stock(tenant_id, sku)
);

CREATE TABLE inventory.inbox (
    consumer text NOT NULL,
    event_id uuid NOT NULL,
    processed_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer, event_id)
);

Provision separate migration-owner and runtime roles. Runtime roles receive only required DML privileges within their schema; the migration role never enters the application connection pool.

Inventory reserves stock using a conditional update:

UPDATE inventory.stock
SET available = available - $3
WHERE tenant_id = $1
  AND sku = $2
  AND available >= $3
RETURNING available;

No returned row means the reservation cannot proceed. Inbox insertion, stock update, reservation creation, and the outcome outbox must share one Inventory transaction.

Retain idempotency records for the documented retry horizon. Purge delivered outbox payloads and inbox entries only under an explicit retention policy; a forgotten retention job becomes a database-growth incident.

6. Low-level design

classDiagram
    class ApiHost
    class OrderingModule
    class PlaceOrderHandler
    class OrderingStore
    class InventoryModule
    class ReserveStockHandler
    class OutboxPublisher
    class EventRouter
    class OrderAcceptedV1
    ApiHost --> OrderingModule
    OrderingModule --> PlaceOrderHandler
    PlaceOrderHandler --> OrderingStore
    PlaceOrderHandler --> OrderAcceptedV1
    OutboxPublisher --> OrderingStore
    OutboxPublisher --> EventRouter
    InventoryModule --> ReserveStockHandler
    ReserveStockHandler ..> OrderAcceptedV1

Module entry points expose application operations; persistence implementations and domain objects remain private.

Use separate projects for each module’s implementation and public contracts. A small composition root references modules; modules do not reference each other’s implementation assemblies.

Minimal runnable boundary

This console example demonstrates the dependency direction without a framework.

dotnet new console -n BoundaryDemo -f net10.0
cd BoundaryDemo

Replace Program.cs:

using Ordering.Contracts;

var handler = new Inventory.Application.ReserveStockHandler();
var accepted = new OrderAcceptedV1(
    Guid.NewGuid(), Guid.NewGuid(), "DRILL-18V", 2);

Console.WriteLine(handler.Handle(accepted));

namespace Ordering.Contracts
{
    public sealed record OrderAcceptedV1(
        Guid OrderId, Guid TenantId, string Sku, int Quantity);
}

namespace Inventory.Application
{
    internal sealed class ReserveStockHandler
    {
        public string Handle(OrderAcceptedV1 message) =>
            $"Inventory received order {message.OrderId}";
    }
}

Run with dotnet run.

Notice that Inventory consumes an immutable contract, not an Ordering entity or repository.

In production, publish contracts as owned projects or packages. Avoid a giant Shared.Domain assembly: it becomes an ungoverned dependency graph disguised as reuse.

Realistic runnable acceptance path

This API atomically stores the order and its outgoing event. It deliberately uses a development tenant header; production must derive the tenant from authenticated, authorized claims.

docker run --name module-db \
  -e POSTGRES_PASSWORD=devpass \
  -p 5432:5432 -d postgres:18

# Save the earlier DDL as schema.sql.
docker exec -i module-db psql -U postgres < schema.sql

dotnet new web -n ModularOrders -f net10.0
cd ModularOrders
dotnet add package Npgsql
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Http
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol

export ConnectionStrings__Orders='Host=localhost;Database=postgres;Username=postgres;Password=devpass'

Replace Program.cs:

using System.Diagnostics;
using System.Text.Json;
using Npgsql;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<NpgsqlDataSource>(_ =>
    NpgsqlDataSource.Create(
        builder.Configuration.GetConnectionString("Orders")
        ?? throw new InvalidOperationException("Missing Orders connection")));

var app = builder.Build();

app.MapPost("/orders", async (
    HttpContext http,
    PlaceOrder request,
    NpgsqlDataSource database,
    ILogger<Program> logger,
    CancellationToken ct) =>
{
    // Demo only: production uses a validated tenant claim.
    if (!Guid.TryParse(http.Request.Headers["X-Tenant-Id"].ToString(),
            out var tenantId))
        return Results.BadRequest(new { error = "Invalid tenant" });

    var key = http.Request.Headers["Idempotency-Key"].ToString();
    if (key.Length is < 1 or > 128 ||
        string.IsNullOrWhiteSpace(request.Sku) ||
        request.Sku.Length > 80 ||
        request.Quantity is < 1 or > 1000)
        return Results.BadRequest(new { error = "Invalid order" });

    using var activity = ModuleTelemetry.Source.StartActivity(
        "ordering.place", ActivityKind.Internal);

    await using var connection = await database.OpenConnectionAsync(ct);
    await using var tx = await connection.BeginTransactionAsync(ct);

    var proposedId = Guid.NewGuid();

    await using var insert = new NpgsqlCommand("""
        INSERT INTO ordering.orders
            (order_id, tenant_id, idempotency_key, sku, quantity)
        VALUES ($1, $2, $3, $4, $5)
        ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
        RETURNING order_id
        """, connection, tx);
    insert.Parameters.AddWithValue(proposedId);
    insert.Parameters.AddWithValue(tenantId);
    insert.Parameters.AddWithValue(key);
    insert.Parameters.AddWithValue(request.Sku);
    insert.Parameters.AddWithValue(request.Quantity);

    var inserted = await insert.ExecuteScalarAsync(ct);

    if (inserted is not Guid orderId)
    {
        await using var existing = new NpgsqlCommand("""
            SELECT order_id, sku, quantity
            FROM ordering.orders
            WHERE tenant_id = $1 AND idempotency_key = $2
            """, connection, tx);
        existing.Parameters.AddWithValue(tenantId);
        existing.Parameters.AddWithValue(key);

        await using var reader = await existing.ExecuteReaderAsync(ct);
        if (!await reader.ReadAsync(ct))
            throw new InvalidOperationException("Missing idempotent order");

        var existingId = reader.GetGuid(0);
        var matches = reader.GetString(1) == request.Sku
            && reader.GetInt32(2) == request.Quantity;

        return matches
            ? Results.Accepted($"/orders/{existingId}",
                new { orderId = existingId })
            : Results.Conflict(new { error = "Idempotency key reused" });
    }

    var eventId = Guid.NewGuid();
    var payload = JsonSerializer.Serialize(new
    {
        eventId,
        orderId,
        tenantId,
        sku = request.Sku,
        quantity = request.Quantity
    });

    await using var outgoing = new NpgsqlCommand("""
        INSERT INTO ordering.outbox_event
            (event_id, order_id, event_type, schema_version,
             payload, trace_parent, trace_state)
        VALUES ($1, $2, 'ordering.order-accepted', 1,
                $3::jsonb, $4, $5);

        INSERT INTO ordering.outbox_delivery (event_id, destination)
        VALUES ($1, 'inventory');
        """, connection, tx);
    outgoing.Parameters.AddWithValue(eventId);
    outgoing.Parameters.AddWithValue(orderId);
    outgoing.Parameters.AddWithValue(payload);
    outgoing.Parameters.AddWithValue(Activity.Current?.Id ?? "");
    outgoing.Parameters.AddWithValue(Activity.Current?.TraceStateString ?? "");
    await outgoing.ExecuteNonQueryAsync(ct);

    await tx.CommitAsync(ct);

    logger.LogInformation(
        "Order accepted {OrderId} {EventId} {TenantId}",
        orderId, eventId, tenantId);

    return Results.Accepted($"/orders/{orderId}", new { orderId });
});

app.Run();

public sealed record PlaceOrder(string Sku, int Quantity);

public static class ModuleTelemetry
{
    public static readonly ActivitySource Source = new("Equipment.Modules");
}

Run and submit twice with the same key:

dotnet run --urls http://localhost:5080

# In another terminal:
curl -i http://localhost:5080/orders \
  -H 'Content-Type: application/json' \
  -H 'X-Tenant-Id: 11111111-1111-1111-1111-111111111111' \
  -H 'Idempotency-Key: purchase-1042' \
  -d '{"sku":"DRILL-18V","quantity":2}'

Notice that retries return the same identifier, conflicting payloads return 409, and there is no database-to-queue dual write.

This example implements acceptance only. The production module also supplies the authenticated status endpoint, bounded request timeouts, and centralized problem responses.

7. Key flows

Order acceptance and reservation

sequenceDiagram
    participant C as Client
    participant O as Ordering API
    participant D as PostgreSQL
    participant P as Outbox publisher
    participant Q as SQS
    participant I as Inventory handler
    C->>O: Submit order with idempotency key
    O->>D: Commit order and outbox delivery
    O-->>C: 202 with order identifier
    P->>D: Claim pending delivery
    P->>Q: Publish event
    P->>D: Mark delivery published
    Q->>I: Deliver event
    I->>D: Commit inbox and reservation outcome
    I->>Q: Delete message

Durable acceptance precedes asynchronous reservation; successful queue publication is not successful business processing.

Claim outbox rows using short transactions and FOR UPDATE SKIP LOCKED. Assign an expiring lease and unique lease token, then publish outside the database transaction. Mark completion only when the lease token still matches.

A crash after publication but before marking creates a duplicate. That is expected: delivery is at least once.

Duplicate delivery and business outcome

sequenceDiagram
    participant Q as SQS
    participant I as Inventory handler
    participant D as PostgreSQL
    participant O as Ordering handler
    Q->>I: Redeliver accepted event
    I->>D: Insert consumer and event identifier
    alt Inbox entry already exists
        D-->>I: Duplicate
        I->>Q: Delete message
    else First processing
        I->>D: Reserve stock and write outcome atomically
        I->>Q: Delete message after commit
        D-->>Q: Outcome via outbox publisher
        Q->>O: Deliver reservation outcome
        O->>D: Update order projection and inbox
    end

The database-to-SQS arrow represents a later outbox-worker operation, not a database trigger.

The inbox key includes the consumer identity because several consumers may legitimately process the same event.

Do not depend on queue ordering. Handlers validate legal state transitions and use aggregate versions where necessary. Stock rejection is a normal result, not a poison message.

8. Build and release

Infrastructure lives beside the application, with separate staging and production state. The deployment baseline includes private subnets, security groups, ECS services, encrypted storage, and database backups.

This Terraform excerpt captures the queue’s essential failure policy:

variable "name" {
  type    = string
  default = "equipment"
}

resource "aws_sqs_queue" "inventory_dlq" {
  name                      = "${var.name}-inventory-dlq"
  message_retention_seconds = 1209600
  sqs_managed_sse_enabled    = true
}

resource "aws_sqs_queue" "inventory" {
  name                       = "${var.name}-inventory"
  visibility_timeout_seconds = 120
  message_retention_seconds  = 345600
  receive_wait_time_seconds  = 20
  sqs_managed_sse_enabled     = true

  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.inventory_dlq.arn
    maxReceiveCount     = 5
  })
}

Treat these timeout values as initial assumptions. Extend visibility for legitimate long-running work; keep normal handlers much shorter than the visibility window.

A GitHub Actions workflow can delegate environment-specific commands to reviewed repository scripts:

name: release

on:
  push:
    branches: [main]

permissions:
  contents: read
  id-token: write

concurrency:
  group: production-release
  cancel-in-progress: false

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: "10.0.x"
      - run: dotnet restore --locked-mode
      - run: dotnet test --configuration Release --no-restore
      - run: ./ops/check-boundaries.sh

  staging:
    needs: verify
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ vars.DEPLOY_ROLE_ARN }}
          aws-region: us-east-1
      - run: ./ops/build-push.sh "${GITHUB_SHA}"
      - run: ./ops/migrate.sh staging "${GITHUB_SHA}"
      - run: ./ops/deploy.sh staging "${GITHUB_SHA}"
      - run: ./ops/smoke.sh staging

  production:
    needs: staging
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ vars.DEPLOY_ROLE_ARN }}
          aws-region: us-east-1
      - run: ./ops/migrate.sh production "${GITHUB_SHA}"
      - run: ./ops/deploy.sh production "${GITHUB_SHA}"
      - run: ./ops/smoke.sh production

The scripts must promote the same immutable image digest, run migrations as a one-off task, and wait for ECS deployment health. Production requires an environment approval. Pin action commit SHAs and dependency lock files in the maintained repository.

Use expand-and-contract migrations. Deploy additive columns and compatible readers first; remove old structures only after all tasks and replayable messages no longer require them.

Test layerRequired coverage
UnitDomain invariants, legal transitions, tenant authorization
IntegrationReal PostgreSQL transactions, concurrent idempotency, inbox rollback
ContractEvent compatibility, required fields, unknown-field tolerance
ArchitectureForbidden project references and cross-schema SQL
LoadAssumed peak plus headroom, queue recovery, connection saturation
ResilienceCrash after publish, worker restart, database failover, poison event

Staging is not evidence of production capacity unless its topology and workload are comparable.

9. Observability

Instrument context operations even while everything shares a process. Otherwise extraction creates a visibility boundary exactly where engineers have the least historical evidence.

Log identifiers, outcomes, durations, retry counts, and schema versions. Never log complete event payloads, access tokens, or customer contact details.

{
  "timestamp": "2026-11-02T10:15:30Z",
  "level": "Information",
  "service": "equipment-worker",
  "context": "inventory",
  "operation": "reserve-stock",
  "event_id": "d05067b7-9314-48c4-b064-9c72b5a3f572",
  "order_id": "ae3fbe8d-6aa0-46f2-ab32-a460cf83e069",
  "tenant_id": "11111111-1111-1111-1111-111111111111",
  "outcome": "reserved",
  "attempt": 1,
  "duration_ms": 24,
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}

Add OpenTelemetry registration before builder.Build() in the API example:

using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService("equipment-api"))
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("Equipment.Modules")
        .AddOtlpExporter());

Send OTLP to an AWS Distro for OpenTelemetry collector configured to export traces to X-Ray. Use distinct service names for API and worker.

The outbox already preserves W3C trace context. A consumer can restore it before executing its handler:

using System.Diagnostics;

public static class MessageTracing
{
    public static Activity? Start(
        string? traceParent,
        string? traceState)
    {
        ActivityContext.TryParse(
            traceParent, traceState, isRemote: true, out var parent);

        return ModuleTelemetry.Source.StartActivity(
            "inventory.consume",
            ActivityKind.Consumer,
            parent);
    }
}

Preserve event identifiers across retries. For delayed replays, prefer a new processing trace linked to the original context rather than implying a continuously active request.

Metrics and objectives

Apply RED to API endpoints and handlers: request rate, error rate, and duration. Apply USE to resources: utilization, saturation, and errors.

Monitor CPU, memory, database connections, database I/O latency, connection-pool wait time, and cache evictions. Add workflow metrics: oldest outbox age, oldest queue message age, duplicate count, reservation outcomes, and time spent pending.

Do not place tenant IDs or order IDs in metric labels.

SLISLOMeasurement
API success99.9% over 30 daysSuccessful eligible requests divided by eligible requests
Catalog latency95% below 300 msServer-side route histogram
Acceptance latency95% below 500 msValid submission histogram
Reservation freshness99% within 60 secondsAccepted-to-terminal reservation duration
Durable acceptanceNo acknowledged order lostReconciliation of accepted orders and durable records

Define exclusions explicitly: valid business rejection is not a server error, while an unexpected authorization-service outage is.

Maintain three dashboards: customer experience, context workflows, and infrastructure saturation. Page on sustained fast error-budget burn, stalled order progress, unavailable database connectivity, or queue growth that threatens the freshness objective. Route isolated DLQ messages to a ticket unless they indicate widespread impact or data corruption.

10. Security and compliance

Authentication terminates in application middleware using validated Cognito tokens. Tenant identity comes from trusted claims plus application membership checks—not a caller-selected header.

Enforce:

  • Least-privilege ECS task roles for each execution mode.
  • Separate database credentials and pools per context.
  • Private database and cache networking with restrictive security groups.
  • TLS in transit and encryption at rest.
  • Secrets retrieval without image-baked credentials.
  • Audited administrative commands rather than ad hoc database edits.

Schema roles prevent accidental SQL coupling, but they do not make modules hostile-code security boundaries: one process can access its configured credentials. A context requiring stronger isolation may need extraction earlier.

Event contracts should carry references and necessary business facts, not whole customer profiles. Document retention across database rows, queues, backups, logs, and exports.

Erasure workflows must account for replay. Deleting a customer record while retaining an event that recreates it is not deletion.

11. Cost

The following is an assumption-based monthly estimate, not an AWS quote. It assumes a US-region deployment, 730 hours/month, modest internet egress, one small staging environment, and no enterprise support plan.

ComponentAssumed configurationMonthly estimate
FargateThree production tasks plus reduced staging capacity$180
Load balancingProduction ALB, staging ingress, moderate processing$65
RDS computeModest Multi-AZ PostgreSQL plus small staging database$470
Database storage and backups250 GB production plus staging and backup allowance$150
ElastiCacheSmall replicated production cache$110
SQSBusiness events, retries, polling$25
NetworkingNAT, selected endpoints, cross-AZ traffic$150
Edge and egressCloudFront, WAF, internet transfer$120
ObservabilityLogs, metrics, traces, retention$140
Supporting servicesECR, Secrets Manager, S3, DNS$45
Subtotal$1,455
Planning contingencyApproximately 20%$290
Planning total$1,745

Validate this in the AWS Pricing Calculator using actual instance classes, traffic, storage IOPS, and retention.

The monolith saves operational cost more reliably than compute cost. Avoid trading away database resilience to save a small fraction of one engineer’s time.

12. Failure modes, resilience and disaster recovery

FailureExpected behaviorRecovery action
Queue unavailableOrders remain durable; outbox growsRetry with jitter; page on workflow delay
Worker crashes after publishDuplicate event arrivesInbox suppresses repeated effects
Database failoverBrief errors and broken connectionsReconnect; client retries with same key
Cache unavailableCatalog falls back to databaseLimit fallback concurrency to avoid overload
Poison eventBounded retries, then DLQInspect, repair, replay with audit trail
Stale schema consumerContract processing failsRoll forward compatible consumer
Inventory unavailableOrders remain pendingSurface delay; do not invent rejection
Regional outagePrimary application unavailableRestore database and redeploy in recovery region

Multi-AZ protects against selected infrastructure failures; it is not regional disaster recovery.

Use continuous cross-region backup capability where supported and verify that its measured lag meets the assumed RPO. Provision recovery infrastructure from code, restore into an isolated environment, and rehearse the full runbook.

A database restore can rewind inbox state while queues retain newer messages. Quarantine queue processing during recovery, reconcile order and reservation records, then resume deliberately. Retain event payloads and delivery history long enough to reconstruct outstanding work; never blindly replay every historical event.

13. Evolving to the next scale

Extract a context when there is evidence, not when its folder becomes large.

SignalFirst responseExtraction trigger
Catalog read pressureImprove indexes, projections, cache policyIndependent scaling materially reduces contention
Inventory workload spikesTune queries and worker concurrencyShared runtime or database limits unrelated contexts
Frequent release conflictsImprove ownership and contractsIndependent release cadence has clear business value
Stronger compliance boundaryTighten access and retentionProcess isolation is a requirement
Reporting joins multiplyBuild owned projectionsDo not extract merely to hide uncontrolled joins

Inventory is a plausible first extraction because it already consumes messages and owns its tables.

The exit sequence is:

  1. Preserve existing contracts and queue semantics.
  2. Deploy Inventory’s handler in a separate process, initially against its existing schema.
  3. Stop the old consumer before enabling the new one.
  4. Move context-owned tables to a separate database using a controlled copy and change-capture plan.
  5. Pause consumption briefly, drain database changes, switch ownership, and validate reconciliation.
  6. Revoke the monolith’s Inventory credentials.

The extraction changes deployment and storage ownership, not business semantics.

Do not dual-write old and new databases. For a manageable dataset, a rehearsed maintenance window may be safer than introducing a permanent replication mechanism.

Synchronous in-process calls need separate treatment. Extract coarse-grained queries through an interface adapter or replace them with local projections; do not translate every method call into HTTP.

14. Phased implementation plan

Phase 1: Establish ownership

Agree on context language, invariants, tenant rules, and event contracts. Create module projects, schema roles, architecture tests, and decision records.

Exit criterion: a forbidden dependency fails CI.

Phase 2: Deliver one vertical workflow

Implement order acceptance, transactional outbox, Inventory reservation, and status projection. Add idempotency, inbox handling, and operator visibility before additional features.

Exit criterion: killing the worker at each transaction boundary does not lose an accepted order or reserve twice.

Phase 3: Make it operable

Provision staging and production, instrument context spans, define SLOs, run peak-load tests, and tune connection and worker limits.

Exit criterion: engineers can identify a stalled order from dashboards without querying tables manually.

Phase 4: Prove recovery and portability

Exercise database failover, regional restore, DLQ replay, and an Inventory-only deployment in staging.

Exit criterion: one context runs outside the original host without importing another context’s persistence model.

Phase 5: Extract only when justified

Review release friction, resource contention, incidents, and ownership quarterly. Keep the monolith if it remains the cheaper, clearer operational unit.

A clean exit path is an architectural capability, not a migration commitment. The strongest result may be a modular monolith that remains one deployment for years—because its boundaries make that choice safe.


This article was generated with AI. #AIGenerated