CQRS (Command Query Responsibility Segregation) splits an application into a write side (commands: create, update, delete) and a read side (queries), each with its own model.It is used because reads and writes have different needs. Writes need validation and consistency, while reads need speed and query-friendly shapes, so each side can be optimized and scaled independently.The command service writes to its own database and then updates the read model held by the query service, so the two sides stay in sync (eventual consistency).In this demo, a Product Command Service (port 8081) handles all changes and a Product Query Service (port 8082) serves all reads from a separate database.
Features
- Separate services and separate databases for writes and reads
- Write model and read model shaped differently (the read model adds
availability) - Independent scaling of the read and write sides
- Query-specific endpoints: by id, by category, by name search, by availability
- Read model synchronized automatically after every command
- Command still succeeds if the query service is down (eventual consistency)
CQRS Types
| Kind | How it works | Used in this demo |
|---|---|---|
| Simple CQRS (same database) | Separate command and query classes or models, but one shared database. | No |
| CQRS with separate databases | The write database and the read database are different. Changes are copied to the read database. | Yes (product_command_db and product_query_db) |
| CQRS with Event Sourcing | The write side stores a sequence of events instead of the current state, and read models are built by replaying the events. | No |
Hands-on Experiment: Building Product Command and Query Services using CQRS
Aim: To build two Spring Boot microservices that follow the CQRS pattern: a command service that handles all writes and a query service that serves all reads from its own read-optimized database, kept in sync after every change.
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
Generate this project twice at https://start.spring.io, once for each service.
Command service
- Project: Maven
- Language: Java
- Spring Boot: 3.3.x
- Group:
com.example - Artifact:
product-command-service - Packaging: Jar
- Java: 17
- Dependencies: Spring Web, Spring Data JPA, MySQL Driver
Query service: the same settings, with Artifact product-query-service.
Click Generate, extract both zips and open each in your IDE.
Step 2: Project Structure

Step 3: Create Product Command service
package com.example.command.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
// WRITE MODEL: normalized entity stored in the command database
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String category;
private Double price;
private Integer stock;
private String description;
public Product() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
package com.example.command.repository;
import com.example.command.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
package com.example.command.service;
import com.example.command.entity.Product;
import com.example.command.repository.ProductRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ResponseStatusException;
// Handles COMMANDS only (create / update / delete). It never serves queries.
@Service
public class ProductCommandService {
private static final Logger log = LoggerFactory.getLogger(ProductCommandService.class);
private final ProductRepository productRepository;
private final RestTemplate restTemplate = new RestTemplate();
@Value("${query.service.url}")
private String queryServiceUrl;
public ProductCommandService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public Product createProduct(Product request) {
request.setId(null);
Product saved = productRepository.save(request);
log.info("COMMAND: product {} created in write database", saved.getId());
syncToReadModel(saved);
return saved;
}
public Product updateProduct(Long id, Product request) {
Product existing = productRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found: " + id));
existing.setName(request.getName());
existing.setCategory(request.getCategory());
existing.setPrice(request.getPrice());
existing.setStock(request.getStock());
existing.setDescription(request.getDescription());
Product saved = productRepository.save(existing);
log.info("COMMAND: product {} updated in write database", saved.getId());
syncToReadModel(saved);
return saved;
}
public void deleteProduct(Long id) {
if (!productRepository.existsById(id)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found: " + id);
}
productRepository.deleteById(id);
log.info("COMMAND: product {} deleted from write database", id);
try {
restTemplate.delete(queryServiceUrl + "/internal/sync/products/" + id);
} catch (Exception e) {
log.warn("Read model could not be updated for delete of product {}: {}", id, e.getMessage());
}
}
// Pushes the change to the read side (eventual consistency).
// The command still succeeds even if the query service is down.
// In production this would be an event sent through Kafka / RabbitMQ.
private void syncToReadModel(Product product) {
try {
restTemplate.put(queryServiceUrl + "/internal/sync/products", product);
log.info("Read model synchronized for product {}", product.getId());
} catch (Exception e) {
log.warn("Read model could not be updated for product {}: {}", product.getId(), e.getMessage());
}
}
}
package com.example.command.controller;
import com.example.command.entity.Product;
import com.example.command.service.ProductCommandService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/commands/products")
public class ProductCommandController {
private final ProductCommandService productCommandService;
public ProductCommandController(ProductCommandService productCommandService) {
this.productCommandService = productCommandService;
}
@PostMapping
public ResponseEntity<Product> create(@RequestBody Product product) {
return ResponseEntity.status(HttpStatus.CREATED).body(productCommandService.createProduct(product));
}
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @RequestBody Product product) {
return productCommandService.updateProduct(id, product);
}
@DeleteMapping("/{id}")
public ResponseEntity<String> delete(@PathVariable Long id) {
productCommandService.deleteProduct(id);
return ResponseEntity.ok("Product " + id + " deleted");
}
}
package com.example.command;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductCommandApplication {
public static void main(String[] args) {
SpringApplication.run(ProductCommandApplication.class, args);
}
}
spring.application.name=product-command-service
server.port=8081
# ---------- Write database (MySQL) ----------
spring.datasource.url=jdbc:mysql://localhost:3306/product_command_db?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# ---------- Query service (read side) ----------
query.service.url=http://localhost:8082Code language: PHP (php)
Step 4: Create Product Query service
package com.example.query.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
// READ MODEL: shaped for queries. The id comes from the command side (no auto-generation),
// and extra query-friendly fields (availability, lastSyncedAt) are added.
@Entity
@Table(name = "product_views")
public class ProductView {
@Id
private Long id;
private String name;
private String category;
private Double price;
private Integer stock;
private String description;
// IN_STOCK / LOW_STOCK / OUT_OF_STOCK - pre-computed so queries are simple and fast
private String availability;
private LocalDateTime lastSyncedAt;
public ProductView() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getAvailability() { return availability; }
public void setAvailability(String availability) { this.availability = availability; }
public LocalDateTime getLastSyncedAt() { return lastSyncedAt; }
public void setLastSyncedAt(LocalDateTime lastSyncedAt) { this.lastSyncedAt = lastSyncedAt; }
}
package com.example.query.repository;
import com.example.query.entity.ProductView;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductViewRepository extends JpaRepository<ProductView, Long> {
List<ProductView> findByCategory(String category);
List<ProductView> findByNameContainingIgnoreCase(String name);
List<ProductView> findByAvailability(String availability);
}
package com.example.query.service;
import com.example.query.entity.ProductView;
import com.example.query.repository.ProductViewRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
// Handles QUERIES only (read). Also applies changes pushed from the command side.
@Service
public class ProductQueryService {
private static final Logger log = LoggerFactory.getLogger(ProductQueryService.class);
private final ProductViewRepository productViewRepository;
public ProductQueryService(ProductViewRepository productViewRepository) {
this.productViewRepository = productViewRepository;
}
// ---------------- Queries ----------------
public List<ProductView> getAll() {
log.info("QUERY: get all products");
return productViewRepository.findAll();
}
public ProductView getById(Long id) {
log.info("QUERY: get product {}", id);
return productViewRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Product not found in read model: " + id));
}
public List<ProductView> getByCategory(String category) {
log.info("QUERY: get products in category {}", category);
return productViewRepository.findByCategory(category);
}
public List<ProductView> search(String name) {
log.info("QUERY: search products by name '{}'", name);
return productViewRepository.findByNameContainingIgnoreCase(name);
}
public List<ProductView> getByAvailability(String availability) {
log.info("QUERY: get products with availability {}", availability);
return productViewRepository.findByAvailability(availability.toUpperCase());
}
// ---------------- Read model synchronization ----------------
public void upsert(ProductView view) {
view.setAvailability(calculateAvailability(view.getStock()));
view.setLastSyncedAt(LocalDateTime.now());
productViewRepository.save(view);
log.info("SYNC: read model updated for product {}", view.getId());
}
public void remove(Long id) {
productViewRepository.deleteById(id);
log.info("SYNC: product {} removed from read model", id);
}
private String calculateAvailability(Integer stock) {
if (stock == null || stock <= 0) {
return "OUT_OF_STOCK";
}
return stock <= 10 ? "LOW_STOCK" : "IN_STOCK";
}
}
package com.example.query.controller;
import com.example.query.entity.ProductView;
import com.example.query.service.ProductQueryService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/queries/products")
public class ProductQueryController {
private final ProductQueryService productQueryService;
public ProductQueryController(ProductQueryService productQueryService) {
this.productQueryService = productQueryService;
}
@GetMapping
public List<ProductView> getAll() {
return productQueryService.getAll();
}
@GetMapping("/{id}")
public ProductView getById(@PathVariable Long id) {
return productQueryService.getById(id);
}
@GetMapping("/category/{category}")
public List<ProductView> getByCategory(@PathVariable String category) {
return productQueryService.getByCategory(category);
}
@GetMapping("/search")
public List<ProductView> search(@RequestParam String name) {
return productQueryService.search(name);
}
@GetMapping("/availability/{status}")
public List<ProductView> getByAvailability(@PathVariable String status) {
return productQueryService.getByAvailability(status);
}
}
package com.example.query.controller;
import com.example.query.entity.ProductView;
import com.example.query.service.ProductQueryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
// Internal endpoints called ONLY by the command service to keep the read model up to date
@RestController
@RequestMapping("/internal/sync/products")
public class ProductSyncController {
private final ProductQueryService productQueryService;
public ProductSyncController(ProductQueryService productQueryService) {
this.productQueryService = productQueryService;
}
@PutMapping
public ResponseEntity<Void> upsert(@RequestBody ProductView view) {
productQueryService.upsert(view);
return ResponseEntity.ok().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> remove(@PathVariable Long id) {
productQueryService.remove(id);
return ResponseEntity.ok().build();
}
}
package com.example.query;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProductQueryApplication {
public static void main(String[] args) {
SpringApplication.run(ProductQueryApplication.class, args);
}
}
spring.application.name=product-query-service
server.port=8082
# ---------- Read database (MySQL) ----------
spring.datasource.url=jdbc:mysql://localhost:3306/product_query_db?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=trueCode language: PHP (php)
Step 5: Run the services one by one
i. Command service
ii. Query service


