CQRS Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CQRS Pattern runs in O(1) time and O(n) space, in Java as in every other language.
- ✓Modern Java supports this directly. Sealed interfaces arrived in Java 17 and record patterns with pattern matching for switch in Java 21, which together give exhaustive command dispatch checked by the compiler.
- ✓Declare a sealed interface permitting exactly the command records, and dispatch with a switch expression over type patterns.
- ✓The Java trap: Adding a default branch to a switch over a sealed type turns off the exhaustiveness check, in the same way a wildcard arm does in Rust, and the compiler does not warn you that the guarantee has been traded away.
- ✓A pattern switch over types compiles to an invokedynamic-based type switch rather than a linear chain of instanceof checks, so it scales with the number of cases far better than the older idiom it replaces.
What CQRS Pattern actually is
CQRS Pattern in Java: what you actually reach for
Java implementation
import java.util.List;
import java.util.UUID;
public final class Orders {
// Sealed (Java 17): the permitted set is closed and known to the compiler.
public sealed interface Command
permits CreateOrder, CancelOrder, ShipOrder {}
public record CreateOrder(UUID orderId, List<String> items) implements Command {}
public record CancelOrder(UUID orderId, String reason) implements Command {}
public record ShipOrder(UUID orderId, String carrier) implements Command {}
public sealed interface Event permits OrderCreated, OrderCancelled, OrderShipped {}
public record OrderCreated(UUID orderId, List<String> items) implements Event {}
public record OrderCancelled(UUID orderId, String reason) implements Event {}
public record OrderShipped(UUID orderId, String carrier) implements Event {}
/**
* Pattern matching for switch (Java 21) over a sealed type. There is
* deliberately NO default branch: with every permitted subtype covered
* the compiler accepts this, and adding a fourth Command makes it a
* COMPILE ERROR, which is the entire point.
*
* Adding "default -> ..." silently disables that check, exactly as a
* wildcard arm does in Rust, and the compiler does not warn you that
* the guarantee is gone. It feels defensive; it is the opposite.
*/
public static Event handle(Command command) {
return switch (command) {
case CreateOrder(UUID id, List<String> items) -> new OrderCreated(id, items);
case CancelOrder(UUID id, String reason) -> new OrderCancelled(id, reason);
case ShipOrder(UUID id, String carrier) -> new OrderShipped(id, carrier);
};
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for CQRS Pattern?
Modern Java supports this directly. Sealed interfaces arrived in Java 17 and record patterns with pattern matching for switch in Java 21, which together give exhaustive command dispatch checked by the compiler.
What is the most common Java mistake when implementing CQRS Pattern?
Adding a default branch to a switch over a sealed type turns off the exhaustiveness check, in the same way a wildcard arm does in Rust, and the compiler does not warn you that the guarantee has been traded away. Because a default branch feels defensive and responsible, it gets added by habit, and the codebase silently reverts to run-time dispatch on a language feature specifically designed to prevent that. Omit it deliberately. It is worth noting how recent all of this is: before Java 21 the same code was a chain of instanceof checks with no checking at all, so a lot of existing Java CQRS code predates the feature and does not use it.
How does CQRS Pattern actually perform in Java?
A pattern switch over types compiles to an invokedynamic-based type switch rather than a linear chain of instanceof checks, so it scales with the number of cases far better than the older idiom it replaces. Records give value-based equality and hashCode for free, which is what you want for a command you may deduplicate. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.