CQRS pattern in Kafka - Time & Space 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?
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.
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.
As the number of commands increases, the processing work grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 command processings |
| 100 | 100 command processings |
| 1000 | 1000 command processings |
Pattern observation: The work grows linearly with the number of commands.
Time Complexity: O(n)
This means the time to process commands grows directly with how many commands arrive.
[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.
Understanding how message processing scales in CQRS with Kafka shows you can reason about real systems that handle many events efficiently.
"What if we batch process commands in groups instead of one by one? How would the time complexity change?"