Integration / Distributed Systems: CQRS: When to Use It and When Not to Interview questions
Last updated
1. What is CQRS?
Command Query Responsibility Segregation (CQRS) is an architectural pattern that splits the model used to change state (commands) from the model used to read state (queries).
Instead of one object model and one service layer doing both jobs, the write side is built to enforce business rules, while the read side is built to return data in exactly the shape a screen or API needs. Greg Young popularised the term, building on Bertrand Meyer's CQS principle.
The two sides can share one database or use separate stores kept in sync through events. CQRS is normally applied to a single bounded context where read and write needs clearly diverge, not to a whole system.
Take quiz
the frontend code from the backend code
the primary database from its nightly backups
the model that changes state from the model that reads state
to specific areas where read and write needs diverge
uniformly to every service in the company
only in systems that already use a message broker
2. Define Command Query Separation (CQS)?
CQS is a design principle from Bertrand Meyer: a method should either be a command that changes state and returns nothing, or a query that returns data and has no side effects. It should never do both.
// Query: returns data, no side effects BigDecimal getBalance(AccountId id); // Command: changes state, returns nothing void deposit(AccountId id, BigDecimal amount);
A classic violation is stack.pop(), which removes the top item and also returns it. CQS works at the method level inside one object. CQRS takes the same idea up to the architecture level.
In everyday code, CQS shows up as a habit: getters don't mutate, and mutators don't hand back computed state. It makes behaviour predictable, since calling a query twice is always safe. Fluent builders and Optional-style APIs are the usual deliberate exceptions.
Take quiz
return data without changing any state
change state and return the updated value
return nothing and only trigger side effects
pop(), which removes and returns the top element
peek(), which returns the top element
size(), which returns the element count
push(item), which adds an item and returns nothing
3. What is a command in CQRS?
A command is a request to change state, named as an intent in the imperative: PlaceOrder, CancelSubscription, ApproveRefund.
It targets one aggregate, goes to exactly one handler, and can be rejected if validation or a business rule fails. It carries only the data needed to do the work and does not return domain data, at most an acknowledgement or a new ID.
A command hasn't happened yet. That's what separates it from an event, which records something that already did.
Take quiz
ApproveRefund
RefundApproved
RefundSummaryList
GetRefund
broadcast to many unrelated handlers
treated as an immutable historical fact
rejected before anything changes
4. What is a query in CQRS?
A query asks for data and must never change state. It returns a DTO shaped for the caller, such as GetOrderSummary or ListOverdueInvoices.
Because queries carry no business rules, they usually skip the domain model entirely and read straight from a table, view, or search index with plain SQL or a document lookup. No aggregates get loaded.
Being side-effect free also makes queries safe to cache and retry.
A useful rule: if you can delete the query handler's database write permissions and everything still works, you built it right. Read-only credentials for the query side are a cheap way to enforce this.
Take quiz
they always run against the write database
they are executed inside aggregates
they do not change any state
a view or store shaped for that query
the event bus
the command handler's in-memory aggregate
5. What is the write model in CQRS?
The write model (command side) captures behaviour: aggregates, invariants, and transactions. Its job is correctness, not convenient querying.
Typical access is simple: load an aggregate by ID, apply the command, save. Storage can be normalised tables or an event stream. Since nobody runs reports against it, you can drop getters and joins that exist only for the UI.
Keep the consistency boundary small. One command, one aggregate, one transaction.
Because the model is private to the command side, you can reshape it freely. Renaming a field or splitting an aggregate won't break any screen, as long as the events or contracts feeding the read side stay compatible.
Take quiz
enforcing business rules and invariants
serving dashboard queries quickly
full-text search
join five tables to build a report
load an aggregate by ID, apply the command, save
scan the whole store for matching rows
6. What is the read model in CQRS?
A read model is a denormalised copy of data shaped for a specific query, often one per screen or API use case. An order_summary table that already contains the customer name and item count is a typical example.
It can live in whatever store suits the query: a SQL table, a document database, Elasticsearch, or Redis. Because the write side stays the source of truth, a read model is disposable and can be rebuilt from scratch.
It holds no business rules. It only holds data ready to read.
Take quiz
it is always stored in memory only
the write side remains the source of truth
it contains the business rules
a fully normalised copy of the write schema
restricted to a single table per aggregate
denormalised and shaped for specific queries
7. What is a projection in CQRS?
A projection is the code that consumes events (or change records) from the write side and updates a read model.
OrderPlacedinserts a row intoorder_summaryItemAddedincrementsitem_countOrderShippedsetsstatus = 'SHIPPED'
Think of it as a function from the event stream to a view of state. Since the same events always produce the same view, a projection can be rebuilt by replaying history.
Projections are also where cross-aggregate data gets combined. A single projection can listen to CustomerRenamed and OrderPlaced and keep a combined row current, which is something no single aggregate could do on its own.
Take quiz
raw HTTP requests from clients
queries from the read API
events or change records from the write side
produce the same read model state
produce a random but valid state
modify the original events
8. What is a command handler?
A command handler receives one specific command type and carries out the use case. There is exactly one handler per command.
- Validate the command shape and the caller's permissions
- Load the target aggregate
- Call a domain method on it
- Persist the result (state or new events) in one transaction
- Return an acknowledgement or ID
Keep it thin. Business rules belong in the aggregate, so the handler only orchestrates.
A common handler responsibility is concurrency control. It checks the aggregate version on save, and on a conflict either retries the command or returns an error so the caller can decide.
Take quiz
exactly one
one per subscribed projection
as many as there are read models
in the query handler
inside the aggregate, not the handler
in the read model table triggers
9. What are the main components of a CQRS architecture?
A typical setup has seven moving parts:
- Command API or bus that accepts intent
- Command handlers that run use cases
- Write model with aggregates and its store
- Change propagation via events, an outbox, or CDC
- Projections that transform changes
- Read store holding denormalised views
- Query API that reads from those views
flowchart LR C[Client] -->|command| H["Command handler"] H --> W[(Write store)] W -->|events| P[Projection] P --> R[(Read store)] C -->|query| Q["Query API"] Q --> R
In small systems several of these collapse into one process: the 'bus' is a method call, and the 'change propagation' is a database trigger or in-process publisher. The roles stay the same even when the infrastructure is minimal, so name them clearly in code from day one.
Take quiz
the command bus
the projection
the aggregate root
the write store's aggregates
the command handler
the read store
10. What is the difference between CQS and CQRS?
| CQS | CQRS |
| Principle for methods | Pattern for architecture |
| Same object and model handle both kinds of methods | Separate models for writes and reads |
| One database, no extra infrastructure | Often separate stores plus propagation |
| No consistency implications | Usually introduces eventual consistency |
| Coined by Bertrand Meyer | Popularised by Greg Young |
CQS is cheap and almost always worth following. CQRS has real operational cost, so adopt it only when separate models pay for themselves.
In short: CQS is a coding convention you can follow without anyone noticing, while CQRS is a structural decision that changes your deployment, data flow, and testing. Teams often adopt CQS first and find it's enough.
Take quiz
CQS applied to a single class
any method named get...
CQRS with separate read stores
individual methods
deployment topology
database replication
11. What is eventual consistency in a CQRS system?
It means the read model can lag the write model for a short time. A write is committed first, and the projection catches up milliseconds, seconds, or occasionally minutes later.
Example: a user submits an order and is redirected to My Orders. If the projection hasn't processed OrderPlaced yet, the new order is missing from that list.
Nothing is lost. With no further writes, the read side converges to the write side's state. The design challenge is deciding which screens can tolerate the delay and handling the ones that can't.
Take quiz
the projection has not caught up yet
the command was silently discarded
the aggregate lost its state
drift further out of sync
converge to the write side's state
be wiped automatically
12. What is the relationship between CQRS and Event Sourcing?
They are independent patterns that are often combined. Event Sourcing stores state as an append-only sequence of events. CQRS splits write and read models.
They pair naturally because an event log is hard to query directly, so you need projections to build usable read models. In the other direction, CQRS gets a ready-made change feed from the event store.
But CQRS works fine on ordinary tables, and Event Sourcing can exist without separate read stores, though that's rare. Adopting one doesn't oblige you to adopt the other.
Take quiz
events cannot be stored durably
an event log is inefficient to query directly
aggregates cannot be loaded
no, they are the same pattern
only if no read model exists
yes, with ordinary tables on the write side
13. What are the benefits of CQRS?
- Independent scaling: scale a heavy read side without touching writes
- Query-shaped data: no joins or ORM gymnastics for dashboards
- Simpler write model: aggregates carry behaviour only, no reporting concerns
- Technology fit: relational for writes, Elasticsearch or Redis for reads
- Cleaner security: read and write permissions are granted separately
- Collaboration-friendly: commands capture intent, which helps in contested domains
These benefits only count when the system actually has the pain. Without it, they are theoretical and the cost is real.
Take quiz
eliminating the need for validation
guaranteeing strong consistency everywhere
scaling reads independently of writes
Elasticsearch for search queries
a store that must match the write schema exactly
no store at all
14. What are the drawbacks of CQRS?
- More moving parts: handlers, projections, brokers, extra stores
- Eventual consistency: UI and APIs must tolerate stale reads
- Duplicated data: the same facts stored in several shapes
- Operational load: projection lag, replays, and failed events need monitoring
- Learning curve: teams must think in commands, events, and idempotency
- Harder debugging: a bug can sit across an asynchronous boundary
For a plain CRUD domain, these costs usually outweigh the benefits.
The hidden cost is often cognitive: a developer fixing a simple bug now has to ask whether the fault is in the command, the event, the projection, or the query. Good tracing and correlation IDs reduce that, but they have to be built.
Take quiz
monitoring and repairing projection lag
maintaining a single schema only
avoiding all asynchronous messaging
it breaks the command pattern
multiple copies must be kept in sync
it prevents caching
15. List situations where CQRS is a good fit?
- Read traffic far exceeds write traffic, or the two have very different scaling needs
- Screens need data joined from many aggregates, and the joins hurt performance
- The write side has rich, rule-heavy behaviour that is cluttered by query concerns
- Reads need a different store, such as full-text search or a graph
- Collaborative domains with many users editing the same data, where intent matters
- A full audit trail or temporal queries are required
Look for measured pain, such as slow joins or a bloated model, rather than hypothetical future scale.
Take quiz
the team wants to try a new pattern
complex read joins slowing down a rule-heavy write model
the database has only three tables
avoiding any projection code
keeping both sides perfectly synchronous
needing full-text search that the write store handles poorly
16. List situations where CQRS is a poor fit?
- Simple CRUD apps where forms map directly to tables
- Small teams without capacity to run projections and monitor lag
- Domains needing strict read-your-writes consistency on every screen
- Low-traffic internal tools with no scaling pressure
- Systems with no real business rules on writes
- Early prototypes where the domain is still being discovered
If a well-indexed table and an ORM already do the job, adding CQRS only adds more places for bugs to live.
A quick check is the 'one table' test. If most of your screens read the same table that most of your commands write, a separate read model is only a copy of data you already have, plus the lag.
Take quiz
a rule-heavy collaborative editor
a system with separate read workloads
a simple CRUD admin screen over one table
CQRS with separate stores is risky
CQRS is mandatory
lag no longer matters
17. How do you apply CQRS with separate read and write databases?
- Define commands and handlers that write to the write database.
- Make every state change emit an event or change record, ideally via a transactional outbox.
- Publish those changes to a broker or change feed.
- Build projections that consume them and update the read database.
- Point query endpoints at the read database only.
- Add lag monitoring and a way to rebuild projections.
Never let the query side write back to the write database, and never let command handlers read from the read store to make decisions. Doing either quietly re-couples the two models.
Take quiz
the read database only
the write database aggregates
the message broker directly
the standard practice
an anti-pattern that re-couples the models
required for idempotency
18. Why do we separate read and write models?
Because reads and writes want opposite things from a model. Writes need small, consistent boundaries and validated invariants. Reads need wide, denormalised, pre-joined data returned fast.
In one shared model, you end up bending entities to serve screens: extra getters, lazy-loaded relations, projections bolted on, and eager-fetch tuning that breaks write-side performance. Every UI change then risks the domain logic.
Splitting them lets each side evolve on its own. The write model stays focused on rules. Read models can be added, reshaped, or dropped per use case without touching business logic.
A practical example: an e-commerce order page needs customer, items, shipping status, and payment info in one response. The write model only needs the order aggregate to accept a cancellation. Making one model serve both usually means over-fetching on writes or under-fetching on reads.
Take quiz
always run on different servers
need opposite shapes and optimisations
use different programming languages
the database refuses concurrent access
commands cannot be validated
UI-driven changes leak into domain entities
19. When should you choose CQRS over plain CRUD?
Choose it when you can point at a specific, measured problem that separate models would fix.
- Query joins across many tables are slow and indexing can't fix them
- The domain model is distorted by reporting and display needs
- Read and write loads differ enough to need separate scaling or storage
- Business rules on the write path are complex and need a clean home
- Users edit the same data concurrently and capturing intent matters
If none of these hurt today, stay with CRUD. You can introduce CQRS later for one slice, since commands and queries are easy to split out of an existing service layer.
Take quiz
a single form that saves one table row
a plan to use more microservices
slow multi-table joins and a model bent by reporting needs
stay with CRUD and revisit later
adopt CQRS everywhere now
add Event Sourcing first
20. When would you avoid CQRS?
Avoid it when its cost has nothing to buy. That's most CRUD-style applications.
- Forms map almost one-to-one to tables and the model is simple
- The team is small and has no appetite for operating projections and brokers
- Users must see their own writes instantly everywhere, and you can't engineer around it
- Traffic is low and a single database handles reads and writes comfortably
- The domain is still unclear and boundaries will keep moving
A common mistake is applying CQRS to the whole system because one module needed it. Scope it to that bounded context only.
Another warning sign is a team that adopts CQRS to look modern. If you can't name the query that's too slow or the rule that's hard to model, hold off. The pattern is easier to add later than to remove.
Take quiz
applying it to the whole system because one module needed it
applying it to a single bounded context
using it after measuring a read bottleneck
a team with a large read-heavy search feature
a small team that cannot operate projections and brokers
a team with complex write-side rules
21. Explain the execution flow of a command in CQRS?
sequenceDiagram participant C as Client participant A as Command API participant H as Command Handler participant G as Aggregate participant S as Write Store participant B as Broker C->>A: PlaceOrder A->>H: dispatch H->>S: load Order H->>G: place(items) G-->>H: OrderPlaced event H->>S: save state + outbox row (one transaction) H-->>C: 202 Accepted + orderId S->>B: relay outbox event
The API validates shape and authorisation, then dispatches to the handler. The handler loads the aggregate, which checks business rules and produces a result or event. State and outbox record are committed together.
The client gets an acknowledgement as soon as the write commits. Read models are updated afterwards, asynchronously, from the published event.
Failure handling matters here. If the aggregate rejects the command, nothing is stored or published, and the caller receives an error. If the handler crashes after the commit, the outbox row guarantees that the event will still be relayed. Version checks on save catch two commands racing for the same aggregate, so one of them fails or retries instead of silently overwriting the other.
Take quiz
after every read model is updated
after the write commits, before projections finish
before the command is validated
the broker
the query API
the aggregate
22. How does a query flow through a CQRS system?
The query path is deliberately short. The request goes to a query handler, which reads from the read store and maps the result to a response DTO. No aggregates, no domain services, no write-side database.
flowchart LR C[Client] --> Q["Query handler"] Q --> R[(Read store: order_summary)] R --> Q Q --> D["DTO response"] D --> C
Most query handlers are a single SQL statement or key lookup. Caching, pagination, and filtering are applied here without worrying about domain invariants. If the data isn't there yet because a projection is behind, the query simply returns what exists.
Because this path is so simple, it's also the easiest to tune. You can add a cache keyed by query parameters, use read-only database users, or serve it from a CDN for public data. Authorisation still applies, but as filtering on the result, not as domain logic.
Take quiz
reading from a read store
returning DTOs
loading aggregates from the write model
return the data that currently exists
block until the projection finishes
read from the command side instead
23. How does a projection get built from events?
A projection subscribes to an event stream, handles each event type, and applies it to the read model. It also stores a checkpoint so it knows where to resume.
@EventHandler void on(OrderPlaced e) { jdbc.update("INSERT INTO order_summary(id, customer, total, status) VALUES (?,?,?,'PLACED') ON CONFLICT (id) DO NOTHING", e.orderId(), e.customerName(), e.total()); } @EventHandler void on(OrderShipped e) { jdbc.update("UPDATE order_summary SET status='SHIPPED' WHERE id=?", e.orderId()); }
The insert uses ON CONFLICT DO NOTHING so a redelivered event is harmless. Each handler should write the read-model change and the checkpoint in the same transaction where possible.
Projections process events one stream position at a time. For throughput, many implementations batch several events per transaction and checkpoint once per batch. The batch size is a trade-off: larger batches are faster but replay more events after a crash. Keep the handler free of network calls to other services, since a slow call there stalls the whole stream.
Take quiz
to resume from the last processed event
to validate commands
to lock the aggregate
a distributed transaction with the broker
ON CONFLICT DO NOTHING on the insert
deleting the event after handling
24. Why is CQRS more than adding read replicas?
A read replica is the same schema copied to another server. It scales read capacity, but queries still hit the same normalised tables with the same joins.
CQRS changes the shape of the data on the read side: pre-joined, denormalised, possibly in a different engine. It also separates the code, so command logic and query logic no longer share entities.
| Read replica | CQRS read model |
| Same schema as primary | Schema designed per query |
| Replication is physical or logical, automatic | Projection logic you write and own |
| Scales read throughput | Scales throughput and simplifies queries |
| Domain model unchanged | Write model freed from reporting concerns |
They aren't exclusive. A CQRS read store can itself have replicas.
Take quiz
is always byte-identical to the primary
has its own query-shaped schema
cannot be scaled
no, they are mutually exclusive
only for write stores
yes, the two approaches combine
25. Why does CQRS add so much complexity?
Because one problem becomes four. A single transactional write turns into write, publish, project, and read, each with its own failure modes.
- Asynchrony: stale reads, ordering, and duplicate delivery must be handled
- Two schemas: every domain change may need a read-model change too
- New infrastructure: brokers, outbox relays, checkpoint stores
- New skills: idempotency, replays, backpressure, eventual-consistency UX
- Operations: lag dashboards, dead-letter queues, rebuild runbooks
None of this is unsolvable, but all of it is work that a plain CRUD service never needed. That's why the pattern should be justified by a real problem.
The complexity is mostly a one-time structural cost plus an ongoing operational one. The structural part (handlers, events, projections) is learned once. The operational part (lag, replays, dead letters) never goes away, so budget for it before adopting.
Take quiz
it can no longer be validated
it must be signed by two aggregates
it must also be published and projected asynchronously
designing idempotent consumers
writing stored procedures only
avoiding all queues
26. How does CQRS handle read-after-write consistency?
Out of the box, it doesn't. The read model lags, so a user may not see their own change immediately. You have to add it deliberately.
- Return the result in the command response so the UI can show it without querying.
- Version tokens: return the new version, and let the query wait or retry until the read model reaches it.
- Optimistic UI: show the change locally and reconcile later.
- Read from the write side for that one record, only when truly needed.
- Synchronous projection for a few critical views, trading latency for consistency.
Pick per screen. Most views don't need it, and the few that do get a targeted fix.
Take quiz
the query can wait until the read model reaches that version
it disables the projection
it forces strong consistency on the whole system
every query in the system
only the screens that need them
the write database only
27. How can you hide eventual consistency from users?
Design the user experience so a short lag is invisible or expected.
- Update the UI from the command response instead of re-querying right away
- Use optimistic updates and a subtle pending state
- Show a success message that points to the action, not to the list
- Poll or push (WebSocket, SSE) until the view reflects the change
- Avoid redirecting straight to a list that may not yet contain the new item
Often the simplest fix is a redirect to a detail page for the item just created, with data taken from the command's response.
Whichever technique you pick, say it in the UI wording too. 'Your order is being processed' is honest and accurate, while 'Your order is shown below' invites confusion when the list hasn't caught up.
Take quiz
redirect to the list and hope it is updated
redirect to a detail view populated from the command response
block the user for a fixed ten seconds
making projections synchronous
removing the need for events
notifying the client when the read model changes
28. What is the difference between single-database and multi-database CQRS?
| Aspect | Single database | Separate databases |
| Consistency | Can be immediate (same transaction or views) | Eventual |
| Complexity | Low to moderate | High: broker, projections, monitoring |
| Read model | Views, tables, or materialised views | Any engine, any shape |
| Scaling | Shared resource limits | Truly independent |
| Failure modes | Few | Lag, duplicates, ordering, rebuilds |
| Typical start point | Good first step | Adopt when needed |
Many teams start with separate command and query code on one database, which gives most of the modelling benefit. Splitting the database comes later, only if scaling or technology needs demand it.
The decision isn't permanent. A single-database design with a clean boundary between command and query code can later point its query side at a new store, with little change to callers.
Take quiz
CQRS over separate databases with a broker
any setup with Elasticsearch
CQRS over a single database
separate code paths on one database
a different database per query
adding Event Sourcing and three brokers
29. What happens when a projection falls behind?
Queries return stale data. The read model keeps working, but it reflects an older state of the system. Users see missing records, old statuses, or wrong counts.
Common causes are slow handlers, a traffic spike, a downstream database under load, or a failing event that keeps being retried.
- Measure it first: compare the latest event position with the projection checkpoint
- Scale out consumers if the stream is partitioned
- Batch writes to the read store
- Fix or quarantine the event that is blocking progress
- Surface a 'data may be delayed' hint for critical screens
Lag is expected to be small and brief. A growing lag is an incident.
Take quiz
queries returning stale data
commands being rejected
aggregates losing events
delete the read model
compare the latest event position to the projection checkpoint
restart the write database
30. How do you rebuild a projection?
Replay the event history (or a snapshot of the write data) through the projection into a new read model, then switch traffic over.
flowchart TD
A["Deploy new projection version"] --> B["Create new read table or index"]
B --> C["Replay events from position 0"]
C --> D{Caught up with live stream?}
D -- No --> C
D -- Yes --> E["Switch query API to new read model"]
E --> F["Drop old read model"]
Build the new one beside the old one, so users keep reading from the old view until the new one is ready. Without Event Sourcing, you rebuild by reading current write-side rows and emitting synthetic events, though you lose history.
Plan for the time it takes. Replaying millions of events can take hours, so test the replay speed on production-sized data in advance. Techniques like parallel replay per partition, bulk inserts, and temporarily disabling secondary indexes during backfill help considerably.
Take quiz
to avoid ever replaying events
users keep reading the old view until the new one is ready
so both can accept commands
an immutable event log that always exists
the old read model as the only source
current write-side data to generate synthetic events
31. Why should projections be idempotent?
Because most brokers deliver at least once. A crash after updating the read model but before saving the checkpoint means the same event arrives again. A non-idempotent handler would count it twice.
-- Not idempotent: replay inflates the count UPDATE product_stats SET sold = sold + 1 WHERE id = :id; -- Idempotent: track the last applied version UPDATE product_stats SET sold = :newSold, last_event = :eventSeq WHERE id = :id AND last_event < :eventSeq;
Other techniques include storing processed event IDs, using upserts, and writing state rather than deltas.
Idempotency is easiest when handlers write state, such as 'set status to SHIPPED', rather than deltas, such as 'add one'. If you must apply deltas, deduplicate using the event ID or sequence number. Test it by deliberately delivering every event twice in your projection tests, and also out of order where your design allows for it.
Take quiz
events are always published twice by design
aggregates emit each event twice
brokers usually guarantee at-least-once delivery
updating only when the stored event sequence is lower than the incoming one
incrementing a counter on every delivery
inserting a row without any key check
32. How do you reliably publish changes from the write side?
Use the transactional outbox. Write the state change and an outbox row in the same local transaction. A separate relay then reads the outbox and publishes to the broker.
BEGIN; UPDATE orders SET status = 'PLACED' WHERE id = 42; INSERT INTO outbox(id, aggregate_id, type, payload) VALUES (gen_random_uuid(), 42, 'OrderPlaced', '{...}'); COMMIT; -- relay: SELECT unsent rows -> publish -> mark sent
This avoids the dual-write problem, where the database commit succeeds but the broker publish fails (or vice versa). The relay can duplicate a message, so consumers must be idempotent. Alternatives are CDC tools reading the transaction log, or an event store acting as its own source of events.
Whichever route you choose, the relay should publish in the order rows were written, at least per aggregate, and mark rows as sent only after the broker acknowledges them. Clean up old outbox rows on a schedule so the table doesn't grow without limit.
Take quiz
state change and event record commit together
exactly-once delivery to consumers
synchronous projection updates
the outbox deletes messages early
the relay may publish a message more than once
events are published before the commit
33. How do you handle event ordering in projections?
Ordering matters per aggregate: OrderShipped must not be applied before OrderPlaced. Global ordering is rarely needed and expensive.
- Partition by aggregate ID so one aggregate's events go to one consumer in order
- Carry a version number on each event and apply only the next expected one
- Buffer or retry events that arrive early, rather than dropping them
- Ignore stale events whose version is already applied
Across different aggregates, design read models so the order doesn't matter, for example by using upserts that tolerate a missing parent row.
Kafka-style brokers preserve order within a partition, so the partition key choice is the real design decision. Using the aggregate ID gives per-aggregate ordering and still allows parallelism across aggregates.
Take quiz
it guarantees global ordering across all aggregates
events of one aggregate stay in order on one consumer
it removes duplicates automatically
apply it again
delete the read model
ignore it as stale
34. How do you evolve a read model schema without downtime?
- Create a new read model version (table, index, or collection) next to the current one.
- Deploy the new projection code writing to the new version while the old one keeps running.
- Backfill by replaying history into the new model until it catches up.
- Switch the query API to the new version, ideally behind a feature flag.
- Keep the old model briefly for rollback, then remove it.
This is the main practical advantage of rebuildable read models: schema changes become deployments, not migrations. The write side is untouched. The cost is double the storage and write load during the switch.
Take quiz
altering the live table in place during peak hours
changing the write schema first
building a new version beside the old one and switching over
temporary extra storage and write load
loss of all historical events
the write side must be offline
35. Why does CQRS pair well with Domain-Driven Design?
DDD gives the write side a clear structure: aggregates enforce invariants inside a transaction boundary, and commands map naturally to use cases on those aggregates.
CQRS removes the pressure to make those aggregates answer every query. Without it, teams add fields and relations to aggregates purely for display, which weakens the model. With it, reads go to purpose-built views and the aggregate stays small and behavioural.
Domain events raised by aggregates also become the natural feed for projections. Bounded contexts decide where to apply CQRS: usually only the contexts with rich behaviour.
A concrete case: in a billing context, an Invoice aggregate enforces that a paid invoice can't be edited. The 'invoices overdue by customer' screen reads from a projection and never touches that aggregate. Neither side has to compromise for the other.
Take quiz
serving display and reporting queries
raising any events
enforcing invariants
the command validation layer
projections that update read models
the authentication service
36. What is the difference between a command and an event?
| Command | Event |
| Request to do something | Record that something happened |
Imperative: PlaceOrder |
Past tense: OrderPlaced |
| One handler | Zero, one, or many subscribers |
| Can be rejected | Cannot be rejected, it is a fact |
| Sent by a caller who expects an outcome | Published by the aggregate; publisher doesn't care who listens |
| Targets one aggregate | Emitted after the aggregate changed |
A useful test: if the name can be answered with 'no', it is a command. If it's something nobody can deny afterwards, it's an event.
In code, this shows up in naming and in routing: commands are sent to a command bus with one registered handler, while events are published to a topic that any number of projections or services can subscribe to. Mixing the two, such as publishing a 'command' to many listeners, leads to duplicate side effects.
Take quiz
an event
a command
both are always rejected
PayInvoice
GetInvoice
InvoicePaid
37. Should a command return data in CQRS?
Strictly, no. A command should return an acknowledgement or at most a generated identifier. Returning domain data blurs the line with queries and tempts callers to use commands as reads.
In practice, teams relax this a little for good reasons. Returning the new ID or the new version number is common, since the client needs it to follow up. Some also return a small result object so the UI can update without an extra query.
What to avoid is returning the full, queried state of the aggregate as a habit. If the client needs to read, it should issue a query, ideally with a version token to cope with lag.
Whatever your team chooses, make it a documented convention and apply it consistently, so developers don't have to guess whether a particular command returns something useful.
Take quiz
a full multi-table report
the entire read model
a new identifier or version number
blurs the line between commands and queries
is required by CQRS
guarantees consistency
38. How do you validate commands in CQRS?
Validation happens in layers, each with a different job:
- Shape validation at the API: required fields, formats, ranges.
- Authorisation check: may this caller issue this command on this resource?
- Business validation inside the aggregate: invariants such as 'cannot ship a cancelled order'.
- Uniqueness and cross-aggregate rules, using a unique constraint or a reservation step, since an aggregate can't see others.
Never validate against the read model for rules that must be strict. It may be stale, so two concurrent commands could both pass. Enforce strict rules where the write happens, inside the transaction.
A practical tip: return structured errors that distinguish 'invalid request' (400-style) from 'business rule violated' (409 or 422-style), since callers handle them differently. The first can be fixed by the client, while the second needs a different user decision.
Take quiz
it may be stale and allow conflicting commands
it is always faster than the write side
it cannot be queried
in the UI only
inside the aggregate
in the projection
39. How does CQRS let you scale reads and writes independently?
Because the two paths share neither code nor, optionally, storage. Each can be deployed, sized, and tuned on its own.
- Read side: add stateless query instances, replicate or shard the read store, add caches in front
- Write side: scale command handlers, partition aggregates by ID, tune the write store for transaction throughput
- Different engines: PostgreSQL for writes, Elasticsearch or Redis for reads
A system with 200 reads for every write can run a handful of write nodes and dozens of read nodes, instead of scaling both together. The projection is the link that must keep up, so its throughput needs capacity planning too.
Keep in mind that independent scaling isn't free. If the read side scales out massively, the projection may need partitioning or batching to keep up, and cache invalidation becomes a topic of its own.
Take quiz
adding more aggregates
adding query instances or read-store replicas without touching writes
slowing the projection on purpose
the UI theme
the command DTO
the projection
40. Which is better for a small admin app, CQRS or CRUD, and why?
CRUD, almost always. A small admin app typically has a handful of entities, forms that map to tables, low traffic, and few real business rules. Nothing about that profile creates the pain CQRS addresses.
CQRS would add a second model, a propagation mechanism, and eventual consistency to a system that has none of the problems it solves. Developers also pay the cost in debugging and onboarding.
A cheap middle ground is to keep CQS habits in code, with separate read and write methods, and use CRUD tooling. If a hot spot appears later, such as a slow report, build one read model for it then.
The exception is if the admin app is a thin front for a rule-heavy domain, for example one that approves loans with several overlapping policies. Then the domain complexity, not the app size, is what justifies a cleaner write model.
Take quiz
CQRS with Event Sourcing
CQRS with a different database for each screen
plain CRUD
follow CQS in code and add a read model only for a proven hot spot
adopt CQRS everywhere now to be safe
remove all validation
41. How does CQRS fit into a microservices architecture?
CQRS lives inside a service boundary, or across a pair of services that own the same domain. It does not mean every microservice needs it.
A common use is the query composition problem: a screen needs data owned by several services. Instead of joining over HTTP on every request, a read service subscribes to events from those services and keeps a local, joined view.
flowchart LR
O["Orders service"] -->|OrderPlaced| B{{Broker}}
C["Customers service"] -->|CustomerUpdated| B
B --> P["Projection in Reporting service"]
P --> V[(Order + customer view)]
U[Client] --> Q["Reporting query API"]
Q --> V
The trade-off is another copy of data and a dependency on event contracts, so those events need to be versioned carefully.
Avoid sharing a read database between services in the name of CQRS. That is just a shared database with a new label, and it breaks the independence that microservices are supposed to provide. Each service should own its projection and its store.
Take quiz
keeping a joined read view built from other services' events
merging all services into one database
replacing the broker with HTTP calls
shared database tables
stable, versioned event contracts between services
identical programming languages
42. How do you test a CQRS system?
Test each part at the level where it can fail.
- Aggregates: given-when-then tests. Given past events, when a command, then expect events or a rejection.
- Command handlers: verify orchestration with a fake store, or a real one in integration tests.
- Projections: feed a fixed event sequence and assert the resulting read-model rows. Also replay the same events twice to prove idempotency.
- End-to-end: issue a command, then poll the query until the expected state appears, with a timeout, to account for eventual consistency.
- Rebuild tests: replay history into an empty model and compare with the live one.
Avoid fixed sleeps in end-to-end tests. Poll with a timeout instead, or the suite will be both slow and flaky.
Take quiz
querying the read model only
given past events, when a command, then expected events
sleeping for five seconds
asserting immediately after the command
reading from the write database
polling the query with a timeout
43. How do you monitor projection lag?
Measure the gap between what the write side has produced and what each projection has processed.
- Position lag: latest event sequence minus the projection's checkpoint
- Time lag: now minus the timestamp of the last processed event
- Broker metrics: consumer group offset lag per partition
- Error counters: failures, retries, and dead-letter queue size
- Canary events: a synthetic command written regularly, with a check on when it appears in the read model
Alert on trend, not just threshold. A lag of two seconds that is stable is fine. A lag that grows every minute means the consumer can't keep up or is stuck.
Put the numbers on a dashboard next to the user-visible symptom, such as 'orders missing from list', so on-call engineers can connect cause and effect quickly. Document the lag threshold that triggers a page, and who owns each projection.
Take quiz
the number of commands per second
the size of the read database
now minus the timestamp of the last processed event
lag that keeps growing over time
a stable lag of two seconds
zero lag during idle periods
44. How do you handle queries that span multiple services?
There are three common approaches, with different cost and freshness.
| Approach | How it works | Trade-off |
| API composition | A gateway calls each service and joins in memory | Simple, but slow and fragile, and weak for big result sets |
| Replicated read model | A reporting service builds a joined view from events | Fast and independent, but adds eventual consistency and data copies |
| Search index | Events from all services feed Elasticsearch or similar | Great for filtering and text, needs index maintenance |
Use composition for small, occasional lookups. Use a replicated read model when the query is hot, large, or needs filtering and sorting across services.
Whichever you choose, treat the cross-service view as a derived copy. Owning services remain the source of truth, and the derived view must be rebuildable from their events.
Take quiz
API composition
a replicated read model
a search index fed by events
there is only one tiny lookup per day
the query is hot or large and needs filtering across services
services cannot publish events
45. How do you handle a poison event in a projection?
A poison event is one that a projection can never process successfully, for example a malformed payload or a bug in the handler. If you retry forever, everything behind it stalls.
- Retry a few times with backoff, since the failure may be transient.
- If it still fails, move the event to a dead-letter queue or error table with its metadata and stack trace.
- Let the projection continue, so the lag doesn't grow.
- Alert someone. A dead-lettered event means the read model is now missing data.
- Fix the bug or data, then reprocess the event, or rebuild the affected view.
For strictly ordered per-aggregate streams, skipping an event may leave that aggregate's view wrong. In that case, mark the aggregate as 'needs rebuild' and fix it before resuming it.
Take quiz
delete events permanently with no record
park events that repeatedly fail so the projection can move on
speed up the write database
ignore it because events don't matter
restart the command handler
alert, fix the cause, and reprocess or rebuild
46. When does CQRS without Event Sourcing make sense?
Most of the time. CQRS alone gets you separate models and read-optimised views, without the extra burden of an event-sourced write side.
- The write side is ordinary relational tables with an ORM or SQL
- State changes are published through a transactional outbox or CDC
- Read models are built from those change events
- You don't need a full history, temporal queries, or replay of business events
This setup keeps familiar tooling: standard backups, SQL for investigation, simple schema migrations. Rebuilding a projection is a bit harder, because you rebuild from current state or a CDC snapshot, not from a complete history. For many systems that's an acceptable trade.
It also fits teams adopting the pattern for the first time. They can learn commands, projections, and idempotency without simultaneously learning event versioning, snapshots, and upcasting, and can still add Event Sourcing later for a single aggregate if the need appears.
Take quiz
an append-only event log only
the read store
ordinary relational tables
rebuilding projections is harder because full history is missing
the write side can no longer validate commands
projections become impossible
47. When is adding Event Sourcing to CQRS a mistake?
When the system doesn't need what Event Sourcing gives, since it brings its own substantial complexity on top of CQRS.
- No need for history: nobody asks what the state was last March
- Simple domain: few state transitions, and current state is what matters
- Hard to change events: events are immutable, so schema changes need upcasting and versioning
- Privacy deletion: erasing personal data from an immutable log needs crypto-shredding or similar tricks
- Team inexperience: aggregate replay, snapshots, and stream design are easy to get wrong
- Ad hoc querying: debugging requires projections, since you can't just SELECT from the log
If audit needs alone drive the choice, an audit table or CDC log is often enough. Add Event Sourcing when the event history is itself a business asset.
Take quiz
the team wants a trendy architecture
a regulatory need for a full, replayable history
the business asks for point-in-time state
inability to store data durably
changing event schemas after events are stored
no way to publish events
48. How do you migrate a CRUD system to CQRS incrementally?
Don't rewrite. Carve out one hot spot at a time, a strangler-style approach.
flowchart TD
A["Pick one painful query"] --> B["Split command and query code paths"]
B --> C["Keep one database, add a query-specific view"]
C --> D["Emit change events via outbox or CDC"]
D --> E["Build projection into a separate read store"]
E --> F["Route that query to the new store"]
F --> G{More pain elsewhere?}
G -- Yes --> A
G -- No --> H["Stop here"]
Step one costs almost nothing: separate reads from writes in code (services, handlers) while still using one database. Step two adds a view or materialised view. Only if that isn't enough do you add events and a separate store.
Run old and new reads side by side for a while and compare results before cutting over.
Keep feature flags around each cut-over, and keep the old query path alive until the new one has run in production for a full business cycle, such as a month-end close. Watch discrepancies between the two results during that period, because they usually point at bugs in the projection and not in the data.
Take quiz
introduce Event Sourcing for all aggregates
separate command and query code paths on the same database
replace the database with several new ones
delete the old path immediately
disable monitoring
compare its results with the old path side by side
49. What are common CQRS anti-patterns?
- CQRS everywhere: applying it to every module, including trivial CRUD ones
- Commands reading the read model to make strict decisions, which relies on stale data
- Queries writing state or triggering side effects
- Shared entity classes used on both sides, which defeats the separation
- Ignoring idempotency: projections that double-count on redelivery
- No rebuild path: read models that can't be recreated from the source of truth
- Hiding lag: no monitoring, so staleness is found by angry users
- Chatty synchronous coupling between handlers that makes the pattern async in name only
- Events as remote procedure calls, with names like
DoSomethingEvent
Most of these come from copying the vocabulary without the discipline. If you can't state which problem the split solves, it's probably not needed yet.
Take quiz
a projection that is idempotent
a query handler that only reads
a command handler making strict decisions from the read model
it can be rebuilt from the source of truth
it holds the only copy of the data
it is edited manually in production
50. How do you decide whether CQRS is worth the cost?
Treat it like any architectural trade: name the problem, estimate the cost, try the cheaper option first.
flowchart TD A["Is there a measured read or write pain?"] -- No --> Z["Stay with CRUD"] A -- Yes --> B["Can indexes, caching, or a view fix it?"] B -- Yes --> Z B -- No --> C["Can the UI tolerate eventual consistency?"] C -- No --> Y["Use one DB with separate code paths"] C -- Yes --> D["Can the team run projections and monitor lag?"] D -- No --> Y D -- Yes --> X["Adopt CQRS for this bounded context"]
Be honest about consistency tolerance and operational maturity. These two kill more CQRS adoptions than technical limits do. If the answer to either is no, separate code paths on one database give most of the modelling benefit with little of the risk.
Revisit the decision when load, team, or domain changes. CQRS is easier to add to a clean CRUD service later than to remove from a tangled one.
A written decision record helps: list the problem, the alternatives tried (indexes, caching, views), the consistency tolerance agreed with the product owner, and who will operate the projections. If any item is blank, the decision isn't ready.
Take quiz
can indexes, caching, or a simple view fix the pain?
how many microservices exist?
which broker is trendy?
separate databases with asynchronous projections anyway
separate code paths on a single database
dropping validation on writes
Found this useful? Follow Javapedia for Distributed Systems: CQRS: When to Use It and When Not to Interview questions updates!