Senior LevelExpress JS
How do you implement Command Query Responsibility Segregation (CQRS) and Event Sourcing in Express APIs?
❓ Interview Prompt: Explain CQRS architecture in Express, separating Command routes (POST/PUT) from Query routes (GET), and read-optimized Materialized Views.
In high-scale enterprise systems, CQRS (Command Query Responsibility Segregation) decouples write operations from read operations.
Express CQRS Architecture:
1
Command Routes (Write): POST/PUT controllers process state mutations by appending immutable events to an EventStore (Kafka/RabbitMQ) and returning 202 Accepted.
2
Query Routes (Read): GET controllers query highly denormalized, read-optimized Materialized Views (Elasticsearch/Redis) updated asynchronously by background event consumers!
Code Implementation Example
javascript
import express from 'express';
const app = express();
// 1. COMMAND ROUTE: Emits event to Kafka; returns 202 Accepted immediately!
app.post('/api/orders', async (req, res) => {
const event = { type: 'OrderCreated', payload: req.body, timestamp: Date.now() };
await kafkaProducer.send({ topic: 'order-events', messages: [{ value: JSON.stringify(event) }] });
res.status(202).json({ status: 'Command accepted for processing' });
});
// 2. QUERY ROUTE: Queries read-optimized Elasticsearch view!
app.get('/api/orders/:id', async (req, res) => {
const orderView = await elasticsearch.get({ index: 'orders_read_view', id: req.params.id });
res.json(orderView._source);
});💡Separating Command routes (Kafka events) from Query routes (Elasticsearch views) in CQRS.
🎯 Interview Key Takeaway
CQRS separates Command routes (emitting events to Kafka) from Query routes (reading denormalized views in Redis/Elasticsearch).
#CQRS#Event Sourcing#Kafka#Architecture#Senior
Back to all Express JS Questions→