Chapter 03

Service layer and REST API

The service owns the transaction and the rules. The controller owns HTTP and nothing else. Keeping that line clean is most of what separates a codebase that survives three years from one that does not.

⏱ 22 min readLevel: intermediateHands-on

The state machine, in code

order/OrderStatus.java
public enum OrderStatus {
    DRAFT, PLACED, PAID, FULFILLED, DELIVERED, CANCELLED, REFUNDED;

    private static final Map<OrderStatus, Set<OrderStatus>> ALLOWED = Map.of(
        DRAFT,     EnumSet.of(PLACED, CANCELLED),
        PLACED,    EnumSet.of(PAID, CANCELLED),
        PAID,      EnumSet.of(FULFILLED, REFUNDED),
        FULFILLED, EnumSet.of(DELIVERED, REFUNDED),
        DELIVERED, EnumSet.of(REFUNDED),
        CANCELLED, EnumSet.noneOf(OrderStatus.class),
        REFUNDED,  EnumSet.noneOf(OrderStatus.class));

    public boolean canTransitionTo(OrderStatus target) {
        return ALLOWED.get(this).contains(target);
    }

    public Set<OrderStatus> nextStates() {
        return ALLOWED.get(this);
    }
}
One map, three uses

The service validates against it, the API returns nextStates() in the order payload, and the Angular UI renders exactly those buttons. The rule lives in one place and the front end never re-implements it.

Order state machine diagram
Reference for the transitions encoded above.

The service

order/OrderService.java
@Service
public class OrderService {

    private final OrderMapper orders;
    private final ProductMapper products;
    private final OutboxMapper outbox;

    public OrderService(OrderMapper orders, ProductMapper products, OutboxMapper outbox) {
        this.orders = orders;
        this.products = products;
        this.outbox = outbox;
    }

    @Transactional(readOnly = true)
    public Order get(long id) {
        return orders.findById(id)
                     .orElseThrow(() -> new NotFoundException("order", id));
    }

    @Transactional(readOnly = true)
    public Page<OrderSummary> search(OrderSearchQuery q) {
        List<OrderSummary> rows = orders.search(q);
        // skip the count query when the first page is not full
        long total = (q.offset() == 0 && rows.size() < q.size())
                   ? rows.size()
                   : orders.countMatching(q);
        return new Page<>(rows, total, q.page(), q.size());
    }

    @Transactional
    public Order create(CreateOrderRequest req, String actor) {
        Map<Long, Product> catalogue = products.findByIds(req.productIds());

        List<OrderLine> lines = req.lines().stream().map(l -> {
            Product p = catalogue.get(l.productId());
            if (p == null) throw new NotFoundException("product", l.productId());
            return new OrderLine(null, p.id(), p.sku(), p.name(),
                                 l.quantity(), p.price(),
                                 p.price().multiply(BigDecimal.valueOf(l.quantity())));
        }).toList();

        Order order = new Order();
        order.setCustomerId(req.customerId());
        order.setStatus(OrderStatus.DRAFT);
        order.setCurrency("EUR");
        order.setMetadata(req.metadata());
        order.setTotalAmount(sum(lines));

        orders.insert(order);                       // id populated here
        orders.insertLines(order.getId(), lines);
        order.setLines(lines);

        recordEvent(order, null, OrderStatus.DRAFT, actor, "created");
        return order;
    }

    @Transactional
    public Order transition(long id, OrderStatus target, int expectedVersion, String actor) {
        Order order = get(id);

        if (!order.getStatus().canTransitionTo(target)) {
            throw new IllegalTransitionException(order.getStatus(), target);
        }
        if (target == OrderStatus.PLACED) {
            if (order.getLines().isEmpty()) {
                throw new BusinessRuleException("An order needs at least one line to be placed.");
            }
            reserveStock(order);
        }

        int updated = orders.updateStatus(id, target, expectedVersion);
        if (updated == 0) {
            throw new OptimisticLockException(id, expectedVersion);
        }

        recordEvent(order, order.getStatus(), target, actor, null);
        outbox.insert(new OutboxEvent(id, "order." + target.name().toLowerCase(),
                                      Map.of("orderId", id,
                                             "reference", order.getReference(),
                                             "status", target.name())));
        return get(id);
    }

    private void reserveStock(Order order) {
        for (OrderLine l : order.getLines()) {
            // atomic: the WHERE clause is the check
            if (products.decrementStock(l.productId(), l.quantity()) == 0) {
                throw new BusinessRuleException("Insufficient stock for " + l.sku());
            }
        }
    }

    private static BigDecimal sum(List<OrderLine> lines) {
        return lines.stream().map(OrderLine::lineTotal)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
Never check-then-act across two statements

SELECT stock_qty followed by UPDATE is a race: two concurrent orders both read 1 and both succeed. Push the condition into the write — UPDATE product SET stock_qty = stock_qty - #{qty} WHERE product_id = #{id} AND stock_qty >= #{qty} — and let the returned row count be the answer.

DTOs and validation

order/dto/CreateOrderRequest.java
public record CreateOrderRequest(
        @NotNull Long customerId,
        @NotEmpty @Size(max = 100) @Valid List<LineRequest> lines,
        Map<String, Object> metadata) {

    public record LineRequest(
            @NotNull Long productId,
            @Min(1) @Max(999) int quantity) {}

    public Set<Long> productIds() {
        return lines.stream().map(LineRequest::productId).collect(toSet());
    }
}
Never bind a request body to the domain object

If the controller accepted Order, a client could post {"status":"PAID","totalAmount":0} and skip the entire state machine. The DTO defines exactly what a client is allowed to say — notice there is no price and no status in CreateOrderRequest. Prices come from the catalogue, server-side.

The controller

order/OrderController.java
@RestController
@RequestMapping("/api/orders")
@Validated
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) { this.service = service; }

    @GetMapping
    public Page<OrderSummary> search(@Valid OrderSearchQuery query) {
        return service.search(query);
    }

    @GetMapping("/{id}")
    public OrderResponse get(@PathVariable long id) {
        return OrderResponse.from(service.get(id));
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity<OrderResponse> create(@Valid @RequestBody CreateOrderRequest req,
                                                Authentication auth) {
        Order created = service.create(req, auth.getName());
        return ResponseEntity
                .created(URI.create("/api/orders/" + created.getId()))
                .body(OrderResponse.from(created));
    }

    @PostMapping("/{id}/transitions")
    public OrderResponse transition(@PathVariable long id,
                                    @Valid @RequestBody TransitionRequest req,
                                    Authentication auth) {
        return OrderResponse.from(
            service.transition(id, req.target(), req.version(), auth.getName()));
    }

    @GetMapping("/{id}/events")
    public List<OrderEvent> events(@PathVariable long id) {
        return service.events(id);
    }
}
Why POST /{id}/transitions and not PATCH

A transition is an action with rules and side effects, not a field assignment. Modelling it as its own sub-resource gives it a natural place for the actor, the note, the expected version, and a 409 response — and stops anyone from "just" patching the status column.

Errors clients can actually use

common/ApiExceptionHandler.java
@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    ProblemDetail notFound(NotFoundException ex) {
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
        p.setTitle("Resource not found");
        p.setDetail(ex.getMessage());
        p.setType(URI.create("https://bitsnippets.com/errors/not-found"));
        return p;
    }

    @ExceptionHandler(IllegalTransitionException.class)
    ProblemDetail illegalTransition(IllegalTransitionException ex) {
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.CONFLICT);
        p.setTitle("Illegal state transition");
        p.setDetail("An order in %s cannot move to %s.".formatted(ex.from(), ex.to()));
        p.setProperty("allowed", ex.from().nextStates());
        return p;
    }

    @ExceptionHandler(OptimisticLockException.class)
    ProblemDetail stale(OptimisticLockException ex) {
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.CONFLICT);
        p.setTitle("The order was modified by someone else");
        p.setDetail("Reload the order and try again.");
        return p;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail invalid(MethodArgumentNotValidException ex) {
        ProblemDetail p = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        p.setTitle("Validation failed");
        p.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
            .map(f -> Map.of("field", f.getField(),
                             "message", f.getDefaultMessage()))
            .toList());
        return p;
    }
}
what the browser sees
{
  "type":   "about:blank",
  "title":  "Illegal state transition",
  "status": 409,
  "detail": "An order in DELIVERED cannot move to PAID.",
  "allowed": ["REFUNDED"]
}

The transactional outbox

"Save the order, then publish an event" is two systems and one of them will fail. Writing the event to outbox_event inside the same transaction makes it atomic; a poller publishes it afterwards.

common/OutboxPublisher.java
@Component
public class OutboxPublisher {

    @Scheduled(fixedDelay = 2000)
    @Transactional
    public void publishBatch() {
        // SKIP LOCKED lets several instances poll the same table safely
        List<OutboxEvent> batch = outbox.lockNextUnpublished(100);
        for (OutboxEvent e : batch) {
            broker.send(e.type(), e.payload());
            outbox.markPublished(e.id());
        }
    }
}
OutboxMapper.xml
<select id="lockNextUnpublished" resultType="OutboxEvent">
  SELECT event_id AS id, aggregate_id AS aggregateId, type, payload
  FROM   outbox_event
  WHERE  published_at IS NULL
  ORDER  BY event_id
  LIMIT  #{limit}
  FOR UPDATE SKIP LOCKED
</select>
At-least-once, not exactly-once

A crash between send and markPublished republishes the event. That is the correct trade-off: make consumers idempotent by keying on the event id rather than chasing a delivery guarantee that distributed systems cannot give you.

Testing the API

OrderControllerTest.java
@SpringBootTest(webEnvironment = RANDOM_PORT)
@Testcontainers
@AutoConfigureMockMvc
class OrderControllerTest {

    @Container @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired MockMvc mvc;

    @Test
    @WithMockUser(roles = "OPERATOR")
    void rejectsIllegalTransition() throws Exception {
        mvc.perform(post("/api/orders/{id}/transitions", deliveredOrderId)
                .contentType(APPLICATION_JSON)
                .content("""
                    {"target":"PAID","version":4}
                    """))
           .andExpect(status().isConflict())
           .andExpect(jsonPath("$.title").value("Illegal state transition"))
           .andExpect(jsonPath("$.allowed[0]").value("REFUNDED"));
    }

    @Test
    @WithMockUser(roles = "VIEWER")
    void viewerCannotCreate() throws Exception {
        mvc.perform(post("/api/orders").contentType(APPLICATION_JSON).content("{}"))
           .andExpect(status().isForbidden());
    }
}

Why does transition() take an expectedVersion from the client?

The version the client sends is the version it saw. If the row has moved on, the UPDATE … AND version = ? matches nothing and the operator is told to reload rather than clobbering a colleague's change.