CQRS
Command Query Responsibility Segregation in Go — commands vs queries, read and write models, projections, the inbox pattern, read-model lag, and when not to use CQRS.
13 questions
JuniorTheoryVery commonWhat is CQRS and how does it differ from CQS?
What is CQRS and how does it differ from CQS?
CQS is a method-level rule: a method either changes state (a command) or returns data (a query), never both. CQRS lifts the split to the architecture: commands go through a write model that guards invariants, and queries are served by a separate read model.
Common mistakes
- ✗Equating CQRS with event sourcing — CQRS needs no event store at all
- ✗Thinking CQRS requires separate services or databases, when separate models in one database already count
- ✗Letting a query change state, such as bumping a view counter inside a read handler
Follow-up questions
- →How does CQRS relate to the storage pattern event sourcing?
- →Why may a command still return the id of the entity it created?
JuniorTheoryVery commonWhy may a user not see their change right after a command if the read store is separate?
Why may a user not see their change right after a command if the read store is separate?
The command commits to the write store and returns; the read store is updated later, asynchronously, when the projector processes the event. Until then a query reads the old data — the read side is only eventually consistent with the write side.
Common mistakes
- ✗Treating the delay as a lost write and retrying the command
- ✗Expecting a separate read store to be strongly consistent with the write store
- ✗Blaming caching when the real cause is the asynchronous projector
Follow-up questions
- →How long can this delay last, and what does it depend on?
- →How could the user still see their own change at once?
JuniorTheoryCommonIn the architecture pattern CQRS, what is a projection and what does a projector do?
In the architecture pattern CQRS, what is a projection and what does a projector do?
A projection is a read model derived from a stream of events. The projector is a process that consumes those events in order and applies each one to the read model, inserting or updating rows, so the read side follows the write side.
Common mistakes
- ✗Thinking a projection is computed on every read rather than stored and updated ahead of time
- ✗Applying events out of order or skipping some, which corrupts the read model
- ✗Putting projection updates into the command handler's request path
Follow-up questions
- →Where can a projector read its events from?
- →Why must a projector apply events in order?
JuniorTheoryCommonIn the architecture pattern CQRS, what is a read model and why is it denormalized?
In the architecture pattern CQRS, what is a read model and why is it denormalized?
A read model is data stored in exactly the shape a screen or API response needs, built from the write side's changes. It is denormalized so a query is a single lookup with no joins or calculations; it holds no invariants and can be rebuilt.
Common mistakes
- ✗Confusing a read model with a plain read replica that copies the normalized schema
- ✗Checking business invariants against the read model, which may lag behind writes
- ✗Treating the read model as the source of truth instead of data that can be rebuilt
Follow-up questions
- →Where can a read model live besides the write database?
- →Why should a command never validate against the read model?
MiddleTheoryCommonWith an asynchronous read model, how do you give a user the consistency guarantee read-your-writes?
With an asynchronous read model, how do you give a user the consistency guarantee read-your-writes?
The command returns the new version, and the query waits, with a timeout, until the read model's version reaches it. Alternatively, read the just-changed entity from the write side for its author, or show the change optimistically in the client.
Common mistakes
- ✗Making the whole projector synchronous to hide lag, which ties write latency to every read store
- ✗Polling the read model with no version to wait for and no timeout
- ✗Serving every reader from the write side, which removes the reason for the read model
Follow-up questions
- →How would you bound the wait so a stuck projector does not hang requests?
- →Which metric shows that the read model is falling behind?
MiddleTheoryCommonWhen is the architecture pattern CQRS not worth adopting in a service?
When is the architecture pattern CQRS not worth adopting in a service?
When reads and writes look alike — a CRUD service, a small team, no read/write load asymmetry. Then CQRS adds two models, projections to run and rebuild, and stale reads, with no payoff. Apply it per bounded context where reads clearly differ.
Common mistakes
- ✗Treating CQRS as a system-wide default instead of a choice per bounded context
- ✗Believing CQRS requires event sourcing, a broker or microservices
- ✗Ignoring the operational cost of running, monitoring and rebuilding projections
Follow-up questions
- →Which signals in a service would make you add a separate read model?
- →What is the shallowest form of CQRS you could start with?
MiddleTheoryOccasionalHow does a projector track its position, and why commit the checkpoint with the read model?
How does a projector track its position, and why commit the checkpoint with the read model?
It stores the position of the last applied event — a global sequence number or a Kafka offset — in a checkpoint table. Updating it in the same transaction as the read-model rows makes both atomic: after a crash it resumes exactly there, never skipping or reapplying an event.
Common mistakes
- ✗Committing the Kafka offset before the read-model write, which loses the event on a crash
- ✗Saving the checkpoint in a separate transaction and assuming every update is idempotent
- ✗Keeping the position only in memory, so a restart replays or skips events
Follow-up questions
- →How would you rebuild this projection after changing its table schema?
- →What changes if two projector instances read the same stream at once?
MiddleTheoryOccasionalHow does the deduplication pattern inbox protect a read-model consumer under at-least-once delivery?
How does the deduplication pattern inbox protect a read-model consumer under at-least-once delivery?
In the same transaction as the read-model update, the consumer inserts the message id into an inbox table with a unique key. If the insert hits a conflict, the message was already applied and is only acknowledged; old inbox rows are purged later.
Common mistakes
- ✗Committing the inbox row and the effect in separate transactions, which leaves a gap on a crash
- ✗Keeping seen ids only in memory, so a restart or a second instance lets duplicates through
- ✗Never purging the inbox, so the table and its index grow without bound
Follow-up questions
- →How long must inbox rows be kept, and what decides that window?
- →When is a per-stream checkpoint enough instead of an inbox table?
MiddleCodeOccasionalWrite a generic decorator that runs any command handler inside a DB transaction
Write a generic decorator that runs any command handler inside a DB transaction
Return a wrapper type that begins a transaction, stores it in the context under the private key and calls the inner handler. Commit when it returns nil; otherwise, and on a panic, roll back. Repositories read the transaction back with TxFrom.
Common mistakes
- ✗Committing in a deferred call regardless of the handler's error
- ✗Not rolling back on a panic, which keeps the connection busy until the context ends
- ✗Keeping the transaction in a global variable, which races between concurrent requests
Follow-up questions
- →How would you stack logging and metrics decorators on top of this one?
- →What are the trade-offs of the data-access pattern Unit of Work versus a transaction in the context?
SeniorTheoryOccasionalHow should a Go command handler change the write model and emit events reliably?
How should a Go command handler change the write model and emit events reliably?
Load the aggregate and call its method, which checks invariants and records events; then save the aggregate and insert those events into an outbox table in one transaction, and a relay publishes them after commit. The handler returns only an error, never read data.
Common mistakes
- ✗Publishing to the broker from the handler after commit, which loses events when the process crashes in between
- ✗Building events from the raw command instead of the aggregate, so they can contradict the stored state
- ✗Returning read-model data from the command handler
Follow-up questions
- →How would the transaction decorator and the outbox insert share one transaction?
- →What does a consumer of these events need, given the relay delivers at least once?
SeniorDebuggingOccasionalFix a projector on the message broker Kafka that applies balance events out of order and twice
Fix a projector on the message broker Kafka that applies balance events out of order and twice
A goroutine per message breaks partition order, so one account's events race. The offset is committed before the update, so a crash or a failed update loses the event, and a duplicate reapplies the increment. Apply messages one by one, record the event id in an inbox inside the update's transaction, and commit the offset only after the DB commit.
Open full question →Common mistakes
- ✗Adding a mutex around the update, which removes the data race but neither the reordering nor the duplicates
- ✗Assuming Kafka never redelivers after a commit and ignoring duplicate publishes by the outbox relay
- ✗Committing the offset before the database write commits
Follow-up questions
- →How would you regain parallelism without losing per-account order?
- →Where should a message that fails to decode go instead of stopping the projector?
SeniorDesignRareDesign the product catalog of a marketplace backend written in Go. Sellers create and edit products: price, stock, attributes and category. Every edit must respect invariants — the price is positive, the category's required attributes are filled, a product without stock cannot go on sale — and the data lives in PostgreSQL. Buyers search the catalog by text and filter it by category, price range and attributes, with facet counts beside the results; read traffic is about 50 times the write traffic. A seller must see their own edit immediately after saving it, while buyers may see a change up to a few seconds late. Describe the write and read models, how changes reach the read side without being lost or applied twice, how the seller gets read-your-writes, and which parts of the system you would deliberately leave without this split.
Design the product catalog of a marketplace backend written in Go. Sellers create and edit products: price, stock, attributes and category. Every edit must respect invariants — the price is positive, the category's required attributes are filled, a product without stock cannot go on sale — and the data lives in PostgreSQL. Buyers search the catalog by text and filter it by category, price range and attributes, with facet counts beside the results; read traffic is about 50 times the write traffic. A seller must see their own edit immediately after saving it, while buyers may see a change up to a few seconds late. Describe the write and read models, how changes reach the read side without being lost or applied twice, how the seller gets read-your-writes, and which parts of the system you would deliberately leave without this split.
Seller edits go through command handlers over a normalized Postgres model whose aggregate checks the invariants, and each change writes an outbox event in the same transaction. A projector feeds a search index shaped for text search and facets, applying an update only if its product version is newer. The seller's own screens read the write side or wait for the version the command returned; buyers accept the monitored lag. Simple CRUD parts such as seller settings stay unsplit.
Common mistakes
- ✗Dual-writing to Postgres and the search index from the request handler
- ✗Relying on asynchronous replicas or the index for the seller's read-your-writes
- ✗Applying the split to every part of the system, including simple CRUD screens
Follow-up questions
- →How would you make the projector idempotent and order-safe per product?
- →How would you reindex the catalog after changing the search engine Elasticsearch mapping?
SeniorTheoryRareHow do you rebuild a read model with a new schema without downtime?
How do you rebuild a read model with a new schema without downtime?
Create a new table and run a second projector with its own checkpoint from position 0 while the old table keeps serving reads. Once it catches up with the head of the stream, switch reads to the new table, keep both briefly for rollback, then drop the old one.
Common mistakes
- ✗Rebuilding in place, so readers see a half-filled table
- ✗Switching reads before the new projector has caught up with the stream
- ✗Reusing the old checkpoint for the new projector, so it skips the history
Follow-up questions
- →What must hold for a projector so that a replay from 0 gives the same table?
- →What if events older than the topic's retention are no longer in Kafka?