How the Payments Platform separates reads and writes of the same aggregate without a dedicated read store, why another user's payment returns 404, and where the asynchronous projection falls behind
Published: November 21, 2026
Reading time: 14 min
Keywords: cqrs java, cqrs postgresql, spring boot cqrs, read model, redis cache aside
Payments Platform in practice series
Most CQRS discussions land on one of two extremes. In the first, CQRS means two databases: PostgreSQL for writes, Elasticsearch or MongoDB for reads, Kafka in between, and a replication delay nobody measures until a customer complains. In the second, CQRS means a PaymentQueryService next to a PaymentCommandService, both using the same JPA entity. The name changes; the model stays the same.
The Payments Platform sits at a point I find more useful for most systems: the read and write models are genuinely different, but they live in the same PostgreSQL database. This chapter shows how that works in the payments module, what the design gains, and what it gives up.
In chapter 1 I covered the boundaries between modules. Now the focus is what happens inside one of them. All excerpts come from commit 5277f6c.
findById methodsThe quickest way to understand this project's CQRS is to compare two interfaces. The first is the write port, which lives in the domain:
// src/main/java/com/muse/payments/payments/domain/PaymentRepository.java:6-11
public interface PaymentRepository {
Payment save(Payment payment);
Optional<Payment> findById(UUID id);
}
The second is the read port, which lives in the application layer:
// src/main/java/com/muse/payments/payments/application/PaymentReadRepository.java:11-22
public interface PaymentReadRepository {
Optional<Payment> findById(UUID id);
List<Payment> findByUserId(UUID userId, int page, int size, PaymentSort sort);
long countByUserId(UUID userId);
List<Payment> findByStatus(PaymentStatus status, int page, int size, PaymentSort sort);
long countByStatus(PaymentStatus status);
}
Both have a findById with the same signature. The difference is the implementation. The write-side findById, in EventSourcedPaymentRepository, loads the payment's event stream and rebuilds the aggregate by applying each event:
// src/main/java/com/muse/payments/payments/infrastructure/EventSourcedPaymentRepository.java:57-69
@Override
@Transactional(readOnly = true)
public Optional<Payment> findById(UUID id) {
Objects.requireNonNull(id, "id must not be null");
EventStream stream = eventStore.load(new StreamRef(PaymentEventRegistryConfiguration.STREAM_TYPE, id));
if (stream.events().isEmpty()) {
return Optional.empty();
}
List<DomainEvent> history = stream.events().stream()
.map(StoredEvent::event)
.toList();
return Optional.of(Payment.rehydrate(history));
}
The read-side findById, in PaymentJpaReadAdapter, is a primary-key lookup on the payments table, which is a projection, mapped to an object:
// src/main/java/com/muse/payments/payments/infrastructure/PaymentJpaReadAdapter.java:27-30
@Override
public Optional<Payment> findById(UUID id) {
return paymentJpaRepository.findById(id).map(PaymentJpaEntity::toDomain);
}
Why two paths to the same data? Because they answer different questions. A command such as "confirm payment" needs the latest consistent state to check an invariant, and needs the stream version to detect concurrent writes. A query such as "list my payments" needs an index, ordering and pagination, and has no invariant to check. Rehydrating a hundred aggregates from events to build one listing page would be expensive and pointless.
This design only exists since ADR 0016, which introduced event sourcing. Before it, ADR 0004 defined "CQRS as a code boundary, not as event sourcing": the payments table stored current state, the version column was the optimistic lock, and domain events were transient. ADR 0004 is worth reading in full, because it shows that CQRS without event sourcing is a legitimate, complete choice. Separate handlers, DTOs and ports already delivered most of the value. Event sourcing came later, for a different reason (rebuildable history), and chapter 3 covers that.
A complete command fits in a few lines. This is payment confirmation:
// src/main/java/com/muse/payments/payments/application/ConfirmPaymentCommandHandler.java:31-53
@Override
@Transactional
public PaymentResponse handle(ConfirmPaymentCommand command) {
Objects.requireNonNull(command, "command must not be null");
Payment payment = paymentRepository.findById(command.paymentId())
.filter(p -> p.isOwnedBy(command.userId()))
.orElseThrow(() -> new EntityNotFoundException("Payment not found with id: " + command.paymentId()));
payment.complete();
Payment saved = paymentRepository.save(payment);
for (var domainEvent : payment.pullDomainEvents()) {
IntegrationEvent integrationEvent = PaymentOutboxMapper.toIntegrationEvent(domainEvent);
if (integrationEvent != null) {
outboxPort.append(integrationEvent);
}
}
paymentCachePort.evictAfterCommit(saved.getId());
return PaymentResponse.from(saved);
}
Everything inside that @Transactional reaches the database together or not at all: the PaymentCompletedEvent in the event store, the update to the payments projection, and the row in outbox_events. The write repository's save is what calls the projector:
// src/main/java/com/muse/payments/payments/infrastructure/EventSourcedPaymentRepository.java:39-55
public Payment save(Payment payment) {
Objects.requireNonNull(payment, "payment must not be null");
List<DomainEvent> uncommitted = payment.peekDomainEvents();
if (uncommitted.isEmpty()) {
return payment;
}
StreamRef stream = new StreamRef(PaymentEventRegistryConfiguration.STREAM_TYPE, payment.getId());
long expectedVersion = payment.version() - uncommitted.size();
EventMetadata metadata = metadataProvider.current();
eventStore.append(stream, expectedVersion, uncommitted, metadata);
long streamVersion = expectedVersion;
for (DomainEvent event : uncommitted) {
streamVersion = Math.incrementExact(streamVersion);
paymentProjector.project(stream, event, streamVersion, metadata);
}
return payment;
}
And the projector refuses to run outside an existing transaction. Both public methods of PaymentProjector carry @Transactional(propagation = Propagation.MANDATORY) (PaymentProjector.java:100-109). Call the projector with no active transaction and Spring throws immediately. It is a cheap way to turn a consistency assumption into an explicit error, instead of letting a projection be written in a commit separate from the event that produced it.
This is what sets this CQRS apart from the two-database model: the payments projection is synchronous. When the HTTP response to POST /confirm reaches the client, the following GET /{id} already sees COMPLETED. There is no replication lag because there is no replication.
Free and paid products to turn ideas into a foundation you can actually ship.
13 products availableContinue exploring similar topics
A BIGSERIAL sequence hands out numbers in order, but transactions commit out of order. If your async projection trusts global_position, it can lose events without a single error.
A module boundary that only exists in a diagram does not exist. How the Payments Platform turns a forbidden dependency into a failing test, and when this design is the wrong call.
When the fraud provider goes down, the payment is held for review, never approved. How the Payments Platform fails closed, measures outbox and projection lag, and makes migrations and rebuilds verifiable.
A 47-point checklist to find bugs, security risks, and performance issues before launch.
Production-tested templates trusted by developers. Save weeks of setup on your next project.
The by-id query looks trivial, and it hides a security decision:
// src/main/java/com/muse/payments/payments/application/GetPaymentByIdQueryHandler.java:22-38
@Override
@Transactional(readOnly = true)
public PaymentResponse handle(GetPaymentByIdQuery query) {
Objects.requireNonNull(query, "query must not be null");
PaymentResponse response = paymentCachePort.getOrLoad(query.paymentId(), () -> {
Payment payment = paymentRepository.findById(query.paymentId())
.orElseThrow(() -> new EntityNotFoundException("Payment not found with id: " + query.paymentId()));
return PaymentResponse.from(payment);
});
if (!query.readAny() && !response.userId().equals(query.userId())) {
throw new EntityNotFoundException("Payment not found with id: " + query.paymentId());
}
return response;
}
Two things stand out.
First: when the payment exists but belongs to someone else, the response is identical to when it does not exist. EntityNotFoundException, which becomes 404. With a 403, an attacker holding a valid token could enumerate ids and learn which payments exist just from the difference between 403 and 404. The architecture documentation states the rule: "An ownership miss stays 404 so callers cannot tell whether another user's payment exists". 403 is reserved for a different case: a valid token without the role the route requires.
Second: the ownership check runs after the cache. The cached value is the payment, with no information about who may read it. ADR 0008 is explicit: "Do not treat a cache hit as authorization". A common production bug is to put authorization inside the cache loader. It works on the first access, and on the next access by another user the cache returns the object without going through the check.
readAny is true for ADMIN and FRAUD_REVIEWER on GET /{id}, decided by the controller at PaymentController.java:173. On command routes (confirm and cancel), even an ADMIN may only act on their own payments and gets 404 on anyone else's. The ArchUnit rule payments_application_should_not_depend_on_spring_security, mentioned in chapter 1, keeps this logic in the handler, readable, rather than spread across @PreAuthorize annotations.
The listing has limits that look arbitrary until you see why:
// src/main/java/com/muse/payments/payments/application/ListPaymentsQueryHandler.java:44-55
static PaymentSort validated(int page, int size, String sort) {
if (page < 0) {
throw new ValidationException("page must be greater than or equal to 0");
}
if (size < 1 || size > MAX_PAGE_SIZE) {
throw new ValidationException("size must be between 1 and 100");
}
if ((long) page * (long) size > MAX_OFFSET) {
throw new ValidationException("page is too large; page * size must be <= " + MAX_OFFSET);
}
return PaymentSorts.parse(sort);
}
MAX_PAGE_SIZE is 100 and MAX_OFFSET is 10,000. An invalid parameter becomes a 400 with RFC 7807 problem details, not a silent clamp to the nearest valid value. The cast to long before multiplying avoids int overflow with large page values.
The query uses offset pagination, backed by a composite index created in migration V3:
-- src/main/resources/db/migration/V3__payments.sql:17-18
CREATE INDEX idx_payments_user_created_at_id
ON payments (user_id, created_at DESC, id DESC);
The trailing id is the tiebreaker. The adapter sorts by createdAt and then by id in the same direction (PaymentJpaReadAdapter.java:59-66). Without it, two payments with the same created_at can swap places between requests, and one item shows up on two pages while another disappears.
Offset has a well-known problem: the database has to walk and discard every row before the requested page. On page 1 that does not matter. On page 500 with 20 items, PostgreSQL reads 10,000 index entries to return 20. The page * size <= 10000 ceiling cuts off the worst case. The right alternative at high volume is keyset pagination (WHERE (created_at, id) < (?, ?)), which costs the same per page and is not thrown off by concurrent inserts shifting items. The sample does not implement keyset. That is a scope decision I would record as explicit debt in a real system.
There is another detail senior candidates often forget in interviews: findByUserId and countByUserId are two separate SELECTs. Inside a readOnly transaction at PostgreSQL's default isolation level (READ COMMITTED), each statement sees what was committed when that statement started. A payment created between the two queries can make the total disagree with the page. For a user listing their own payments, that is acceptable. For a financial report, it would not be.
GET /{id} is the hot read and uses cache-aside on Redis, with key payment:cache:{id} and a 10-minute TTL. The delicate part is invalidation. Every handler that changes a payment's state calls evictAfterCommit: confirmation, cancellation, review, provider intent recording and webhook settlement. The implementation:
// src/main/java/com/muse/payments/payments/infrastructure/cache/PaymentCacheService.java:111-122
public void evictAfterCommit(UUID paymentId) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
evict(paymentId);
}
});
} else {
evict(paymentId);
}
}
Evicting before commit opens a bad window: the cache entry is deleted, another request reads the database before the commit, gets the old state and puts it back. If the transaction then rolls back, the eviction was pointless. If it commits, the cache may be serving the previous state. Registering eviction as afterCommit guarantees it only happens once the new state is visible in the database.
ADR 0008 rejects write-through because it couples the payment transaction to Redis: "A Redis failure would fail the payment write". And it accepts the side effects of the chosen design with numbers:
get catches the exception, increments payments.cache.errors and the read falls through to PostgreSQL.ConcurrentHashMap of per-key locks, local to the instance. With N replicas, N simultaneous loads of the same payment can still happen.One effect the ADR does not discuss, and that is worth knowing, is the classic cache-aside race: a read that started before the commit loads the old state from the database, the command commits and evicts, and only then does the read write the old value into the cache. The local lock does not prevent it, because reads and writes take different paths. The 10-minute TTL is what bounds the damage. For a payment status read by its owner, that window is acceptable. For a balance used in a credit decision, I would not use cache-aside without versioning the cached value.
Not every read model in this project is synchronous. A payment's history, served by GET /api/v1/payments/{id}/history, comes from the payment_history table, populated by an asynchronous projector that reads the event store with a durable checkpoint.
GetPaymentHistoryQueryHandler does two reads: first it confirms in the synchronous read model that the payment exists and belongs to the user, then it reads the history. The consequence: right after a POST /confirm, GET /{id} already shows COMPLETED, but GET /{id}/history may not yet include the confirmation event. That endpoint has no read-your-writes guarantee.
The asymmetry is deliberate. ADR 0016 considers and rejects making every projection asynchronous because it "breaks read-your-writes and the uniqueness/race backstops for payments and identity". The rule the project follows is sound and I would reuse it elsewhere: the read model a client queries right after writing is synchronous. The audit and timeline read model may lag (the async runner polls every 250 ms by default, and a long transaction increases the lag), and that lag is measured by the projection.lag metric, covered in chapter 5.
Making the asynchronous projection work without losing events is much harder than it looks, and it is the subject of chapter 3.
GET /under-review filters by status = 'UNDER_REVIEW', and the existing index starts with user_id, so it does not serve that filter. docs/data.md itself records that the held-payment list has no status-specific index. With few held payments, it does not matter. With millions of rows in payments, it is a scan.identity module only has commands. There are no query types there, so the pattern is complete only in payments.PaymentResponse is both the query DTO and the HTTP body. Changing a projection field can change the API. There is no response payload versioning beyond the /api/v1 prefix.I would split reads and writes like this when the two sides genuinely need different things: invariants and concurrency on one side, indexing and pagination on the other. When that is not the case, CQRS is cost:
Propagation.MANDATORY helps, but it does not catch a projector that ignores an event type.findById with a cache is enough. You do not need two ports."Is this CQRS or event sourcing?" trips up a lot of people, because the two usually appear together. The short answer: they are independent. This project had CQRS without event sourcing (ADR 0004) and later had both (ADR 0016). CQRS separates the model that validates commands from the model that serves queries. Event sourcing stores facts as the source of truth instead of current state. You can have one without the other, and each choice has its own reasons.
The write side in this chapter depends on an event store built on PostgreSQL. In chapter 3 I open it up: the immutable table, optimistic concurrency per stream, and the subtle bug that appears when an asynchronous projection trusts the order of the database sequence.
If you are evaluating CQRS for your system and want to check whether the problem calls for two models or just better indexes, that is a conversation I have in architecture reviews at LEMON.DEV.
java-clean-arch-sample repository, commit 5277f6c (checked on November 21, 2026).TransactionSynchronization.