Clean architecture patterns

From FerroxLabs/murage · View interactive version

Clean architecture patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level clean architecture patterns implementation: clean-code and design-patterns decision frameworks, production-ready patterns, and concrete templates for clean architecture patterns workflows. Use when the user asks about clean architecture patterns, clean architecture patterns confi

How to use this skill

Skill file

Clean Architecture Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Establish the Architectural Context and Pain Points

Before recommending any pattern, diagnose what is actually broken or at risk.

2. Explain the Dependency Rule and Layer Model

The single most important concept in Clean Architecture is the Dependency Rule: source code dependencies must point inward only. Outer layers depend on inner layers -- never the reverse.

3. Define the Structural Mapping for the Specific Project

Translate abstract layers into actual folder structure and module boundaries for the user's stack.

```

src/

domain/

entities/ # Pure domain objects, no imports from src/infrastructure

value-objects/ # Immutable, equality by value

domain-services/ # Domain logic spanning multiple aggregates

repositories/ # Interface definitions only (IOrderRepository)

events/ # Domain event definitions

application/

use-cases/ # One file per use case, depends on domain interfaces

dtos/ # Input/output data shapes for use cases

ports/ # Input port interfaces (IPlaceOrderUseCase)

infrastructure/

persistence/ # Repository implementations (TypeORM, Prisma, raw SQL)

http/ # Express/Fastify controllers, route handlers

messaging/ # Kafka/RabbitMQ consumers and publishers

external-services/ # HTTP clients for third-party APIs

di/ # Dependency injection wiring (composition root)

```

```

com.company.app/

domain/

application/

adapters/

web/

persistence/

messaging/

config/ # Spring @Configuration, dependency wiring only

```

```

src/

domain/

application/

adapters/

api/

database/

external/

main.py # FastAPI app instantiation, DI wiring

```

4. Design the Use Case Interface and Data Flow

Show the user exactly how data flows through the architecture for a single feature.

1. Validates the command (or delegates to a domain service/entity)

2. Loads required entities through repository interfaces

3. Calls entity methods to execute business logic (entities mutate themselves and emit domain events)

4. Persists changed entities through repository interfaces

5. Publishes domain events (optional -- through an event publisher interface)

6. Returns a Result DTO

5. Define Repository and Port Contracts

The Repository pattern is the most commonly misimplemented part of Clean Architecture. Define it correctly.

6. Enforce Boundaries with Tooling

Architectural rules that are not enforced will erode within weeks on a team.

```js

// .dependency-cruiser.js excerpt

forbidden: [

{ name: "domain-must-not-depend-on-infrastructure",

from: { path: "^src/domain" },

to: { path: "^src/infrastructure" } },

{ name: "application-must-not-depend-on-infrastructure",

from: { path: "^src/application" },

to: { path: "^src/infrastructure" } }

]

```

7. Define the Testing Strategy by Layer

Clean Architecture's primary practical benefit is testability. Make this explicit.

8. Handle Cross-Cutting Concerns Without Polluting Layers

Logging, authentication, authorization, caching, and transactions are the most common sources of layer violations.


Output Format

When advising on Clean Architecture patterns, produce the following structured output:

## Clean Architecture Assessment

### Context Summary
- Codebase profile: [greenfield / brownfield migration / partial adoption]
- Primary language and ecosystem: [TypeScript / Java / Python / C# / Go / other]
- Delivery mechanisms: [list all: REST API, CLI, queue consumer, batch job, etc.]
- Team size and Clean Architecture experience: [n engineers, experience level]
- Key pain point being addressed: [testability / coupling / multiple delivery mechanisms / etc.]

---

### Layer Mapping

| Layer            | Contents in This Project         | Enforcement Tool              |
|------------------|----------------------------------|-------------------------------|
| Domain (Entities)| [entity/aggregate names]         | [tooling: ArchUnit, dep-cruiser] |
| Application (Use Cases) | [use case names]          | [tooling]                     |
| Interface Adapters | [controllers, presenters, gateways] | [tooling]               |
| Infrastructure   | [DB, HTTP framework, external APIs] | [tooling]                  |
| Composition Root | [DI config module]               | --                            |

---

### Dependency Rule Violations Identified
[List any current or anticipated violations with recommended remediation]

---

### Recommended Folder Structure

\`\`\`
[Concrete folder tree for this specific project]
\`\`\`

---

### Use Case Implementation Template

\`\`\`typescript (or language of choice)
// Application Layer -- Use Case
interface PlaceOrderCommand {
  customerId: string;
  lineItems: { productId: string; quantity: number }[];
  shippingAddressId: string;
}

interface PlaceOrderResult {
  orderId: string;
  estimatedDeliveryDate: Date;
  totalAmountCents: number;
}

// Input port -- defined in application layer
interface IPlaceOrderUseCase {
  execute(command: PlaceOrderCommand): Promise<PlaceOrderResult>;
}

// Output ports -- defined in application layer, implemented in infrastructure
interface IOrderRepository {
  save(order: Order): Promise<void>;
  findById(orderId: OrderId): Promise<Order | null>;
}

interface IInventoryPort {
  checkAvailability(productId: string, quantity: number): Promise<boolean>;
}

class PlaceOrderUseCase implements IPlaceOrderUseCase {
  constructor(
    private readonly orderRepository: IOrderRepository,
    private readonly inventoryPort: IInventoryPort,
  ) {}

  async execute(command: PlaceOrderCommand): Promise<PlaceOrderResult> {
    // Domain logic delegated to entities
    const order = Order.create({
      customerId: CustomerId.of(command.customerId),
      lineItems: command.lineItems,
    });

    for (const item of order.lineItems) {
      const available = await this.inventoryPort.checkAvailability(
        item.productId.value,
        item.quantity,
      );
      if (!available) {
        throw new InsufficientInventoryError(item.productId.value);
      }
    }

    await this.orderRepository.save(order);

    return {
      orderId: order.id.value,
      estimatedDeliveryDate: order.estimatedDeliveryDate,
      totalAmountCents: order.total.amountCents,
    };
  }
}
\`\`\`

---

### Architecture Decision Record (ADR)

**Title:** [Architecture pattern decision]
**Status:** Proposed / Accepted / Deprecated
**Context:** [What problem is being solved, what forces are in tension]
**Decision:** [The specific structural decision made]
**Consequences:** [What becomes easier, what becomes harder, what new constraints apply]

---

### Testing Strategy

| Layer              | Test Type        | Example Tooling           | Infra Required |
|--------------------|------------------|---------------------------|----------------|
| Domain entities    | Pure unit        | Jest, JUnit, pytest       | None           |
| Use cases          | Unit w/ in-memory doubles | Jest, JUnit      | None           |
| Adapters/repos     | Integration      | Testcontainers + Jest     | Docker         |
| Full stack         | E2E              | Supertest, RestAssured    | Docker Compose |

---

### Enforcement Configuration
[Specific tooling config snippet for the user's ecosystem]

Rules

  1. NEVER allow a domain entity or use case to import from the infrastructure layer by any path -- not transitively, not through re-exports. A single such import destroys the testability guarantee that is the primary benefit of Clean Architecture.
  1. NEVER place business rules in controllers, route handlers, or HTTP middleware. If a controller contains an if statement that makes a business decision (not a routing decision), that logic belongs in a Use Case or domain entity.
  1. ALWAYS define repository and port interfaces in the application or domain layer. If the interface definition lives in the infrastructure package, the dependency direction is inverted and inner layers cannot use it without depending outward.
  1. NEVER return ORM entities (ActiveRecord objects, JPA @Entity classes, Mongoose documents) from repository methods to use cases. Map them to domain entities inside the repository implementation. Leaking ORM objects into the use case layer creates a hidden dependency on the ORM.
  1. ALWAYS use a Composition Root -- a single, explicit location where all interfaces are wired to their implementations. Avoid distributed new ConcreteClass() calls scattered across use cases or domain services. In Spring, this is @Configuration classes. In Node.js, it is typically src/di/container.ts. In Python, it is main.py or an dependencies.py module.
  1. NEVER conflate the domain model with the persistence model. A domain Order entity with rich behavior is not the same thing as an orders database row. The repository is responsible for the translation. Accepting ORM constraints (e.g., requiring a no-arg constructor, requiring @Column annotations) on domain entities means the ORM is dictating domain model design -- a critical inversion.
  1. ALWAYS write one Use Case per business operation. A single OrderService class with 12 methods (placeOrder, cancelOrder, fulfillOrder, refundOrder, etc.) is not a Use Case -- it is a service class that will accumulate dependencies and become a maintenance burden. Each operation gets its own class with its own constructor-injected dependencies.
  1. NEVER mock what you own in use case tests. Use in-memory implementations (fake objects) of repository interfaces rather than jest.mock() or Mockito mocks. Mocks verify interaction patterns; fakes verify behavior. A InMemoryOrderRepository that throws DuplicateOrderError when saving an order with an existing ID tests real behavior that a mock cannot capture.
  1. ALWAYS enforce layer boundaries in CI with automated tooling. Architectural conventions without automated enforcement degrade within weeks on teams of 3+ engineers. Choose one enforcement tool (ArchUnit, dependency-cruiser, import-linter, NetArchTest) and treat violations as build failures.
  1. NEVER apply Clean Architecture uniformly to all parts of a system. CRUD-heavy administration screens, reporting queries, and data migration scripts rarely benefit from full Use Case / Repository abstraction. Apply the pattern where business complexity justifies it; use simpler patterns (thin controllers with direct query objects) for genuinely simple CRUD operations. Document the decision explicitly so future developers do not apply it inconsistently by accident.

Edge Cases

Legacy Codebase with Business Logic in ActiveRecord/ORM Models

Rails, Laravel, Django, and similar frameworks encourage putting business logic directly in model classes that inherit from ORM base classes. Migrating this to Clean Architecture cannot be done in a single refactor.

Anemic Domain Model Masquerading as Clean Architecture

A common failure mode: the architecture looks structurally correct (layers, interfaces, repositories) but all business logic lives in Use Cases while domain entities are data bags with only getters and setters. This is the Transaction Script pattern in Clean Architecture clothing.

Multiple Bounded Contexts Sharing a Database

In a monolith, multiple business domains (Orders, Inventory, Billing) may share a single relational database. Clean Architecture per-domain is straightforward, but the seams between domains need design.

Dependency Injection Container Complexity

When using a DI container (InversifyJS, Spring, Dagger, Python-inject), the Composition Root can become unwieldy and hard to debug.

High-Throughput / Low-Latency Systems Where Abstraction Overhead Matters

Clean Architecture adds indirection layers. In systems processing 50,000+ transactions per second with sub-10ms latency requirements, the cost of virtual dispatch, interface indirection, and object mapping can be measurable.

Testing in an Event-Driven Architecture with Domain Events

When domain entities emit events (order.domainEvents collection), the testing pattern changes.

Microservice Boundary Coincides with Clean Architecture Module

When a Clean Architecture module is extracted into a microservice, the internal structure should not need to change significantly -- only the infrastructure adapters change.


Example

Input: "We're building a fintech payment processing API in TypeScript with Node.js. The API receives payment requests over REST, processes them against external payment providers (Stripe, Braintree), applies our own risk-scoring logic, and stores transaction records in PostgreSQL. We have 5 engineers, and two of us have used Clean Architecture before. We also need a background worker that retries failed payments. How should we structure this?"


Output:

Clean Architecture Assessment

Context Summary


Layer Mapping

| Layer | Contents in This Project | Enforcement Tool |

|--------------------|-----------------------------------------------------------------------|---------------------|

| Domain (Entities) | PaymentTransaction aggregate, Money value object, RiskScore value object, PaymentStatus enum, PaymentAttempt entity, domain events | dependency-cruiser |

| Application (Use Cases) | InitiatePaymentUseCase, RetryFailedPaymentUseCase, GetTransactionStatusUseCase | dependency-cruiser |

| Interface Adapters | PaymentController (Fastify), RetryWorkerAdapter (queue consumer), StripePaymentGateway, BraintreePaymentGateway, PrismaTransactionRepository | dependency-cruiser |

| Infrastructure | Fastify app instance, Prisma client, Stripe SDK client, Braintree SDK client, BullMQ worker | dependency-cruiser |

| Composition Root | src/di/container.ts -- binds all interfaces to implementations | -- |


Dependency Rule Violations to Avoid


Recommended Folder Structure

src/
  domain/
    entities/
      PaymentTransaction.ts       # Aggregate root -- owns status transitions
      PaymentAttempt.ts           # Child entity: single attempt against a provider
    value-objects/
      Money.ts                    # Currency + amount, arithmetic, comparison
      RiskScore.ts                # 0-100 score, threshold logic
      PaymentStatus.ts            # Enum: PENDING | PROCESSING | SUCCESS | FAILED | RETRYING
    events/
      PaymentInitiated.ts
      PaymentSucceeded.ts
      PaymentFailed.ts
    repositories/
      ITransactionRepository.ts   # Interface: save(), findById(), findPendingRetries()
    ports/
      IPaymentGatewayPort.ts      # Interface: charge(attempt): Promise<GatewayResult>
      IRiskScoringPort.ts         # Interface: score(transaction): Promise<RiskScore>
      IRetrySchedulerPort.ts      # Interface: scheduleRetry(transactionId, delayMs)
  application/
    use-cases/
      InitiatePaymentUseCase.ts
      RetryFailedPaymentUseCase.ts
      GetTransactionStatusUseCase.ts
    dtos/
      InitiatePaymentCommand.ts
      InitiatePaymentResult.ts
      RetryPaymentCommand.ts
  infrastructure/
    persistence/
      PrismaTransactionRepository.ts   # Implements ITransactionRepository
      mappers/
        TransactionMapper.ts           # Domain entity <-> Prisma model
    payment-gateways/
      StripePaymentGateway.ts          # Implements IPaymentGatewayPort
      BraintreePaymentGateway.ts       # Implements IPaymentGatewayPort
    risk-scoring/
      InternalRiskScoringAdapter.ts    # Implements IRiskScoringPort
    retry/
      BullMQRetryScheduler.ts          # Implements IRetrySchedulerPort
      RetryWorkerAdapter.ts            # BullMQ worker -- calls RetryFailedPaymentUseCase
    http/
      PaymentController.ts             # Fastify route handler
      PaymentRouter.ts
  di/
    container.ts                       # Composition root -- all interface bindings
  main.ts                              # Fastify app + BullMQ worker startup

Use Case Implementation Template

// src/domain/repositories/ITransactionRepository.ts
export interface ITransactionRepository {
  save(transaction: PaymentTransaction): Promise<void>;
  findById(id: TransactionId): Promise<PaymentTransaction | null>;
  findPendingRetries(maxAttempts: number, beforeDate: Date): Promise<PaymentTransaction[]>;
}

// src/domain/ports/IPaymentGatewayPort.ts
export interface GatewayResult {
  success: boolean;
  providerTransactionId: string | null;
  failureCode: string | null;
  failureMessage: string | null;
}

export interface IPaymentGatewayPort {
  charge(attempt: PaymentAttempt): Promise<GatewayResult>;
}

// src/application/dtos/InitiatePaymentCommand.ts
export interface InitiatePaymentCommand {
  customerId: string;
  amountCents: number;
  currencyCode: string;   // ISO 4217: "USD", "EUR"
  paymentMethodToken: string;
  idempotencyKey: string;
  preferredGateway: "stripe" | "braintree";
}

export interface InitiatePaymentResult {
  transactionId: string;
  status: "PROCESSING" | "SUCCESS" | "FAILED";
  providerTransactionId: string | null;
}

// src/application/use-cases/InitiatePaymentUseCase.ts
export class InitiatePaymentUseCase {
  constructor(
    private readonly transactionRepository: ITransactionRepository,
    private readonly paymentGateway: IPaymentGatewayPort,
    private readonly riskScoring: IRiskScoringPort,
    private readonly retryScheduler: IRetrySchedulerPort,
    private readonly eventPublisher: IEventPublisher,
  ) {}

  async execute(command: InitiatePaymentCommand): Promise<InitiatePaymentResult> {
    const money = Money.of(command.amountCents, command.currencyCode);

    // Domain entity creation enforces invariants (throws if currency unsupported, amount <= 0)
    const transaction = PaymentTransaction.initiate({
      customerId: CustomerId.of(command.customerId),
      amount: money,
      paymentMethodToken: command.paymentMethodToken,
      idempotencyKey: command.idempotencyKey,
    });

    // Application-layer concern: risk gate before charging
    const riskScore = await this.riskScoring.score(transaction);
    if (riskScore.exceedsThreshold(RiskScore.HIGH_RISK_THRESHOLD)) {
      transaction.block(riskScore);
      await this.transactionRepository.save(transaction);
      await this.eventPublisher.publish(transaction.domainEvents);
      throw new PaymentBlockedByRiskError(transaction.id.value, riskScore.value);
    }

    const attempt = transaction.createAttempt(command.preferredGateway);
    const result = await this.paymentGateway.charge(attempt);

    if (result.success) {
      transaction.recordSuccess(attempt, result.providerTransactionId!);
    } else {
      transaction.recordFailure(attempt, result.failureCode!, result.failureMessage!);
      if (transaction.isEligibleForRetry()) {
        // Exponential backoff: attempt 1 = 30s, attempt 2 = 120s, attempt 3 = 600s
        const delayMs = Math.pow(4, transaction.attemptCount) * 30_000;
        await this.retryScheduler.scheduleRetry(transaction.id.value, delayMs);
      }
    }

    await this.transactionRepository.save(transaction);
    await this.eventPublisher.publish(transaction.domainEvents);
    transaction.clearDomainEvents();

    return {
      transactionId: transaction.id.value,
      status: transaction.status,
      providerTransactionId: result.providerTransactionId,
    };
  }
}

Architecture Decision Record (ADR)

Title: Use Clean Architecture with per-gateway adapter pattern for payment processing

Status: Accepted

Context: The system must support Stripe and Braintree as payment gateways, with the ability to add a third gateway or switch primary gateways within a quarter. Risk scoring logic is proprietary and must remain independent of any gateway SDK. A background retry worker must reuse the same payment processing logic as the API without code duplication. These requirements create strong pressure for decoupling business logic from infrastructure.

Decision: Apply Clean Architecture with explicit port interfaces (IPaymentGatewayPort, IRiskScoringPort) in the application layer. Each gateway gets its own adapter class. The retry worker is an infrastructure-layer adapter that invokes the same RetryFailedPaymentUseCase as if it were an HTTP request. Prisma is used for persistence but is strictly isolated to the infrastructure layer via a repository mapper pattern.

Consequences: Adding a third payment gateway requires only a new adapter class implementing IPaymentGatewayPort and a wiring change in the Composition Root -- no Use Case code changes. Use Cases are fully testable without Stripe/Braintree credentials or a PostgreSQL instance. The mapping layer between Prisma models and domain entities adds approximately 80--120 lines of boilerplate per aggregate, which is an accepted trade-off for the domain model freedom gained.


Testing Strategy

| Layer | Test Type | Tooling | Infra Required |

|------------------------|-----------------------|--------------------------------|-----------------|

| PaymentTransaction, Money, RiskScore | Pure unit | Vitest, zero mocks | None |

| InitiatePaymentUseCase | Unit with in-memory doubles | Vitest + InMemoryTransactionRepository | None |

| PrismaTransactionRepository | Integration | Vitest + Testcontainers (PostgreSQL 15) | Docker |

| StripePaymentGateway | Integration | Vitest + Stripe test mode keys | Network (Stripe sandbox) |

| Full payment flow | E2E | Supertest against Fastify app + Testcontainers | Docker |

For the Use Case unit tests, implement InMemoryTransactionRepository as a real in-memory store:

// src/infrastructure/testing/InMemoryTransactionRepository.ts
export class InMemoryTransactionRepository implements ITransactionRepository {
  private store = new Map<string, PaymentTransaction>();

  async save(transaction: PaymentTransaction): Promise<void> {
    this.store.set(transaction.id.value, transaction);
  }

  async findById(id: TransactionId): Promise<PaymentTransaction | null> {
    return this.store.get(id.value) ?? null;
  }

  async findPendingRetries(maxAttempts: number, beforeDate: Date): Promise<PaymentTransaction[]> {
    return [...this.store.values()].filter(
      t => t.status === "RETRYING" &&
           t.attemptCount < maxAttempts &&
           t.lastAttemptAt < beforeDate
    );
  }
}

Enforcement Configuration

// .dependency-cruiser.js
module.exports = {
  forbidden: [
    {
      name: "domain-no-infrastructure",
      severity: "error",
      from: { path: "^src/domain" },
      to: { path: "^src/(infrastructure|di)" },
    },
    {
      name: "application-no-infrastructure",
      severity: "error",
      from: { path: "^src/application" },
      to: { path: "^src/(infrastructure|di)" },
    },
    {
      name: "domain-no-application",
      severity: "error",
      from: { path: "^src/domain" },
      to: { path: "^src/application" },
    },
  ],
  options: { tsConfig: { fileName: "tsconfig.json" } },
};

Add to CI pipeline (package.json):

{
  "scripts": {
    "check:architecture": "depcruise src --config .dependency-cruiser.js",
    "pretest": "npm run check:architecture"
  }
}

This configuration means any pull request that accidentally imports a Prisma type or Stripe SDK class into a Use Case or domain entity will fail the CI pipeline before it can be merged. The architecture rules are self-enforcing from day one.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.