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.
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.
| Domain | Required behavior | Design constraint |
|---|---|---|
| Account and authentication | Registration, login, token refresh | Validate input and give authors and administrators distinct permissions |
| Post, comment, and tag | CRUD, tags, search, and sorting | Limit titles to 200 characters and bodies to 1,000, soft-delete records, and warn on day nine before the ten-day editing limit |
| Image upload | Attach several images | Enforce the 15 MB limit and validate formats at the boundary |
| View count | Count reads of the detail endpoint | Reserve counts in Redis to limit duplicate writes |
| Notification | Report comments, likes, and edit deadlines | Let domain events trigger notifications without a synchronous dependency from the board |
| Writing tone | Analyze posts and generate draft rewrites | Keep 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
| Design | Transaction boundary | Read behavior | Cost |
|---|---|---|---|
| One service per domain | Readers and writers live in the same class | Each method needs the appropriate transaction | Few classes |
| Separate command and query services | Each class owns one transaction policy | A query service can default to readOnly = true | More service classes and clear boundaries |
| Separate read store and write store | Each side has its own persistence path | A dedicated read model can serve projections | Synchronization 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
synchronizedsection may pin a carrier thread on Java 21. Keep such sections small or use aReentrantLockwhere 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: falseand 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
- Exercise a query and a write through their Spring-managed services. Check the read-only flag and confirm that writes update the audit timestamps.
- Run the database integration cases against PostgreSQL, especially where a query relies on locks or dialect behavior.
- Serialize responses with OSIV disabled and check that list requests use batched reads where expected.
- Verify that management port
8081is reachable from the probe and that Swagger follows the active profile.
