CQRS, Kafka, Debezium

December 2nd, 2026

🏠

What Is CQRS?

CQRS, also known as command query responsibility segregation, is a way to separate the models used for writing data and reading data. Within CQRS, a command is a request which updates data, and a query is a request which fetches data. In the context of HTTP, these can be thought of as including, but not exclusive to POST, PATCH, PUT for commands, and GET for queries.

What CQRS Is Not

CQRS is not the same as DDD. It does not require a separate read database, does not require the use of domain events, eventual consistency, or CDC. At its heart, it is purely concerned with the separation of models for reading and writing, however it enables and is often talked about in the same context as DDD and scalability/performance. Another benefit is code simplicity and separation of concerns, keeping code quality high and repositories organized.

Why CQRS

Although I did explicitly say that CQRS does not require the use of DDD in order to be considered CQRS, in my opinion, the strongest benefit of CQRS comes when utilizing data modeling concepts found in DDD, such as aggregates. An aggregate's main purpose is to protect business invariants and ensure that data remains consistent. As such, aggregates often have to encompass many smaller entities in order to protect the rules of the business. Quite often the data required for UI pages does not encompass all of the data in the aggregate, and in some cases could even require data outside the bounds of any one specific aggregate. Because of this, it could become cumbersome to attempt to utilize the aggregate data model to fetch data, especially when no invariants need to be upheld for read operations. Because read operations do not update any data and therefore cannot violate any invariants, SQL queries can be fine tuned and optimized to fetch exactly the data required by the UI without having to worry about upholding business rules. To keep it simple, this can just be implemented with a raw SQL query, selecting and joining any columns from within the same database. This is CQRS at its most pure form, and oftentimes it is enough in order to achieve great separation of concerns and performance increases!

What Is This Post About?

This post is an exercise taking CQRS to the extreme. It exhibits a complex way to incorporate CQRS with a scalable system. It is in no way what should be strived for out of the gate, and is most likely only necessary with extremely hot read paths for thousands of requests a second. Starting with the aforementioned strategy of simply separating DDD aggregate roots for writes and raw SQL queries for reads is a great starting point for implementing CQRS.

Data Modeling and Technology

In order to implement this, I used AI (of course at this point), along with some other technologies. Firstly, I want to start with the framework and language, that being NestJS and TypeScript.

NestJS actually has an explicit section in the documentation (yes, people still read documentation) for CQRS implementation, meaning the support is great and the implementation is easy to follow. For my implementation, I decided to go with an airline booking service, which would manage flights and seats, and have requirements to fetch some aggregated data for specific flights, such as how many first class seats are left, potential revenue, total price of already booked seats, and more.

NestJS Implementation

To start, we have our controller which handles all incoming requests. NestJS has the concept of a command bus, which executes commands, and therefore updates data. Taking a look at the commands, you can see that they are related to the updating or creating of data with regards to an airplane, such as creating an airplane, or booking a seat. This is only a subset of the controller code.

@ApiTags('commands (write DB)')
@ApiNotFoundResponse({ type: ErrorResponseDto, description: 'Airplane or seat does not exist' })
@Controller('airplanes')
export class AirplaneCommandController {
constructor(private readonly commandBus: CommandBus) {}

  @Post()
  @ApiOperation({ summary: 'Create an airplane with a generated seat map' })
  @ApiCreatedResponse({ type: CommandResultDto })
  @ApiBadRequestResponse({ type: ErrorResponseDto, description: 'Validation or invalid layout' })
  @ApiConflictResponse({ type: ErrorResponseDto, description: 'Tail number already exists' })
  create(@Body() dto: CreateAirplaneDto): Promise<CommandResultDto> {
	return this.commandBus.execute(
	  new CreateAirplaneCommand(dto.tailNumber, dto.model, dto.baseTicketPrice, {
		rows: dto.rows,
		seatsPerRow: dto.seatsPerRow,
		firstClassRows: dto.firstClassRows,
	  }),
	);
  }

  @Post(':id/seats/:seatNumber/book')
  @HttpCode(200)
  @ApiOperation({ summary: 'Book a seat for a passenger' })
  @ApiParam(airplaneIdParam)
  @ApiParam(seatParam)
  @ApiOkResponse({ type: CommandResultDto })
  @ApiConflictResponse({
	type: ErrorResponseDto,
	description: 'SEAT_ALREADY_BOOKED, PASSENGER_ALREADY_SEATED, AIRPLANE_GROUNDED or AGGREGATE_LOCKED',
  })
  book(
	@Param('id', ParseUUIDPipe) id: string,
	@Param('seatNumber') seatNumber: string,
	@Body() dto: BookSeatDto,
  ): Promise<CommandResultDto> {

	return this.commandBus.execute(new BookSeatCommand(id, seatNumber, dto.passengerName));

In order to model the airplane aggregate and seat entity, we utilize TypeORM. In this example, I've merged the domain model with the TypeORM entity to keep things simple, although it could be argued it is against DDD and there should be a separate pure domain model living in the code which can be "materialized" from a database record. The airplane aggregate upholds the dummy invariants that I've invented for this project, which can be seen in the methods on the class. Again, this is only a snippet of the entity.

@Entity({ name: 'airplanes' })
export class Airplane {
  @PrimaryColumn('uuid')
  readonly id: string;

  @Column({ name: 'tail_number', type: 'text', unique: true })
  readonly tailNumber: string;

  @Column({ type: 'text' })
  readonly model: string;

  @Column({ name: 'base_ticket_price', type: 'numeric', precision: 10, scale: 2, transformer: NumericTransformer })
  private _baseTicketPrice: number;

  @Column({ name: 'status', type: 'text' })
  private _status: AirplaneStatus;

  /** Bumped by the repository on every save; read models expose it as writeVersion. */
  @Column({ type: 'integer', default: 0 })
  version: number;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  readonly createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  readonly updatedAt: Date;

  /** Always loaded together with the root. Mutate seats through the methods below, not directly. */
  @OneToMany(() => Seat, (seat) => seat.airplane, { cascade: ['insert', 'update'] })
  readonly seats: Seat[];

  /** TypeORM instantiates with no arguments and then assigns columns; the factory passes props. */
  private constructor(props?: { id: string; tailNumber: string; model: string; baseTicketPrice: number; seats: Seat[] }) {
    if (props) {
      this.id = props.id;
      this.tailNumber = props.tailNumber;
      this.model = props.model;
      this._baseTicketPrice = props.baseTicketPrice;
      this._status = AirplaneStatus.ACTIVE;
      this.version = 0;
      this.seats = props.seats;
    }
  }

  static create(input: { tailNumber: string; model: string; baseTicketPrice: number; layout: SeatLayout }): Airplane {
    const { layout } = input;
    const tailNumber = input.tailNumber.trim().toUpperCase();

    if (!/^[A-Z0-9-]{3,10}$/.test(tailNumber)) {
      throw new InvalidAirplaneError('Tail number must be 3-10 alphanumeric characters');
    }
    if (!input.model.trim()) {
      throw new InvalidAirplaneError('Model is required');
    }
    if (!(input.baseTicketPrice > 0)) {
      throw new InvalidAirplaneError('Base ticket price must be positive');
    }
    if (layout.rows < 1 || layout.rows > 60) {
      throw new InvalidAirplaneError('Rows must be between 1 and 60');
    }
    if (layout.seatsPerRow < 1 || layout.seatsPerRow > SEAT_LETTERS.length) {
      throw new InvalidAirplaneError(`Seats per row must be between 1 and ${SEAT_LETTERS.length}`);
    }
    if (layout.firstClassRows < 0 || layout.firstClassRows > layout.rows) {
      throw new InvalidAirplaneError('First class rows must be between 0 and the number of rows');
    }

    const id = randomUUID();
    const seats: Seat[] = [];
    for (let row = 1; row <= layout.rows; row++) {
      const cabin = row <= layout.firstClassRows ? CabinClass.FIRST : CabinClass.ECONOMY;
      for (let i = 0; i < layout.seatsPerRow; i++) {
        seats.push(Seat.create(randomUUID(), id, `${row}${SEAT_LETTERS[i]}`, cabin));
      }
    }

    return new Airplane({
      id,
      tailNumber,
      model: input.model.trim(),
      baseTicketPrice: round2(input.baseTicketPrice),
      seats,
    });
  }

  // ---------- behaviour (commands) ----------

  bookSeat(seatNumber: string, passengerName: string): Seat {
    this.assertActive();
    const seat = this.seatOrThrow(seatNumber);
    const name = passengerName.trim();
    if (!name) {
      throw new InvalidAirplaneError('Passenger name is required');
    }

    const existing = this.seatHeldBy(name);
    if (existing) {
      throw new PassengerAlreadySeatedError(name, existing.seatNumber);
    }

    seat.book(name, new Date());
    return seat;
  }

  cancelSeat(seatNumber: string): Seat {
    const seat = this.seatOrThrow(seatNumber);
    seat.release();
    return seat;
  }

  changeBasePrice(newPrice: number): void {
    if (!(newPrice > 0)) {
      throw new InvalidPriceChangeError('Base ticket price must be positive');
    }
    const ceiling = round2(this._baseTicketPrice * MAX_PRICE_INCREASE_FACTOR);
    if (newPrice > ceiling) {
      throw new InvalidPriceChangeError(
        `Price can be raised to at most ${ceiling.toFixed(2)} in one change (current ${this._baseTicketPrice.toFixed(2)})`,
      );
    }
    this._baseTicketPrice = round2(newPrice);
  }

  ground(): void {
    const booked = this.seats.filter((s) => s.isBooked).length;
    if (booked > 0) {
      throw new AirplaneHasBookingsError(this.tailNumber, booked);
    }
    this._status = AirplaneStatus.GROUNDED;
  }
			

Taking a look at the commands themselves, it delegates the business logic to the aggregate root while utilizing a unit of work pattern in order to keep all entity adjustments transactionally consistent.

 
@CommandHandler(CreateAirplaneCommand)
export class CreateAirplaneHandler implements ICommandHandler<CreateAirplaneCommand, CommandResult> {
  constructor(private readonly uow: AirplaneUnitOfWork) {}

  execute(cmd: CreateAirplaneCommand): Promise<CommandResult> {
    return this.uow.create(
      Airplane.create({
        tailNumber: cmd.tailNumber,
        model: cmd.model,
        baseTicketPrice: cmd.baseTicketPrice,
        layout: cmd.layout,
      }),
    );
  }
}

@CommandHandler(BookSeatCommand)
export class BookSeatHandler implements ICommandHandler<BookSeatCommand, CommandResult> {
  constructor(private readonly uow: AirplaneUnitOfWork) {}

  execute(cmd: BookSeatCommand): Promise<CommandResult> {
    return this.uow.mutate(cmd.airplaneId, (airplane) => airplane.bookSeat(cmd.seatNumber, cmd.passengerName));
  }
}
 
@Injectable()
export class AirplaneUnitOfWork {
  private readonly logger = new Logger(AirplaneUnitOfWork.name);

  constructor(
    @InjectDataSource(WRITE_DB) private readonly dataSource: DataSource,
    private readonly airplanes: AirplaneRepository,
  ) {}

  async mutate(airplaneId: string, action: (airplane: Airplane) => void): Promise<CommandResult> {
    return this.dataSource.transaction(async (manager) => {
      // Fail fast instead of queueing forever behind a slow writer.
      await manager.query(`SET LOCAL lock_timeout = '5s'`);

      const airplane = await this.airplanes.findByIdForUpdate(manager, airplaneId);
      action(airplane);
      await this.airplanes.save(manager, airplane);

      this.logger.log(`airplane ${airplane.tailNumber} -> version ${airplane.version}`);
      return { airplaneId: airplane.id, version: airplane.version };
    });
  }

  async create(airplane: Airplane): Promise<CommandResult> {
    return this.dataSource.transaction(async (manager) => {
      await this.airplanes.insert(manager, airplane);
      this.logger.log(`airplane ${airplane.tailNumber} created with ${airplane.seats.length} seats`);
      return { airplaneId: airplane.id, version: airplane.version };
    });
  }
}

CDC

CDC, or change data capture, is a way to keep track of row level changes of specific database tables. Oftentimes, it is implemented by reading the database WAL to figure out which rows have been updated, deleted, or created. With CDC, it becomes possible to stream changes from a database directly into a queue to be processed by downstream services. With CDC enabled, each change is tracked in a global transaction log. In order to determine at which point in time a CDC consumer should start and end at, LSNs, or log sequence numbers, are used. They tell the database during which time period the client wants to receive changes for. This allows for CDC events to be replayed, in the event that a client was down and missed CDC events during a specific duration of time. CDC also typically has different modes, either net changes or full changes. Net changes will, over a point in time, give the most recent state of each row which has been changed in the LSN window. Contrarily, full changes will give all the changes which have occurred to a specific row during the selected time. Full changes can be especially useful for event streaming, while net changes may be more useful for data warehousing applications.

Postgres and CDC

Postgres has extensive CDC support, especially with its configuration options. With CDC, the WAL is cleaned up every so often, to maintain speed and performance requirements of the database. Consider the event that a CDC consumer goes down at LSN 10, until LSN 100. If at any point before the consumer comes back up, the database decides to clear the WAL events between 10 and 100, the consumer will actually miss important changes! To combat this, historically the WAL will be written to a separate file, and CDC consumers will have to look to this file in the event the WAL no longer contains the changes they request. But Postgres has a more elegant solution. Postgres offers what is known as a logical replication slot. This slot keeps track of CDC consumers and what LSN each of them have consumed up to, so it knows what data from the WAL is safe to remove. This ensures that consumers will never miss any data, and the WAL will never be prematurely cleaned up.

Kafka

Kafka is an event streaming platform which stores and streams real time events to consumers. In order to understand the next section, it's important to know a couple of key terms.

Broker
A Kafka server typically running only a singular Kafka instance.
Topic
A named feed or log which consumers will subscribe to, in order to get events which are written to said topic. One topic can have multiple subscribers, and an event is not removed if consumed by a subscriber. It can be thought of as a logical grouping of messages.
Partition
A physical grouping of messages on a topic. A topic can be split amongst many different servers for reliability or scalability. Event ordering is only guaranteed within a Kafka partition, and cannot be guaranteed across multiple partitions in a singular topic. Events can be routed to the same partition by specifying a message key.
Consumer Group
One or more consumers which read data from topics. Consumers will join a group, where a group is subscribed to one or more topics. Kafka will manage the message group and evenly distribute the consumers within the group to read from the underlying partitions of a topic, and rebalance in the event of new or leaving consumers. For example, if there are 6 partitions of a topic, and 3 consumers, Kafka will automatically allocate each consumer 2 partitions.

Kafka Setup

For this project, we have a Kafka instance running in a Docker container, with two topics, "airline.public.airplanes" and "airline.public.seats", and a single partition per each. Within this project, we are subscribing to the Kafka topics in a separate NestJS application specifically designed to consume and replicate events to our read database, called a projector.

Kafka UI showing the two topics for airplanes and seats

Events in the Kafka topic for airplanes

Visibility into consumers in the consumer group

Consumer metadata

 
@Injectable()
export class CdcConsumer implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(CdcConsumer.name);
  private readonly kafka: Kafka;
  private readonly consumer: Consumer;
  private readonly groupId = process.env.KAFKA_GROUP_ID ?? 'airline-read-model-projector';

  constructor(private readonly projections: ProjectionService) {
    this.kafka = new Kafka({
      clientId: 'airline-projector',
      brokers: (process.env.KAFKA_BROKERS ?? 'localhost:29092').split(','),
      logLevel: logLevel.WARN,
    });
    this.consumer = this.kafka.consumer({ groupId: this.groupId });
  }

  async onModuleInit(): Promise<void> {
    await this.ensureTopics();

    await this.consumer.connect();
    // fromBeginning only matters for a brand-new consumer group (first start / rebuild):
    // it replays everything the broker retained, which rebuilds the read models from scratch.
    await this.consumer.subscribe({ topics: CDC_TOPICS, fromBeginning: true });

    await this.consumer.run({
      eachMessage: async ({ topic, partition, message }) => {
        if (!message.value) {
          return; // Kafka tombstone (disabled in Debezium config, but be safe)
        }
        const event = JSON.parse(message.value.toString()) as DebeziumEvent;
        this.logger.debug(`${topic}[${partition}]@${message.offset} op=${event.op}`);
        await this.projections.project(event);
      },
    });

    this.logger.log(`consuming ${CDC_TOPICS.join(', ')} as group "${this.groupId}"`);
  }

  async onModuleDestroy(): Promise<void> {
    await this.consumer.disconnect();
  }

  /** Create the topics up front so the consumer never waits on broker auto-creation. Idempotent. */
  private async ensureTopics(): Promise<void> {
    const admin = this.kafka.admin();
    await admin.connect();
    try {
      await admin.createTopics({
        waitForLeaders: true,
        topics: CDC_TOPICS.map((topic) => ({ topic, numPartitions: 1, replicationFactor: 1 })),
      });
    } finally {
      await admin.disconnect();
    }
  }
}

Debezium

Debezium is the glue that holds together the CDC and Kafka. Debezium automatically connects to Postgres and will output CDC events which have been written to the WAL into our Kafka topic based on which table the CDC event came from. This Debezium instance is also running on a Docker container and is set up to subscribe to Postgres with the aforementioned logical replication slot. Debezium will publish the change event into the Kafka topic, so that consumers will have all the information required to do their own tasks.

Two Postgres Databases

The main point of this architecture is so that we can have a consumer which reads our Kafka topic and writes to a separate Postgres database, on an entirely different server. This Postgres database instance will be specifically used for reading data. Not only will the server be scalable independently of our write database, but the tables and models within the database will differ completely. This gives us the ability to cater directly to what our UI is going to need to display to users, aggregating data across different tables in the write database, or utilizing different indexes which might slow down updates or insertions on the write database. This also increases fault tolerance. Read paths of the application will continue to operate if the write database goes down, and vice versa. It also allows for sharding of data more easily, as distributed writes and transactions are much more difficult than distributed reads, and we can choose to shard read data while keeping write data all in one place.

Two APIs

To organize this project, there are two main APIs which should be noted. The first is the API which handles direct HTTP requests from clients, both the command side and read side. The read side will consume from the read-only Postgres database and serve the read models which we have created via the Debezium + Kafka replication process. The second API is for consuming the messages from Kafka, transforming them, and writing them over to the read database. This style of application is known as a projector, as it "projects" data to a downstream system.

 
@Injectable()
export class ProjectionService {
  private readonly logger = new Logger(ProjectionService.name);

  constructor(
    @InjectDataSource(READ_DB) private readonly readDb: DataSource,
    private readonly airplaneSummary: AirplaneSummaryProjector,
    private readonly seatMap: SeatMapProjector,
    private readonly bookingActivity: BookingActivityProjector,
  ) {}

  async project(event: DebeziumEvent): Promise<void> {
    const table = event?.source?.table;
    if (!table || !event.op) {
      this.logger.warn(`ignoring non-change payload: ${JSON.stringify(event).slice(0, 200)}`);
      return;
    }

    await this.readDb.transaction(async (manager) => {
      switch (table) {
        case 'airplanes':
          await this.airplaneSummary.apply(manager, event as DebeziumEvent<AirplaneRow>);
          break;
        case 'seats':
          await this.seatMap.apply(manager, event as DebeziumEvent<SeatRow>);
          await this.bookingActivity.apply(manager, event as DebeziumEvent<SeatRow>);
          break;
        default:
          this.logger.debug(`no projector for table ${table}`);
      }
    });
  }
}
			
 
@Injectable()
export class AirplaneSummaryProjector {
  private readonly logger = new Logger(AirplaneSummaryProjector.name);

  async apply(manager: EntityManager, event: DebeziumEvent<AirplaneRow>): Promise<void> {
    if (event.op === 'd') {
      const id = event.before!.id;
      await manager.delete(BookingActivityEntity, { airplaneId: id });
      await manager.delete(SeatMapEntity, { airplaneId: id });
      await manager.delete(AirplaneSummaryEntity, { airplaneId: id });
      this.logger.log(`airplane ${id} removed from read models`);
      return;
    }

    const row = event.after!;

    await manager.upsert(
      AirplaneSummaryEntity,
      {
        airplaneId: row.id,
        tailNumber: row.tail_number,
        model: row.model,
        status: row.status,
        baseTicketPrice: row.base_ticket_price,
        writeVersion: row.version,
        projectedAt: new Date(),
      },
      { conflictPaths: ['airplaneId'] },
    );

    // Base price lives on the airplane; every seat's effective price depends on it.
    await manager
      .createQueryBuilder()
      .update(SeatMapEntity)
      .set({ price: () => `ROUND(:base * price_multiplier, 2)` })
      .where('airplane_id = :airplaneId')
      .setParameters({ base: row.base_ticket_price, airplaneId: row.id })
      .execute();

    await recalculateAirplaneSummary(manager, row.id);

    this.logger.log(`[${event.op}] airplane ${row.tail_number} v${row.version} -> airplane_summary`);
  }
  }
			
 
@Injectable()
export class BookingActivityProjector {
  private readonly logger = new Logger(BookingActivityProjector.name);

  async apply(manager: EntityManager, event: DebeziumEvent<SeatRow>): Promise<void> {
    if (event.op !== 'u' && event.op !== 'c') {
      return; // snapshot reads and deletes are not activity
    }

    const before = event.before;
    const after = event.after!;
    const wasBooked = before?.status === 'BOOKED';
    const isBooked = after.status === 'BOOKED';
    if (wasBooked === isBooked) {
      return; // no status transition (e.g. only the airplane changed, or an unrelated column)
    }

    const eventType = isBooked ? 'SEAT_BOOKED' : 'SEAT_RELEASED';
    const passengerName = isBooked ? after.passenger_name : (before?.passenger_name ?? null);

    await manager
      .createQueryBuilder()
      .insert()
      .into(BookingActivityEntity)
      .values({
        sourceLsn: event.source.lsn ?? 0,
        seatId: after.id,
        airplaneId: after.airplane_id,
        seatNumber: after.seat_number,
        cabinClass: after.cabin_class,
        eventType,
        passengerName,
        occurredAt: new Date(event.source.ts_ms),
      })
      .orIgnore() // ON CONFLICT DO NOTHING: a redelivered event is a no-op
      .execute();

    this.logger.log(`${eventType} seat ${after.seat_number} ${passengerName ?? ''} (lsn ${event.source.lsn})`);
  }
}

Why?

Now with all this complexity, you might be asking why? Well, because I wanted to. But from a professional standpoint, most of the time something like this won't be necessary. The benefits of CQRS can be vastly different depending on how far you want to take it, anywhere from simple code organization to being able to scale each and every part of your application to your specific needs. In this case, the separate read model and read database allow for the read database to be scaled completely separately from the write database, in the event that our system has to serve an absurd amount of read requests per second, but not a lot of write requests.

Link to the GitHub repository