Clean and Hexagonal Architecture Interview Questions
2,511 multiple-choice tech interview questions on Clean and Hexagonal Architecture: Layered architecture, the dependency rule, ports and adapters, onion and clean architecture, vertical slices, SOLID and dependency injection, including strict and relaxed layering, enterprise versus application business rules, source dependencies, package by layer, and policy versus detail; inbound and outbound ports, outside actors, delivery and persistence adapters, port contracts, and technology leaks; request and response models, presenters, interactors, command and write models, rich domain models, expected failures, and use-case output ports; SOLID at the architecture level, including actors and reasons to change, extension points, substitutable ports, role-focused contracts, policy-owned abstractions, the Reuse/Release, Common Closure, and Common Reuse principles, acyclic and stable component graphs, the main sequence, and the Main component; dependency injection as an edge concern and cross-cutting placement, including middleware and other edge pipelines, correlation IDs and context propagation, request context versus framework leaks, tenant resolution and tenant context, resource-based authorization and current-user ports, validation placement, audit trails, commit boundaries, ambient transactions, and use-case decorators; boundaries, DTOs and data mapping, including input and output shapes, over-posting and allowlist binding, view models, DTO assemblers and mapping pitfalls, Problem Details and error catalogs, persistence and wire shapes, and contract evolution; testing a clean or hexagonal codebase, including test doubles at ports, recording fakes and over-mocking, clock ports, Testcontainers and wait strategies, the testing trophy, subcutaneous and narrow integration tests, characterization and pinning tests, and fitness functions; vertical slices, modular monoliths and alternatives, including feature folders and package by feature, module contracts and data ownership, schema per module and the integration-database pitfall, transaction scripts, table modules, service layers, package by component, architecture quanta, and when a process split is actually worth the cost; enforcing and evolving architecture, including architecture tests with ArchUnit and NetArchTest, CI layer-violation checks, architecture decision records, the C4 model and Structurizr, diagrams as code, architecture erosion, evolutionary architecture, the strangler fig approach, Conway's law, and coupling metrics. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 186 key terms with the flashcards first, then test yourself.
Take the practice test · Flashcards · All study tools
What it covers
- 9.1 Layers and the dependency rule
- 9.2 Ports and adapters
- 9.3 Entities, use cases and the application layer
- 9.4 SOLID principles at the architecture level
- 9.5 Dependency injection and cross-cutting concerns
- 9.6 Boundaries, DTOs and data mapping
- 9.7 Testing a clean or hexagonal codebase
- 9.8 Vertical slices, modular monoliths and alternatives
- 9.9 Enforcing and evolving architecture
Key terms
9.1 Layers and the dependency rule
- Dependency rule
- Source dependencies point inward toward the domain
- Use case
- Application operation orchestrating entities and ports
- Onion architecture
- Domain at the center, infrastructure outside, dependencies inward
- Clean Architecture
- Robert C. Martin's layered design where dependencies point inward to the core
- Entities
- Core business rules and objects at the center of Clean Architecture
- Interface adapters
- Ring that converts data between use cases and external formats
- Frameworks and drivers
- Outermost ring: web framework, database, UI and external services
- Screaming architecture
- Top-level structure reveals the system's purpose, not its framework
- Application layer
- Use cases plus interfaces the infrastructure implements
- Domain layer
- Entities, value objects and domain rules with no infrastructure
- Infrastructure layer
- Implementations of persistence, messaging and external services
- Layered architecture
- Code organized in horizontal layers like presentation, business and data
- Sinkhole anti-pattern
- Requests passing through layers that add no logic
- Layers vs tiers
- Layers are logical groupings; tiers are physical deployments
- Strict layering
- A layer may call only the layer immediately beneath it, not skip ahead
- Relaxed layering
- A layer may skip an intermediate layer and call a lower one when the design allows it
- Enterprise business rules
- The most stable domain policies, held in entities at the center of Clean Architecture
- Application business rules
- Use-case-specific policies in the ring around the entities, independent of delivery mechanisms
- Source dependency
- A compile-time or import relationship, which the dependency rule requires to point inward
- Package by layer
- Organizing code into horizontal packages such as presentation, domain, and infrastructure rather than by feature
- Policy vs detail
- Inner rings hold stable business policy; outer rings hold volatile mechanisms such as frameworks and I/O
- n-tier architecture
- A deployment style in which presentation, processing, and data often run in separate process or machine tiers
9.2 Ports and adapters
- Port
- Interface owned by the core for talking to the outside
- Adapter
- Implementation connecting a port to a real technology
- Hexagonal architecture
- Alistair Cockburn's design: core with ports, plugged in by adapters
- Driving adapter
- Adapter that calls into the core, like a controller or consumer
- Driven adapter
- Adapter the core calls out through, like a repository
- Primary port
- Interface the core exposes for driving adapters
- Secondary port
- Interface the core uses to reach external systems
- Fake adapter
- In-memory port implementation for tests or local runs
- Anti-corruption layer
- Translation layer that keeps an external model out of the core
- Configurator
- Startup code wiring adapters to ports
- Inbound port
- A port the core offers so driving adapters can call in; also called a primary port
- Outbound port
- A port the core calls to reach an outside system; also called a secondary port
- Outside actor
- A person, program, or system that interacts with the application through an adapter
- Application core
- The inside of the hexagon: policy and ports that do not depend on a particular adapter's technology
- Persistence adapter
- A driven adapter that implements an outbound port using a database, file, or similar store
- Delivery adapter
- A driving adapter that takes an outside request such as HTTP, CLI, a UI event, or a message and calls an inbound port
- Port contract
- The application-owned language and behavior a port promises, independent of a particular technology
- Technology leak
- Vendor types, status codes, or product names appearing in the core or in a port's signature
9.3 Entities, use cases and the application layer
- Request model
- Simple input object for a use case, independent of transport
- Response model
- Simple output object from a use case for adapters to format
- Presenter
- Adapter turning use-case output into a view model
- Anemic domain model
- Entities with data but no behavior
- Domain service
- Stateless domain logic spanning several entities
- Application service
- Orchestrates loading, calling and saving aggregates for a request
- CQRS
- Command Query Responsibility Segregation: separate write and read models
- Mediator pattern
- Object routing requests to handlers, decoupling senders from receivers
- Pipeline behavior
- Cross-cutting step wrapped around mediator handlers
- Domain invariant
- Business rule an entity always enforces
- Humble object
- Thin hard-to-test part with logic moved to testable code
- Domain event
- Record that something meaningful happened in the domain
- Result type
- Return value carrying success or an expected error
- Interactor
- Another name for a use-case object that runs one application operation
- Rich domain model
- Entities that carry behavior and enforce invariants, rather than exposing bare fields for services to set
- Command model
- A request object that carries the data a state-changing use case needs, independent of transport
- Expected failure
- A business outcome a use case can return as a result, such as already cancelled, rather than treating it as a crash
- Use-case output port
- An interface the use case calls to deliver a response to a presenter, without depending on UI or HTTP types
- Domain exception
- An exception that represents a broken business rule, as opposed to an infrastructure or programming failure
- Use case interface
- The application-owned contract a driving adapter calls to run one operation, often called an input port
- Write model
- The model used to enforce invariants when changing state, as distinct from a shape optimized only for queries
9.4 SOLID principles at the architecture level
- SOLID
- Five object-oriented design principles: SRP, OCP, LSP, ISP, DIP
- Dependency injection
- Supplying dependencies from outside a class
- Dependency inversion
- High and low-level modules both depend on abstractions
- Single Responsibility Principle
- A module should answer to one actor or reason to change
- Open/Closed Principle
- Open for extension, closed for modification
- Liskov Substitution Principle
- Subtypes must work wherever their base type is expected
- Interface Segregation Principle
- Clients shouldn't depend on methods they don't use
- Dependency Inversion Principle
- High- and low-level modules depend on abstractions
- Common Closure Principle
- Group classes that change together for the same reasons
- Acyclic Dependencies Principle
- No cycles in the component dependency graph
- Stable Dependencies Principle
- Depend toward stability
- Stable Abstractions Principle
- Stable components should be abstract
- Main component
- Outermost component that creates and wires all the others
- Reuse/Release Equivalence Principle
- The unit you expect others to reuse must be the unit you version and release
- Common Reuse Principle
- Classes reused together belong in the same component; do not force a consumer to depend on types it does not use
- Zone of uselessness
- The region of highly abstract but unstable components, which churn without providing a firm foundation
- Main sequence
- The desirable balance where a component's abstractness rises with its stability
- Dependency cycle
- A loop in the component graph so that no package in the loop can be understood or released on its own
- Abstractness metric
- The fraction of a component's types that are abstract, used with stability in the main-sequence picture
- Extension point
- A stable hook, such as a port or strategy, where new behavior can be plugged in without editing the closed policy
- Axis of change
- A direction along which a module is asked to evolve, usually corresponding to one actor or one kind of variation
9.5 Dependency injection and cross-cutting concerns
- Cross-cutting concern
- Behavior many features need, like logging, security or caching
- Commit boundary
- Point where a use case commits all its changes as one step
- Aspect-oriented programming
- Applying cross-cutting behavior separately via aspects
- Correlation ID
- Identifier tying together logs and traces for one request
- Global exception handler
- Outer-layer handler turning unhandled errors into safe responses
- Request context
- Per-request data like user, tenant and correlation ID
- Idempotency key
- Client-supplied key so repeated requests don't repeat the effect
- Middleware pipeline
- Chain of request-handling steps around the app
- Multi-tenancy
- One app serving several isolated customer tenants
- Audit trail
- Record of who changed what and when
- Tenant context
- The bound tenant identity for the current operation, supplied by the edge rather than guessed from untrusted input
- Context propagation
- Passing a correlation ID, and often a tenant or actor, onto outbound calls and into inner layers so one action stays joined
- Use-case decorator
- A wrapper around a use-case port that applies logging, a transaction, or other cross-cutting policy to every call
- Tenant resolution
- Identifying and binding the tenant at the edge from a trusted source such as a host name or a token claim
- Resource-based authorization
- A decision that depends on the actor's relationship to a particular resource, not only on a coarse role
- Ambient transaction
- An implicit, context-flowing transaction that later code can join without seeing it, which can accidentally widen a commit boundary
- Current-user port
- An application abstraction that supplies the already-authenticated actor, so the core does not read a web framework context
- Framework context leak
- Inner layers reaching for a host object such as HttpContext to get a user, tenant, or correlation ID
9.6 Boundaries, DTOs and data mapping
- DTO
- Data transfer object: plain data shape for crossing a boundary
- View model
- Data shaped for one screen or response
- Over-posting
- Clients setting fields they shouldn't via model binding
- Value object
- Immutable type defined by its values, like Money
- Primitive obsession
- Using raw strings and numbers for domain concepts
- Persistence model
- Separate ORM-mapped class translated to and from the domain
- Boundary
- Line where dependencies invert and data is translated
- Partial boundary
- Lighter separation that can be split into components later
- Projection
- Selecting only the fields a view needs
- Leaky abstraction
- Interface exposing details of the technology beneath it
- Problem Details
- RFC 9457 standard JSON shape for HTTP errors
- Strongly typed ID
- Wrapper type for IDs to stop mixing them up
- Contract test
- Verifies both sides agree on an API's shape
- Mapperly
- .NET source generator for compile-time object mapping
- DTO assembler
- A boundary object that maps between domain or application types and DTOs, rather than putting that translation on the entity
- Allowlist binding
- Accepting only the named input fields a caller may set, so unexpected properties cannot over-post onto a model
- Error type URI
- The Problem Details type member: a stable URI that identifies a kind of error and should stay meaningful as wording changes
- Field-level error
- A per-field problem in an error body, often with a pointer or name, so a client can highlight the exact input member
- Problem extension member
- A documented custom field on a Problem Details body, beyond type, title, status, detail, and instance
- Convention-based mapping
- Copying fields by matching names or other conventions, which is convenient and can silently pair the wrong members
- Public identifier
- The stable id a published DTO commits to, which may be a business number rather than a raw internal storage key
- Additive field
- A new contract field that existing clients can ignore or omit, typically a compatible change when it is not suddenly required
9.7 Testing a clean or hexagonal codebase
- Fake
- Simple working implementation of a dependency for tests
- Mock
- Test double that verifies expected interactions
- Testcontainers
- Library starting throwaway Docker dependencies from tests
- WebApplicationFactory
- ASP.NET Core helper hosting the app in memory for tests
- Test seam
- Place where behavior can be swapped for testing
- Testing trophy
- Model favoring integration tests
- Arrange-Act-Assert
- Test structure: set up, act, then check
- Mutation testing
- Changing code to see if tests catch it
- Characterization test
- Captures existing behavior before changing legacy code
- Snapshot test
- Compares output against a stored known-good version
- Fitness function
- Automated check of an architectural property
- Acceptance test
- Test of a business scenario end to end
- Clock port
- An inbound-to-the-core or outbound time abstraction a use case consults instead of reading the machine clock, so tests can fix or advance now
- Recording fake
- A working test stand-in for a port that remembers what it was asked to do, so a test can assert on recorded events or commands after the use case finishes
- Over-mocking
- Replacing too many collaborators with interaction-scripted mocks, so tests describe call choreography instead of business outcomes and break on harmless refactors
- Wait strategy
- A Testcontainers readiness policy that waits for a port, log line, HTTP status, or health check before a test connects, instead of sleeping a guessed interval
- Subcutaneous test
- A test that drives the application just under the UI or HTTP edge, often through use-case APIs, so it exercises real behavior without the fragility of the presentation layer
- Solitary unit test
- A unit test that isolates the subject by substituting tight doubles for its collaborators, as opposed to a sociable test that lets nearby real types run
- Narrow integration test
- A focused test of one real adapter against real infrastructure, without dragging a whole user journey through the UI
- Pinning test
- A characterization-style test that records current observable behavior so a structural refactor, such as extracting a port, cannot quietly change results
9.8 Vertical slices, modular monoliths and alternatives
- Vertical slice
- Code organized by feature across all layers
- Modular monolith
- One deployable with strong internal module boundaries
- Vertical slice architecture
- Organizing code by feature end to end
- Feature folders
- Grouping files by feature instead of by technical type
- Transaction script
- One procedure per request handling all its logic
- Table module
- One class handling logic for all rows of a table
- Service layer
- Boundary of application operations coordinating the domain
- Big design up front
- Detailed architecture fixed before learning from use
- Last responsible moment
- Delaying decisions until enough is known, but no later
- Shared kernel
- Small jointly owned model several modules depend on
- Functional core, imperative shell
- Pure logic inside, I/O at a thin outer layer
- Architecture quantum
- Independently deployable, cohesive unit including its data
- Microkernel architecture
- Small core extended by plug-ins
- Big ball of mud
- System without clear structure where everything depends on everything
- Package by feature
- Organizing source so a feature's types live together, rather than grouping all controllers, services, and repositories by technical role
- Schema per module
- Giving each module its own database schema so data ownership stays explicit even when modules share a database server
- Integration database
- A shared database several modules or applications read and write freely, coupling them through tables instead of contracts
- Package by component
- Grouping the parts of one cohesive component behind a narrow public interface, with implementations and helpers kept non-public
- Data ownership
- The rule that one module is the sole writer, and usually the sole reader of private tables, for a given set of data
- In-process contract
- The public commands, queries, events, and types a module exposes to other modules in the same deployable, used instead of reaching into internals
- Cross-module join
- A query that joins tables owned by different modules, quietly coupling their schemas without going through a contract
- Module facade
- A narrow public front that translates incoming requests into a module's internal model and keeps callers off internals and private data
9.9 Enforcing and evolving architecture
- ArchUnit
- Java library for asserting architecture rules in unit tests
- NetArchTest
- .NET library for architecture rule tests
- Architecture test
- Automated test that checks dependency and layering rules
- Architecture decision record
- Short note of a decision, its context and consequences
- C4 model
- Context, containers, components and code diagrams
- Strangler fig pattern
- Gradually replacing legacy code by routing features to new code
- Architecture erosion
- Gradual drift from the intended structure
- Evolutionary architecture
- Architecture built to change incrementally, guided by fitness functions
- Conway's law
- Systems mirror the communication structure of the teams that build them
- Afferent coupling
- Number of modules that depend on a module
- Efferent coupling
- Number of modules a module depends on
- Instability metric
- Efferent / (afferent + efferent) coupling
- Zone of pain
- Stable, concrete modules that are hard to change
- Structurizr
- Tool for C4 models as code
- Diagrams as code
- Expressing architecture diagrams in versioned text, such as a Structurizr, PlantUML, or Mermaid model, so they can be reviewed and rendered
- ArchUnit freeze
- A baseline of known architecture-rule violations that ArchUnit stores so new violations fail the build while the old ones are paid down
- ADR status
- A lifecycle label on an architecture decision record, such as proposed, accepted, deprecated, or superseded, so readers know whether to follow it
- System landscape
- A C4-style diagram of several systems and their users, one zoom level above a single system's context diagram
- C4 container
- In the C4 model, a separately runnable or deployable process, application, or data store — not necessarily a Docker container
- MADR
- Markdown Any Decision Records, a markdown template for writing architecture decision records in a consistent, repo-friendly shape
- ArchUnitNET
- A .NET port of ArchUnit for asserting architecture rules in tests
- Y-statement
- A compact decision sentence of the form: in this context, facing these forces, we decided this, to achieve this, accepting these consequences
Sample practice questions
What is the dependency rule in Clean Architecture?
- Outer layers must never reference inner layers; only inner ones point out
- Every layer depends on the database layer, which sits at the center
- Dependencies may point in whichever direction is most convenient
- Dependencies point only inward; inner layers know nothing of outer ones
Answer: D. Dependencies point only inward; inner layers know nothing of outer ones The domain does not reference frameworks, databases or the UI.
What is hexagonal architecture (ports and adapters)?
- An architecture where every service must always run exactly six instances
- A network topology that connects six routers in a ring for redundancy
- A user interface layout made of six panels arranged in a hexagon
- The core defines ports, and adapters connect them to HTTP, databases and queues
Answer: D. The core defines ports, and adapters connect them to HTTP, databases and queues Alistair Cockburn introduced it to make apps equally drivable by users, tests and other programs.
What does a use case class typically do?
- Stores the application's data in tables on disk
- Configures the web server's routes and middleware
- Coordinates entities and ports to carry out one application action
- Renders the pages and forms that users interact with
Answer: C. Coordinates entities and ports to carry out one application action Like `PlaceOrder` or `CancelSubscription`.
What does the Single Responsibility Principle state?
- A module should have one reason to change
- A class may only contain a single method
- An app may only contain one single class
- A function may only take a single parameter
Answer: A. A module should have one reason to change Robert C. Martin frames it as "one actor" whose needs drive changes.
What is dependency injection?
- Injecting SQL fragments into a query to make it more flexible at runtime
- Installing NuGet or npm packages that the project depends on
- Copying shared code from one project into another to reuse it
- Supplying a class's dependencies from outside, often via its constructor
Answer: D. Supplying a class's dependencies from outside, often via its constructor ASP.NET Core has a built-in container: `builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();`
What is a DTO?
- A domain type object that holds all of an entity's business rules
- A database trigger object that runs after each insert
- A data transfer object: a simple shape for moving data across a boundary
- A distributed transaction object used by two-phase commit
Answer: C. A data transfer object: a simple shape for moving data across a boundary No behavior, just data.
A use case needs the current time to check whether a coupon is expired. What is the cleanest approach?
- Call `DateTime.Now` directly inside the domain logic
- Query the current time from the database server
- Inject a time abstraction like .NET's `TimeProvider`
- Hard-code today's date as a constant in the code
Answer: C. Inject a time abstraction like .NET's `TimeProvider` `TimeProvider` was added in .NET 8 and has a `FakeTimeProvider` for tests.
What is a vertical slice architecture?
- Slicing the database horizontally into shards, one per customer region
- Organizing by feature, each slice holding everything for one request
- Running each architectural layer on its own separate set of servers
- A CSS layout technique that splits the page into vertical columns
Answer: B. Organizing by feature, each slice holding everything for one request Jimmy Bogard popularized it; it reduces cross-layer ceremony for feature work.
How can teams enforce architecture rules automatically in .NET?
- By asking every developer to remember the rules during code reviews
- By disabling the compiler's warnings about project references
- Architecture tests with NetArchTest or ArchUnitNET that fail the build
- By putting every class into one single project so nothing can break
Answer: C. Architecture tests with NetArchTest or ArchUnitNET that fail the build Project references enforce some rules; architecture tests cover the rest.
In Clean Architecture, what sits at the very center?
- The web framework and its routing
- The database schema and its tables
- Entities: core business rules
- The REST controllers and their DTOs
Answer: C. Entities: core business rules Use cases (application business rules) form the next ring out.
More Architecture
- System Design Interview Fundamentals
- Monoliths vs Microservices
- Event-Driven Architecture
- Scalability: Horizontal and Vertical Scaling, Sharding and Partitioning
- CAP Theorem and Distributed Consistency
- High Availability and Fault Tolerance
- API Gateways and Service Meshes
- Domain-Driven Design
- Security Architecture: Zero Trust and OWASP Top 10
- AI and LLM Integration: RAG, Prompts and APIs