Overview

10 Organizing a Kafka project

This chapter argues that a successful Kafka adoption is as much about process and governance as it is about code. It begins with business discovery—clarifying outcomes, mapping real-world workflows, and cataloging meaningful state-change events with clear ownership and semantics. From there, teams formalize functional requirements for topics and contracts (naming, keys and partitioning, replication, retention and compaction, schemas and compatibility, headers, consumer groups and assignment) and capture nonfunctional needs (message size and compression, latency targets via percentiles, throughput patterns and growth, security and compliance controls, loss tolerance, and dead-letter handling). Treating these as first-class requirements aligns cost, reliability, and performance expectations before any workload goes live.

To keep clusters consistent and auditable across environments, the chapter promotes a declarative, GitOps-led model over ad hoc CLI/UI changes and auto-creation defaults. Kafka artifacts—topics, schemas, ACLs, connectors—are stored in version control, applied by CI/CD, and guarded by validation and drift detection; collaboration flows through pull requests owned by producer teams. Automation can leverage Kafka Admin, Schema Registry, and Connect APIs; in platformed estates, Kubernetes operators orchestrate CRDs via tools like Argo CD or Flux, while non-Kubernetes setups rely on IaC alternatives. Environment strategy favors separate clusters per stage, or, when sharing is unavoidable, strict isolation via prefixes, distinct registries, ACLs, quotas, and controlled, masked migration of production data.

Quality assurance spans unit, integration, and performance testing tailored to event-driven components. Unit tests isolate service logic with mocks and validate producer/consumer behavior at API boundaries; Kafka Streams topologies are exercised with a dedicated test driver. Integration tests verify real communication paths using lightweight brokers (embedded) or disposable, Dockerized clusters (Testcontainers) to cover serialization, offsets, security, and rebalances. Finally, performance tests use producer/consumer benchmarks and load-testing tools to measure throughput and latency percentiles against the stated nonfunctional requirements, feeding data back into tuning, sizing, and quota decisions.

Applying Kafka cluster modifications via GitOps: After the updated Kafka cluster configuration is pushed, the CI/CD pipeline retrieves the current cluster state, calculates the required modifications, and applies them.
Collaborating on changes via pull requests. Developers from the consumer team use pull requests to propose changes, which are then reviewed and either approved or rejected by the data owners (producer team).
Applying changes with a Kubernetes operator. Argo CD synchronizes the desired state from Git with the current state of custom resources in the cluster, and it applies the differences automatically.
Unit testing of the ProfileService component. The test invokes the service with test input and verifies its behavior without involving a Kafka cluster. Evaluation is done by inspecting the return value or verifying that the producer was called as expected.
Unit testing the Customer360Service component. The test directly invokes the consumer’s handler method with a deserialized Kafka message, simulating message delivery without involving a Kafka cluster. The test then evaluates the service’s behavior by inspecting its side effects, such as interactions with downstream components or state changes.
Unit testing Kafka components using mock implementations. The services are tested in isolation by replacing the actual Kafka producer and consumer with mocks. This allows the test logic to focus on verifying functional behavior without involving a Kafka cluster or real network communication.
Integration testing of the ProfileService producer. The test invokes the service, triggering the actual producer code that sends a message to Kafka. A test consumer subscribes to the topic and receives the message from the Kafka cluster. The test then evaluates the content and metadata of the received message to verify correct delivery and structure.
Integration testing of the consumer component in Customer360Service. The test sends a message to the Kafka cluster using a test producer. When the message is consumed, ArgumentCaptor is used to capture the parameters passed to the service logic. The test then evaluates the captured data to verify that the consumer received and handled the message correctly.
Integration testing using an embedded Kafka broker. ProfileService sends a message to an in-memory Kafka instance provided by the EmbeddedKafkaBroker component. The test code verifies the message by consuming it from the embedded broker and evaluating its content and metadata.
Integration testing of the consumer logic using an embedded Kafka broker. A test message is sent to the in-memory broker, which is consumed by Customer360Service. The test verifies that the consumer processes the message correctly, without requiring an external Kafka cluster.
Integration testing of ProfileService using a Kafka cluster launched via Testcontainers. The test code starts a real Kafka broker inside a Docker container, invokes the service, and validates that the message was correctly sent to the Kafka topic.
Integration testing of the Customer360Service using a Dockerized Kafka cluster. A test message is sent to the cluster, and the consumer processes it as it would in production. The test verifies the consumer’s behavior by evaluating the resulting side effects or service invocations.

Summary

  • Business-first event modeling is essential. Start by identifying meaningful state changes and who needs to react. Don’t just jump ahead to topic design.
  • Event catalogues bridge business and tech. Capture each event’s purpose, producer, consumer, and data long before thinking about serializers or wire formats.
  • Functional requirements help validate Kafka as the right fit. They also guide topic design, including ordering, partitioning, retention, and data sensitivity.
  • Nonfunctional requirements shape cluster sizing and tuning. Collect data on latency, throughput, and message size to configure producers, consumers, and brokers effectively.
  • Declarative GitOps workflows promote consistency. Using tools like Kafka-GitOps or Terraform helps maintain reliable, version-controlled topic and schema definitions.
  • Unit and integration testing are critical for Kafka clients. Frameworks like Mockito exist to simulate producers, consumers, and end-to-end flows in automated tests.
  • Performance testing reveals real-world behavior. Use tools like JMeter and Trogdor to experiment with different configurations and validate how they impact throughput and latency under load.

FAQ

How do we decide if a use case is a good fit for Kafka and event-driven architecture?Start from business outcomes, not technology. Validate that the process benefits from asynchronous, decoupled communication and can tolerate eventual consistency. Ask functional questions: is ordering required, can events be partitioned by a stable key, are consumers idempotent, do we need real time or batch, do we know and govern the schema, and do we need to correlate events across workflows. If these align, Kafka is likely appropriate.
What should we capture during business discovery before modeling events?Run workshops, interviews, write user stories, and map process flows to understand goals, actors, approvals, timing, edge cases, and failure paths. Use plain-language narratives such as “When X happens, Y should occur.” This ensures the technical model reflects how the business really operates and avoids premature design based on system internals.
How do we turn workflows into events and what belongs in an event catalog?Identify meaningful state changes and define producers and consumers for each. For every event, capture: event name (past tense), producer, consumers, business meaning, trigger, expected reactions, business owner, and data requirements. Keep the catalog as a bridge from business to tech; later tie it to topics, schemas, and access policies.
Which functional requirements should be documented for Kafka topics and clients?Document topic names and ownership; producer/consumer identifiers and groups; assignment and consumption model (e.g., server-side assignment, shared groups); partition count and replication factor; retention and compaction; serializers, key field, headers, null-key policy; schema format and evolution compatibility; recommended producer acks and consumer offset strategy. Keep traceability back to the business events in the catalog.
Which nonfunctional requirements matter most, and how do they influence Kafka configuration?Define message size (avg/max) and compression strategy to tune batching, buffers, and costs. Specify latency targets using percentiles (P95/P99, max) per stage and end-to-end. Quantify throughput (expected volume, peaks, patterns, burst handling, growth). Capture security (TLS, at-rest encryption, field masking), data-loss tolerance (critical/important/non-critical), and dead-letter handling (DLT, retries, alerts).
Why should auto-creation of topics and schemas be disabled in shared production clusters?Auto-created topics and schemas use defaults, bypass review, and encourage drift. With multiple teams, this leads to inconsistent settings, weak governance, and no audit trail. Set auto.create.topics.enable and auto.register.schemas to false in production and provision artifacts through controlled, declarative processes.
What does a GitOps workflow for Kafka look like, and how does it handle collaboration and drift?Store the desired Kafka state (topics, ACLs, schemas, connectors) as declarative YAML/JSON in Git. A CI/CD or pull-based tool compares the cluster to Git and applies only the diffs. Use validation and change planning before applying. Consumers propose changes via pull requests; producers (as data owners) review and approve. A periodic validation job detects and reconciles any manual drift.
Which tools support GitOps for Kafka, with and without Kubernetes?Without Kubernetes: Kafka-GitOps, Jikkou, plus IaC like Ansible, Puppet, and Terraform providers. With Kubernetes: represent Kafka artifacts as CRDs and use operators (Strimzi, Confluent for Kubernetes) alongside Argo CD or Flux to sync desired state from Git to the cluster automatically.
How should we structure environments and safely use production data in non-prod?Maintain separate clusters for Dev/UAT/Prod when possible; tune replication and sizing per environment. If sharing a cluster in lower envs, use environment prefixes, separate registries, strict auth/ACLs, and quotas. For UAT with prod-like data, establish a migration pipeline that masks/anonymizes sensitive fields, reshapes to UAT schemas, and updates periodically—not via real-time replication.
How should Kafka applications be tested across unit, integration, streams, and performance?- Unit: test services in isolation with mocks/fakes; for Kafka Streams, use TopologyTestDriver with test topics. - Integration: exercise real client paths. Prefer EmbeddedKafka for lightweight in-memory tests (Spring) or Testcontainers to run real Kafka in Docker; avoid shared dedicated clusters for tests. - Performance: use Kafka perf tools (producer/consumer perf, end-to-end latency) or load tools (JMeter, Gatling, k6) and, for advanced scenarios, Trogdor. Measure throughput and percentile latencies against your nonfunctional targets.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kafka for Architects ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kafka for Architects ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Kafka for Architects ebook for free