With a database per service, how do you query across services? Explain CQRS and event sourcing.
Database per service
Each service owns its schema; others access the data only through its API or events. This preserves autonomy (schema changes, technology choice, scaling) but removes cross-service joins and ACID transactions.
Querying across services
- API composition: a composer (gateway, BFF or service) calls several services and joins in memory. Simple; fine for small result sets; latency and availability depend on all callees.
- CQRS read model: services publish events; a query service subscribes and maintains a denormalised view (in Elasticsearch, a document store or SQL tables) optimised for the query, for example an "order history" view combining orders, payments and shipments. Fast and independent, but eventually consistent and more moving parts.
CQRS (Command Query Responsibility Segregation)
Separate the write model (commands, validation, invariants, normalised) from one or more read models (queries, denormalised, possibly different stores). Use it when read and write needs differ a lot (complex domain writes, high-volume searches). Do not apply it everywhere; it adds complexity.
Event sourcing
Instead of storing current state, store the sequence of events (AccountOpened, MoneyDeposited, MoneyWithdrawn); current state is derived by replaying them. Benefits: complete audit trail, temporal queries ("balance on 1 March"), natural event publication, rebuilding new read models from history. Costs: event schema evolution, snapshotting for long streams, eventual consistency of projections, a steep learning curve. Suits ledgers, audit-heavy and collaborative domains; overkill for CRUD.
Follow-up questions interviewers ask
Try answering each one before you open it.
How do you deal with eventual consistency in the user experience?
Return the command's result directly to the user who made the change (read-your-own-writes from the write model), show pending states ("Payment processing"), use optimistic UI updates, include a version or timestamp so the client can poll until the read model catches up, and push updates via WebSocket or SSE. Measure and alert on projection lag.
How do snapshots work in event sourcing?
Replaying thousands of events per load is slow, so every N events (or periodically) the current state is saved as a snapshot with the version it reflects. Loading reads the latest snapshot and replays only the later events. Snapshots are a cache and can be discarded and rebuilt; when the aggregate's structure changes, version the snapshot format or rebuild snapshots from events.