ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 5 · Software Design & Design Patterns
  4. Volume V
  5. Service Layer
Book 5 · Volume V — Enterprise & Application Design Patterns · Topic 1.2

Service Layer

Application services, transaction boundaries and business orchestration

9 min readStage 2 · Frameworks & design8 interview questions
Chapter
Chapter 1 — Enterprise Architecture Patterns
Prerequisites
Topic 1.1; Volume III Topic 8.3 (Service Facades); Volume IV Chapter 4 (Command)
You will be able to
Define an application's use cases as a service layer, place transaction boundaries correctly, orchestrate domain objects and infrastructure without absorbing business rules, and keep services thin as the application grows
Covers
Application services; Transaction boundaries; Business orchestration
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Spring's Transactional Service
  5. 4A. Deep Dive — Keeping the Service Layer Healthy as It Grows
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

The Service Layer defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation (Fowler). In practice: one application service method per use case.

Where the service layer sits
Figure 1 — Where the service layer sits
AspectService layer's role
APIThe set of use cases the application supports
CallersEvery inbound adapter: REST, messaging, scheduler, CLI
TransactionsBegin and end the unit of work
SecurityAuthorise use cases
OrchestrationLoad aggregates, invoke domain behaviour, persist, publish events, call gateways
Table 1 — Service layer responsibilities

2Why It Exists

Applications are reached through several channels — web, mobile API, messaging, batch. Without a common service layer, each channel re-implements the use case, and rules, transactions and security diverge. The service layer gives every channel the same operations with the same guarantees, and gives developers one obvious place to look for "what can this application do?".

3Core Concepts

3.1 Application services

An application service groups related use cases (often per aggregate or feature) and exposes intention-revealing methods taking commands and returning results.

JAVA
public record TransferMoney(CommandId id, AccountId from, AccountId to, Money amount) {}
public record TransferResult(TransferId transferId, Money newBalance) {}
 
@Service
public class TransferService {
    private final AccountRepository accounts;
    private final TransferRepository transfers;
    private final ApplicationEventPublisher events;
    private final Clock clock;
 
    // constructor injection omitted
 
    @Transactional
    @PreAuthorize("hasAuthority('TRANSFER')")
    public TransferResult transfer(TransferMoney cmd) {
        if (transfers.existsByCommandId(cmd.id())) {                  // idempotency
            return transfers.resultOf(cmd.id());
        }
        Account from = accounts.get(cmd.from());
        Account to   = accounts.get(cmd.to());
        Transfer t = Transfer.execute(from, to, cmd.amount(), clock); // domain behaviour
        accounts.save(from);
        accounts.save(to);
        transfers.save(t, cmd.id());
        t.pullEvents().forEach(events::publishEvent);
        return new TransferResult(t.id(), from.balance());
    }
}
Responsibilities of an application service
Figure 2 — Responsibilities of an application service
Design ruleReason
One public method per use caseClear API; easy authorisation and metrics per use case
Commands/records as input, results/DTOs as outputStable contracts; no entities leaking
No HTTP/messaging typesSame service for all channels
StatelessSafe as a Spring singleton
Group by feature/aggregateAvoid god services
Table 2 — Application service design rules

3.2 Transaction boundaries

The service method is the natural unit of work: it should begin a transaction, perform all changes of one use case and commit once.

Transaction boundary around a use case
Figure 3 — Transaction boundary around a use case
PlacementProblem
@Transactional on repositories onlyEach save commits separately — partial updates on failure
@Transactional on controllersCouples web layer to persistence; long transactions including rendering
@Transactional on service methodOne use case = one atomic unit ✔
Nested services each with REQUIRES_NEW by defaultAccidental independent commits
Table 3 — Where transactions belong

Rules for healthy transaction boundaries:

  • Short: no remote calls, no user interaction, no large file processing inside.
  • Complete: all state changes of the use case inside the same transaction; integration events written to an outbox in the same transaction.
  • Explicit read-only for queries: @Transactional(readOnly = true).
  • Proxy-aware: @Transactional works through Spring proxies — no self-invocation (Volume III Topic 9.4).
JAVA
@Transactional(readOnly = true)
public OrderView view(OrderId id) {
    return OrderView.from(orders.get(id));      // map inside the transaction (Topic 3.2)
}

When one use case must call a slow external system, split it: a transaction to record intent, the external call outside, and another transaction to record the result (or an outbox + asynchronous processor).

JAVA
public PaymentResult pay(PayOrder cmd) {
    var attempt = tx.execute(s -> attempts.start(cmd));               // tx 1
    var result = paymentGateway.charge(attempt.request());            // no tx held
    return tx.execute(s -> attempts.complete(attempt.id(), result));  // tx 2
}

3.3 Business orchestration

Orchestration means sequencing domain operations and infrastructure calls to fulfil a use case — without owning the business decisions.

Thin service vs fat service
Figure 4 — Thin service vs fat service
JAVA
// Fat (anemic): rules live in the service
if (account.getBalance().compareTo(cmd.amount()) < 0) throw new InsufficientFunds();
if (account.getStatus() == FROZEN) throw new AccountFrozen();
account.setBalance(account.getBalance().subtract(cmd.amount()));
 
// Thin: service orchestrates, aggregate decides
account.withdraw(cmd.amount());   // throws InsufficientFunds / AccountFrozen
Belongs in the service (orchestration)Belongs in the domain (decisions)
Loading and saving aggregatesBalance and limit rules
Calling gateways, publishing eventsState transitions and their legality
Idempotency, authorisation, transactionsCalculations (totals, fees, discounts)
Mapping commands/resultsInvariants across an aggregate's parts
Table 4 — Division of labour

Logic that spans several aggregates but is still a business rule belongs in a domain service (e.g. TransferPolicy deciding whether a cross-currency transfer is allowed), called by the application service.

4How It Works Internally — Spring's Transactional Service

1. The controller calls transferService.transfer(cmd) on a Spring proxy.

2. TransactionInterceptor obtains a transaction from the PlatformTransactionManager (binding a connection and JPA persistence context to the thread).

3. The method loads aggregates (persistence context tracks them), invokes domain behaviour, saves, and publishes events.

4. On return, the interceptor flushes the persistence context (SQL), commits, then runs AFTER_COMMIT listeners.

5. On a runtime exception, it rolls back; changes and after-commit events are discarded.

4ADeep Dive — Keeping the Service Layer Healthy as It Grows

Growth symptomRemedy
OrderService with 60 methodsSplit by use-case area: OrderPlacementService, OrderFulfilmentService, OrderQueryService
Services calling services calling servicesExtract domain services; limit service-to-service calls to one level
Many if rules in servicesMove rules into aggregates/domain services
Heavy read logic mixed with writesSeparate query services reading projections (CQRS-light)
Cross-cutting code repeated (logging, idempotency)Command bus behaviours or AOP (Volume IV Chapter 6)
Table 5 — Growth management

Command/query separation at the service level. Separating write services (commands, transactions, aggregates) from read services (queries, projections, no aggregates) keeps each simple: writes protect invariants, reads optimise for screens.

JAVA
@Service
@Transactional(readOnly = true)
class OrderQueries {
    private final JdbcClient jdbc;
    List<OrderSummary> recentFor(CustomerId c) {
        return jdbc.sql("""
                    select id, total, status, placed_at from orders
                    where customer_id = ? order by placed_at desc limit 20""")
                   .param(c.value()).query(OrderSummary.class).list();
    }
}

5APIs / Features / Syntax

APIUse
@ServiceApplication service stereotype
@Transactional (propagation, readOnly, rollbackFor, timeout)Transaction boundary
TransactionTemplateProgrammatic boundaries, split transactions
@PreAuthorizeUse-case authorisation
ApplicationEventPublisher, @TransactionalEventListenerEvents and after-commit side effects
RecordsCommands and results
Micrometer @Observed / @TimedMetrics per use case
Table 6 — Service-layer APIs

6Practical Examples

6.1 Same use case, three channels

JAVA
@PostMapping("/transfers")
TransferResult rest(@RequestBody TransferRequest r) {
    return service.transfer(r.toCommand());
}
 
@KafkaListener(topics = "transfers")
void msg(TransferRequested e) { service.transfer(e.toCommand()); }
 
@Scheduled(cron = "0 0 1 * * *")
void standingOrders() { due().forEach(s -> service.transfer(s.toCommand())); }

All three get the same rules, transactions, security and idempotency.

6.2 Testing an application service

With in-memory fake repositories and a fixed Clock, application-service tests are fast and verify orchestration: correct aggregates loaded, saved, events published, idempotency honoured.

6.3 Splitting a slow use case

A report-export use case held a transaction for 90 seconds while generating a PDF. Splitting into "record export request" (tx), background generation (no tx), and "mark completed" (tx) removed connection-pool exhaustion.

7Common Problems & Mistakes

  • Fat services / anemic domain.
  • Transactions around remote calls or long computations.
  • @Transactional on private methods or self-invoked methods — ignored.
  • Services returning entities — lazy-loading failures later.
  • Service-to-service call chains creating hidden coupling and nested transactions.
  • God services grouping unrelated use cases.

8Performance & Production Considerations

SignalWhy
Transaction duration per use caseLong transactions exhaust pools and hold locks
Connection pool wait timeSymptom of long or too many transactions
Use-case latency and error rateService methods are natural SLI boundaries
Rollback rate by exception typeBusiness rejections vs technical failures
Table 7 — What to monitor

Most service-layer incidents are transaction problems. Give every write use case a time budget and enforce it with @Transactional(timeout = ...) or a database statement timeout, because one slow query or remote call inside a transaction holds a pooled connection and row locks for its full duration. Size the HikariCP pool from measured transaction time and concurrency rather than raising it under pressure; more connections often just move the bottleneck into the database. Add Micrometer observations per service method so latency, error rate and rollbacks are reported per use case, and alert on connection-pool wait time. Keep after-commit listeners fast or hand them to an executor, and make every command idempotent, because client and message-broker retries will happen in production.

9Architecture & Design Considerations

  • Treat the service layer as the published API of a module; other modules call it (or react to its events), never its internals.
  • Keep transactions within one module; cross-module consistency via events/outbox.
  • Separate command and query services when read and write needs diverge.
  • Use the service layer as the extraction seam when splitting into microservices.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is the Service Layer pattern?

The Service Layer, from Fowler's Patterns of Enterprise Application Architecture, defines an application's boundary as a set of services that expose the available operations and coordinate the application's response to each one. In practice each public method of an application service is one use case, such as transfer, placeOrder or cancelSubscription, taking a command and returning a result. The service begins and ends the transaction, authorises the call, loads aggregates, invokes domain behaviour, saves and publishes events. Every inbound channel, whether REST, Kafka, a scheduler or a CLI, calls the same methods, so rules and guarantees cannot diverge. The service orchestrates; the domain objects make the business decisions.

Q2L1 · BasicConcept

Where should @Transactional usually be placed?

Usually on public application service methods, so that one use case runs as one transaction: all its changes commit together or roll back together. Placing it only on repositories makes each save commit separately, leaving partial updates when a later step fails. Placing it on controllers couples the web layer to persistence and stretches transactions over serialisation and rendering. Mark query methods @Transactional(readOnly = true). Because Spring applies transactions through proxies, the annotation is ignored on private methods and on calls from another method of the same bean, so self-invocation silently runs without the intended boundary. Keep the boundary short and free of remote calls.

Q3L2 · IntermediateConcept

What is the difference between orchestration and business logic?

Orchestration is the sequencing of a use case: load the aggregates, call domain behaviour, save the results, publish events, call gateways, and handle idempotency, authorisation and transactions. Business logic is the decisions themselves: whether the balance is sufficient, whether the account is frozen, which state transitions are legal, how fees and totals are calculated. Orchestration belongs in the application service; business logic belongs in entities, value objects and domain services. The test is simple: if a service contains if statements about business rules followed by setters, the logic has leaked. A thin service calls account.withdraw(amount) and lets the aggregate throw InsufficientFunds or AccountFrozen.

Q4L2 · IntermediateTricky

Why should services not return JPA entities?

Returning JPA entities couples every caller to the persistence model and moves transaction problems outside the service. Lazy associations accessed after the transaction has closed throw LazyInitializationException or, with open-session-in-view enabled, trigger hidden queries during JSON serialisation, often as N+1 selects. Callers can also invoke mutating methods on a detached entity outside any use case, bypassing authorisation and invariants, and any change to the mappings ripples into API contracts. Instead, return records or DTOs built inside the transaction, such as OrderView.from(order), or just an ID from commands. That gives a stable contract, fetches exactly what the caller needs, and keeps entities inside the module boundary.

Q5L3 · Senior EngineerScenario

How do you handle a use case that must call a slow external system?

Never hold a database transaction open across the slow call, because it pins a pooled connection, holds locks and fails badly when the external system times out. Split the use case instead. In a first short transaction, record the intent, such as a payment attempt in PENDING state with an idempotency key. Make the external call outside any transaction, with timeouts and bounded retries. In a second transaction, record the result and complete the domain change. Alternatively, write the request to a transactional outbox in the first transaction and let an asynchronous processor make the call. Either way, design for partial failure: a reconciliation job must resolve attempts left pending after a crash.

Q6L3 · Senior EngineerConcept

What are signs of an anemic domain in the service layer?

The domain classes are just data holders with getters and setters, and every decision lives in services. Typical signs are service methods full of if checks on entity fields followed by setters, such as comparing getBalance() with an amount and then calling setBalance(); the same validation duplicated across services, batch jobs and controllers; entities with public setters for status fields, so a PAID order can be set back to DRAFT; and tests that need many mocks to verify a single rule. Services also grow to dozens of methods. The remedy is to move each rule onto the aggregate or domain service that owns the data, leaving services to orchestrate calls like account.withdraw(amount).

Q7L4 · Technical ArchitectDesign

How do you keep service layers manageable in large applications?

Split services by use-case area rather than by entity, for example OrderPlacementService, OrderFulfilmentService and OrderQueryService instead of one OrderService with sixty methods. Separate command services, which load aggregates and protect invariants inside transactions, from query services that read projections directly with JdbcClient or database views, a light form of CQRS. Push business rules into aggregates and domain services so the services stay thin. Avoid deep service-to-service call chains: limit them to one level and use domain events for side effects. Handle cross-cutting concerns such as idempotency, logging and metrics once, through AOP or a command bus, and enforce module boundaries with Spring Modulith or ArchUnit.

Q8L5 · Solution ArchitectDesign

Why is the service layer the key seam for microservice extraction?

Because the service layer already defines what a future microservice would offer. Its public methods are the use-case API, its transaction boundaries show what must stay consistent together, and its published events show what other parts of the system need to know. If other modules call only that API and react only to those events, never touching its repositories or entities, extraction becomes largely mechanical: put the module behind a REST or messaging interface and replace local calls with remote ones. A transaction spanning two modules signals they should stay together or need a saga. Without a clean service layer, extraction first means untangling hidden dependencies, which is where most migrations stall.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.