designing-hexagonal-architecture
Guides the design and analysis of hexagonal architecture (Ports & Adapters) for backend systems. Use when structuring modular applications with clean separation between business logic and infrastructure.
What this skill does
# Designing Hexagonal Architecture ## Philosophy / Approach Hexagonal Architecture, also known as Ports & Adapters pattern, is an architectural pattern proposed by Alistair Cockburn that aims to separate the core business logic of an application from external infrastructure. The philosophy centers on creating a flexible, testable, and maintainable system by inverting dependencies and isolating the domain from technical concerns. The hexagonal shape represents the idea that the application has multiple "sides" where it interacts with the outside world, and each side is interchangeable. This approach enables: - **Technology Independence**: Business logic doesn't depend on specific frameworks or databases - **Testability**: Core domain can be tested without infrastructure - **Flexibility**: External components can be replaced without affecting business rules - **Maintainability**: Clear boundaries make reasoning about the system easier ## When to Use This Skill - Designing new project architecture - Refactoring inter-module dependencies This skill is particularly valuable when building enterprise applications, microservices, or any system where long-term maintainability and testability are priorities. ## Core Concepts Hexagonal Architecture is built on several fundamental principles that work together to create a robust, maintainable system. ### 1. Layer Separation The application is organized into distinct layers, each with specific responsibilities: - **Presentation Layer**: HTTP requests/responses, DTO transformation, user interface concerns - **Application Layer**: Business logic orchestration, transaction management, use case implementation - **Domain Layer**: Core business rules, domain models, business validations - **Infrastructure Layer**: Database access, external APIs, file systems, third-party integrations The dependency direction flows from outer layers toward the domain at the center. ### 2. Port - Interface Abstraction Ports define the boundaries between the domain and the outside world. They are interfaces that express what the business logic needs without specifying how it's implemented. **Characteristics of Ports:** - Defined as interfaces or abstract contracts - Located in or near the domain layer - Express business needs in domain language - Independent of implementation details ### 3. Adapter - Concrete Implementation Adapters are concrete implementations of Port interfaces. They handle the actual communication with external systems and infrastructure. **Types of Adapters:** - **Primary/Driving Adapters**: Controllers, REST endpoints, GraphQL resolvers (drive the application) - **Secondary/Driven Adapters**: Repositories, external service clients, messaging systems (driven by the application) Adapters translate between the domain's language and the technical protocols of external systems. ### 4. Dependency Inversion One of the most critical principles: dependencies point inward, toward the domain. **Dependency Flow:** ``` External → Infrastructure → Application → Domain ``` **Key Rules:** - Inner layers (domain) must never depend on outer layers - Business logic remains independent of infrastructure - Interfaces are defined by the domain, implemented by infrastructure ### 5. Applying SOLID Principles Hexagonal Architecture naturally aligns with SOLID principles: - **Single Responsibility**: Each module handles one specific concern - **Open/Closed**: System is open for extension (new adapters) but closed for modification (domain remains stable) - **Liskov Substitution**: Adapters implementing the same port are interchangeable - **Interface Segregation**: Ports expose only the methods needed by the domain - **Dependency Inversion**: Domain depends on abstractions (ports), not concrete implementations (adapters) ### 6. Module Independence Each domain module operates independently with minimal coupling: - Clear boundaries between modules - Communication through well-defined interfaces - Circular dependencies resolved through design patterns - Modules can be deployed, tested, and scaled independently ## Implementation Workflow ### Step 1: Identify Domain Boundaries Begin by understanding your business domains and their relationships. Map out: - Core business entities and their responsibilities - Natural boundaries between different business concerns - Use cases and workflows within each domain ### Step 2: Define Ports For each domain module, identify what it needs from the outside world and what it provides to others: - **Inbound Ports**: Use cases the domain exposes (service interfaces) - **Outbound Ports**: Dependencies the domain requires (repository interfaces, external service interfaces) ### Step 3: Implement Domain Logic Build the core business logic without any infrastructure concerns: - Create domain models and entities - Implement business rules and validations - Write services that orchestrate use cases - Keep domain logic pure and testable ### Step 4: Create Adapters Implement concrete adapters for each port: - Primary adapters to expose domain functionality (controllers, event handlers) - Secondary adapters to fulfill domain dependencies (database repositories, API clients) ### Step 5: Configure Dependency Injection Wire everything together using a DI container: - Bind port interfaces to adapter implementations - Configure module relationships - Resolve circular dependencies if needed ## Patterns / Examples Hexagonal Architecture can be implemented in various programming languages and frameworks. We provide detailed examples for: - **[TypeScript/NestJS](./examples/TYPESCRIPT.md)**: Full implementation with NestJS dependency injection, decorators, and Prisma ORM - **[Ruby on Rails](./examples/RUBY_ON_RAILS.md)**: Rails-friendly approach with service objects, repositories, and Active Record integration - **[Java Spring](./examples/JAVA_SPRING.md)**: Spring Boot implementation with Spring Data JPA, component scanning, and annotations - **[Kotlin Spring](./examples/KOTLIN_SPRING.md)**: Kotlin Spring Boot implementation with coroutines support, null safety, and idiomatic Kotlin patterns Each example demonstrates: 1. Port Interface Definition 2. Adapter Implementation 3. Module Configuration with Dependency Injection 4. Repository Pattern (Infrastructure Layer) 5. Complete Layered Architecture 6. Using Ports in Other Modules 7. Testing with Mocks Choose the example that matches your technology stack to see concrete implementations of the concepts discussed in this skill. ## Best Practices ### Clear Layer Separation Maintain strict separation between layers with consistent dependency direction. Each layer should have a single, well-defined responsibility. Never allow business logic to leak into presentation or infrastructure layers. **Guidelines:** - Controllers should only handle HTTP concerns (validation, serialization) - Services contain business logic and orchestration - Repositories handle data persistence - Keep domain models independent of ORM annotations ### Minimize Port Interfaces Design ports to expose only the methods needed by the domain. Follow the Interface Segregation Principle by creating focused, role-specific interfaces rather than large, monolithic ones. **Guidelines:** - Create separate ports for different client needs - Avoid "god interfaces" with many unrelated methods - Name ports based on their business purpose - Keep port methods at the right level of abstraction ### Domain-Based Module Separation Organize code by business domain rather than technical layers. Each domain module should be cohesive and loosely coupled from other domains. **Guidelines:** - Use forwardRef to resolve circular dependencies when necessary - Communicate between modules through ports/adapters - Keep each module independently testable - Consider domain boundaries when splitting modules ## Common Pitfalls ### Managing Circular Dependencies Circular dependencies between mod
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.