Spring › Wanted-Challenge

Designing a Spring Boot board with three layers and CQRS

Turn a backend challenge brief into domain boundaries, read and write services, JPA auditing, and environment profiles for a Spring Boot board.

Designing a Spring Boot board with three layers and CQRS

I turned a bulletin-board assignment into a Spring Boot service with domain-oriented packages and separate read and write services. Those boundaries kept the database shared while making auditing, event publication, and deployment behavior explicit.

The project uses Java 21, Kotlin 1.9.25, Spring Boot 3.5.16, PostgreSQL 17, Redis 8, and Spring AI 1.1.8.

Turning the brief into domain boundaries

The Wanted Pre-onboarding Backend Challenge asked for a board with accounts, authentication, posts, comments, images, view counts, and notifications. I also added a feature that analyzes a user’s writing tone. I grouped those requirements by the state they own and the operations they have to support.

DomainRequired behaviorDesign constraint
Account and authenticationRegistration, login, token refreshValidate input and give authors and administrators distinct permissions
Post, comment, and tagCRUD, tags, search, and sortingLimit titles to 200 characters and bodies to 1,000, soft-delete records, and warn on day nine before the ten-day editing limit
Image uploadAttach several imagesEnforce the 15 MB limit and validate formats at the boundary
View countCount reads of the detail endpointReserve counts in Redis to limit duplicate writes
NotificationReport comments, likes, and edit deadlinesLet domain events trigger notifications without a synchronous dependency from the board
Writing toneAnalyze posts and generate draft rewritesKeep Spring AI and Google GenAI calls outside database transactions

I used Kotest, MockK, Fixture Monkey, and ArchUnit for test coverage. The OpenAPI document identifies which endpoints need authentication and exposes the last Git commit so an API response can be traced back to the deployed version.

Three layers with separate reads and writes

The top-level packages follow the domains. Within each, presentation owns HTTP contracts, application coordinates use cases, and domain owns business state and rules. The writing-tone package also has an infrastructure layer for its external AI client.

1
2
3
4
5
6
org.project.portfolio
├── article          # presentation / application(Command·Query·scheduler) / domain(event·validator)
├── auth / user / notification
├── writing/tone     # presentation / application / domain / infrastructure
├── common           # aop / domain / presentation / storage / utils
└── config           # Security, JWT, JPA Auditing, Redis, Async, Swagger
DesignTransaction boundaryRead behaviorCost
One service per domainReaders and writers live in the same classEach method needs the appropriate transactionFew classes
Separate command and query servicesEach class owns one transaction policyA query service can default to readOnly = trueMore service classes and clear boundaries
Separate read store and write storeEach side has its own persistence pathA dedicated read model can serve projectionsSynchronization and eventual consistency

I used one database with ArticleCommandService and ArticleQueryService. Read-side operations commonly assemble response models, while writes enforce invariants and can publish events. Physically splitting the database would introduce a projection pipeline and a new failure mode before this board needed either.

flowchart TD
    Client["Client request"] --> Pres["Presentation (Controller)"]
    Pres -->|"Write"| Cmd["Command transaction"]
    Pres -->|"Read"| Qry["Read-only query"]
    Cmd --> Dom["Domain (Entity / Repository)"]
    Qry --> Dom
    Dom --> Infra["PostgreSQL 17 & Redis 8"]

@Transactional(readOnly = true) expresses the query side’s intent and lets Hibernate skip some dirty-checking work in a read-only session. It also creates a useful seam for replica routing later. I left simple domains in one service when their reads and writes had little code and shared the same collaborators. See the article and comment CQRS implementation for the read-side queries.

Sharing audit columns and publishing events

The entities share a BaseTimeEntity for creation and modification timestamps. I chose Instant because these values identify points on a timeline. The allOpen configuration includes @MappedSuperclass so Kotlin’s final-by-default declarations do not get in the way when Hibernate needs open entity classes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/main/kotlin/org/project/portfolio/common/domain/BaseTimeEntity.kt
package org.project.portfolio.common.domain

import jakarta.persistence.Column
import jakarta.persistence.EntityListeners
import jakarta.persistence.MappedSuperclass
import org.springframework.data.annotation.CreatedDate
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.time.Instant

@MappedSuperclass
@EntityListeners(AuditingEntityListener::class)
abstract class BaseTimeEntity(
    @CreatedDate
    @Column(nullable = false, updatable = false)
    var createdAt: Instant = Instant.now(),
    @LastModifiedDate
    @Column(nullable = false)
    var updatedAt: Instant = Instant.now(),
)

JpaAuditingConfiguration enables auditing separately from the main application class. When a focused @WebMvcTest excludes JPA, this avoids bringing in auditing configuration that needs a JPA metamodel bean.

1
2
3
4
5
6
7
8
9
// src/main/kotlin/org/project/portfolio/config/JpaAuditingConfiguration.kt
package org.project.portfolio.config

import org.springframework.context.annotation.Configuration
import org.springframework.data.jpa.repository.config.EnableJpaAuditing

@Configuration
@EnableJpaAuditing
class JpaAuditingConfiguration

I also considered AbstractAggregateRoot for domain events. Spring Data’s @DomainEvents callback runs on applicable repository methods such as save. Hibernate dirty checking at transaction commit does not call that repository callback. Kotlin single inheritance would also conflict with the shared audit base class. I instead published the domain event explicitly via ApplicationEventPublisher in the command service. Spring Data aggregate events

Profiles and runtime defaults

For quick local and test runs, I used H2 in PostgreSQL compatibility mode. For integration behavior, the Compose stack uses postgres:17-alpine and redis:8-alpine. H2 compatibility mode leaves differences in indexing, locking, and execution plans, so those database-specific behaviors belong in tests against PostgreSQL.

Production gets PostgreSQL 17 and Redis 8 connection details from environment variables. Actuator listens on port 8081 with health probes and ECS JSON logs. Swagger is disabled by default in that profile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# src/main/resources/application.yml
spring:
  application:
    name: portfolio
  profiles:
    default: local
  threads:
    virtual:
      enabled: true
  lifecycle:
    timeout-per-shutdown-phase: 30s
  jpa:
    open-in-view: false
    properties:
      hibernate:
        default_batch_fetch_size: 100
  data:
    redis:
      host: localhost
      port: 6379
      database: 2
server:
  shutdown: graceful
  • Virtual threads. With Java 21 and virtual threads enabled, requests waiting on ImgBB or Gemini can spend less time occupying platform threads. Blocking I/O inside a synchronized section may pin a carrier thread on Java 21. Keep such sections small or use a ReentrantLock where appropriate.
  • Graceful shutdown. On SIGTERM, the server stops accepting new requests and gives in-flight work up to 30 seconds in the shutdown phase. Confirm that the deployment environment grants the app that window.
  • Open Session in View. I set open-in-view: false and a default Hibernate batch fetch size of 100. Query services assemble DTOs before leaving the read transaction so JSON serialization never needs to initialize a detached lazy association.

Checks for the first deployment

  1. Exercise a query and a write through their Spring-managed services. Check the read-only flag and confirm that writes update the audit timestamps.
  2. Run the database integration cases against PostgreSQL, especially where a query relies on locks or dialect behavior.
  3. Serialize responses with OSIV disabled and check that list requests use batched reads where expected.
  4. Verify that management port 8081 is reachable from the probe and that Swagger follows the active profile.
Contribute to dev-mentoring/template development by creating an account on GitHub.
원티드 8월 프리온보딩 백엔드 챌린지 (게시글 CRUD). Contribute to cmsong111/Wanted-PreOnBoarding-Backend-Challenge development by creating an account on GitHub.
This post is licensed under CC BY 4.0 by the author.