0
0
Kafkadevops~5 mins

CQRS pattern in Kafka - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: CQRS pattern
O(n)
Understanding Time Complexity

When using the CQRS pattern with Kafka, we want to understand how the time to process commands and queries changes as the number of messages grows.

We ask: How does the system's work grow when more commands or queries come in?

Scenario Under Consideration

Analyze the time complexity of the following Kafka consumer code snippet implementing CQRS.


    consumer.subscribe(List.of("commands"));
    while (true) {
      var records = consumer.poll(Duration.ofMillis(100));
      for (var record : records) {
        processCommand(record.value());
      }
    }
    

This code listens to a Kafka topic for commands and processes each command one by one.

Identify Repeating Operations

Look at what repeats as input grows.

  • Primary operation: Loop over all received command messages.
  • How many times: Once for each command message received in the poll batch.
How Execution Grows With Input

As the number of commands increases, the processing work grows roughly the same amount.

Input Size (n)Approx. Operations
1010 command processings
100100 command processings
10001000 command processings

Pattern observation: The work grows linearly with the number of commands.

Final Time Complexity

Time Complexity: O(n)

This means the time to process commands grows directly with how many commands arrive.

Common Mistake

[X] Wrong: "Processing commands in CQRS is always constant time no matter how many commands come in."

[OK] Correct: Each command must be handled, so more commands mean more work and more time.

Interview Connect

Understanding how message processing scales in CQRS with Kafka shows you can reason about real systems that handle many events efficiently.

Self-Check

"What if we batch process commands in groups instead of one by one? How would the time complexity change?"