ADR-0002: Clean Architecture with single-responsibility use cases
Status: Accepted — amended 2026-09-10 (see the amendments below); Expenses’ compliance notes updated 2026-10-11
Date: 2026-05-30
Scope: core (any backend service)
Context
A REST API grows messy when controllers hold logic, services become grab-bags,
and validation is scattered. We want strict, predictable dependencies and one
obvious place for each kind of rule.
Decision
Layered Clean Architecture with dependencies pointing inward:
WebServices map DTO↔entity and orchestrate use cases.
Use cases have a single execute(), one responsibility, wrapped @Transactional; they return domain entities, never DTOs.
Services encode business rules, not repo pass-throughs — the method
name states the rule (e.g. findOwnedByUserOrThrow vs findAccessibleByUserOrThrow). BaseService provides findByIdOrThrow/save/delete.
Four-level validation, each with a home:
Presentation: annotation-based on DTO records.
Application: the validation strategy pattern — a @Component extending the
feature’s abstract base strategy, auto-discovered by the Validator bean. Adding
a rule needs no changes to existing code. These produce 400 (InvalidBodyException
carrying a ValidationResult). Never throw InvalidBodyException directly in a
use case — create a strategy.
Domain: constructor invariants.
Repository: sort/filter sanitization.
Operation guards (“can this run?”) stay inline in the use case and throw 409 (ConflictException). Exception hierarchy: EntityNotFoundException(404), InvalidBodyException(400), InvalidCredentialsException(401), ConflictException(409).
Generic infrastructure delegates live in one place: a BaseRepositoryAdapter<E,R>
implements the common JPA pass-throughs once, so feature adapters stay thin.
Amendment — 2026-09-10: transactional web services, whitelisted sort input, a catch-all only for server faults
Three presentation-layer rules that both Spring backends reached, or tripped over, with
no written home. They surfaced while building dracomania’s players and decks.
1. A WebService method is a transaction
Every WebService method is @Transactional, with readOnly = true on reads, and the
use case joins that transaction. Both backends run with open-in-view: false. Without
the outer transaction, the persistence context closes when the use case returns, and DTO
mapping that walks a lazy association throws LazyInitializationException. Evidence: 33
of Expenses’ 39 WebServices, and dracomania’s PlayerWebService and DeckWebService.
Never reach a write from a readOnly method. The joined use case inherits
read-only, and its changes are not flushed: no error, and no row.
A method that streams, or waits on a slow external call, holds no transaction.
Expenses’ ChatWebService (SSE, and an LLM tool loop) has none. Its use cases run
their own transactions, and nothing lazy is mapped outside them.
A WebService that maps nothing lazy would work without the annotation, but it breaks
the day one of its DTOs gains a lazy field. Add the annotation anyway.
2. Sort input is a whitelist, never a raw Pageable
This is what the repository: sort/filter sanitization level above means in practice.
A controller does not bind a raw Spring Data Pageable and pass its sort through.
Doing so lets a client sort by any entity property name, and an unknown or malformed
one reaches the query and surfaces as a 500. Accept sort as a closed set (an enum
of sortable fields, mapped to property paths) or not at all. Page number and size may
still bind.
A small, bounded list returns a plain List, with no paging contract.
A mapped sort names the entity’s property path, not the column: an embedded field sorts
by its path (attributes.magic, not magic). The id tiebreaker still applies
(0016-stable-pagination-tiebreaker).
Found in dracomania, whose catalogue reads first took a Pageable. Expenses complied later
(backend v1.74.0): its list endpoints take page / size, and where the client may sort, a sort checked against a per-endpoint enum (PageRequests.sorted, an unknown field is a 400).
Before that, ten of its controllers bound a raw Pageable.
3. The catch-all is for server faults only
The global handler’s @ExceptionHandler(Exception.class) resolves before Spring MVC’s
default resolver does. It therefore also catches the framework exceptions that mean the client erred, and answers them with a 500. Every such exception is mapped to its 4xx
explicitly. The ones met so far:
Exception
Cause
Status
HttpMessageNotReadableException
a body that is not JSON, or holds a value of the wrong type
400
MethodArgumentTypeMismatchException
a path or query value of the wrong type (/decks/not-a-uuid)
400
NoResourceFoundException
an unknown route
404
HttpRequestMethodNotSupportedException
a known route called with a verb it does not accept
Spring MVC’s other standard exceptions (a missing parameter, an unsupported media type)
fall under the same rule. A 500 in response to bad client input is a bug, however wrong
the request was. Dracomania maps the two 400s, the 404 and the 405, and adds the 403 with
its security. Expenses mapped only the 403 pair until backend v1.74.0; it now maps all of the
above plus a missing parameter (400) and media types (415 / 406), and routes the filter
chain’s own 401 / 403 through the same handler so every error shares one body shape.
Amendment — 2026-09-10: a write that must survive a refusal commits on its own
A use case runs in one transaction, and a refusal ends it by throwing. The throw rolls back
everything the transaction wrote, including a write the refusal depends on. The response
still looks right, which is why this is found by running the flow, not by reading it. Both
backends met it and fixed it the same way.
A write that must outlive the use case’s rollback runs in @Transactional(propagation = Propagation.REQUIRES_NEW). It is one of two kinds:
what a refusal rests on: a session family revoked because a spent refresh token came
back (0013-sessions-and-refresh-tokens §2), or a wrong attempt counted against a
reset code. Rolled back, the first leaves a stolen family alive, and the second makes
the attempt limit decorative;
a record of an attempt: an email sent, a webhook received, a job run, an AI call’s
usage, a login attempt. These matter most when the work failed.
The method lives on a bean of its own. Spring applies REQUIRES_NEW through the
proxy, so a call from inside the same bean silently joins the outer transaction. Name the
bean for its reason: SessionRevocationTransactional, PasswordResetAttempts, Expenses’ JobRunTransactional.
Keep the inner transaction to one short write, on rows the outer transaction has not
written. A row the outer transaction has already updated stays locked until it commits,
and the outer transaction is waiting on the inner one.
A write that returns normally (a logout, a revocation the user asked for) commits with
its caller and needs none of this.
Evidence: dracomania SessionRevocationTransactional and PasswordResetAttempts; Expenses SessionRevocationTransactional, EmailDeliveryService, PaymentWebhookEventLogger, JobRunTransactional, AiUsageService and LoginAttemptService, and since backend v1.74.0 PasswordResetAttempts and TwoFactorChallengeAttempts (a wrong reset code, a wrong
second-factor code).
Example
Real code from the repos — optional
Agents: safe to skip. The Decision above is the specification; everything below is
illustration. Skipping this block costs you nothing normative and saves tokens. Expand it
when you need the shape rather than the rule — porting the pattern to a new project, or
answering “what does this actually look like”.
@Component@RequiredArgsConstructorpublic class DeleteCsvImportTemplateUseCase { private final CsvImportTemplateService templateService; @Transactional public void execute(UUID id, UUID userId) { CsvImportTemplate template = templateService.findAccessibleByUserOrThrow(id, userId); if (template.isSystem()) { throw new ConflictException("System templates cannot be deleted", ApiErrorCode.CSV_TEMPLATE_SYSTEM); } templateService.delete(template); }}
One execute(), one responsibility, one transaction. It takes a userId rather than
reaching for a security context, so the use case stays a plain object that can be called
from anywhere and reasoned about without Spring.
The access rule is not inline. findAccessibleByUserOrThrow is a service method whose
name states the rule, so “which templates may this user address” is answered in one place
rather than re-derived at every call site:
Note it returns the entity, not a DTO — mapping is the web service’s job — and that a
template the user may not touch is a 404, not a 403. Distinguishing the two would confirm
that someone else’s template exists.
The WebService that calls the use case above. It is where the transaction is opened and
where the authenticated user is read — which is why the use case takes a userId and
touches no security context. The reads are readOnly = true; open-in-view is off, so
without this outer transaction CsvImportTemplateResponse::new would walk a closed
persistence context.
/** * Reuse detection refuses the token by throwing, and a throw rolls the * surrounding transaction back — which would quietly undo the revocation the * refusal was based on, leaving a stolen family alive. */@Service@RequiredArgsConstructorpublic class SessionRevocationTransactional { private final SessionRepositoryPort repository; @Transactional(propagation = Propagation.REQUIRES_NEW) public int revokeFamily(UUID familyId, SessionRevocationReason reason) { return repository.revokeFamily(familyId, reason, Instant.now()); }}
A bean of its own, holding one short write — both deliberate. REQUIRES_NEW is applied
through the Spring proxy, so calling this from inside the revoking service would silently
join the outer transaction and be rolled back with it. The class is named for its reason
rather than its subject, which is how you can tell at the call site that it commits
independently.