Analyze with AI
Get AI-powered insights from this Mad Devs article:
Consider an illustrative online store. Its order system confirms a purchase, a Kafka producer publishes an order-confirmation event, and a consumer updates a status table. The store's API then exposes that confirmation to the customer. During peak sales, customers wait too long to see the new status. Consumer group lag rises, and the team proposes additional brokers. The Head of Engineering needs evidence that this purchase will shorten the wait. This article follows that single flow through measurement, competing changes, and release checks so you can approve a defined fix. All measurements and thresholds below are hypothetical.
Key takeaways
- Evaluate Kafka performance tuning against the time customers wait for a correct result. Improving a technical metric alone does not establish that the business requirement passes.
- Measure the producer, brokers, consumer, and downstream write separately to identify which stage limits completion during the affected window.
- Compare proposed changes under the same workload and database constraints. Require recovery and correctness checks alongside the speed test before authorizing production rollout.
Define what counts as a fast order confirmation
The store requires at least 98% of confirmed orders to appear correctly in the status API within 15 seconds. The clock starts when the source system commits the order confirmation. It stops when the customer-facing API returns the correct new status. Kafka acknowledgment, consumer receipt, and database commit are intermediate milestones.
Attach a stable event ID to each confirmation and carry it through publication, processing, and the status record. Record timestamps at those boundaries and synchronize the participating clocks. In the test, an API observer checks each order using the same polling interval and observation method for every candidate. Its resolution must be recorded: polling cannot reveal the exact instant between observations when a status became visible. Avoid selecting a faster observer for the favored change.
Count every confirmed order in the acceptance population. An order without a correct API result by its deadline is late, even if it eventually succeeds. Calculate end-to-end latency from matched event observations; adding stage percentiles does not produce an end-to-end percentile because the slowest events can differ across stages.
Limit the investigation to one topic, one consumer group, and one status table. Before testing, the backend lead records the normal and peak arrival profiles, while the database owner approves connection, write-load, and lock-wait limits. The process owner accepts the customer threshold. These agreements distinguish acceptance criteria from diagnostic signals such as fetch duration and lag measured in records.
Trace the delay across producers, brokers, and consumers
Start with the affected peak window and compare it with a healthy window for the same order-confirmation flow. The broader method for finding application performance bottlenecks applies here, but the investigation follows each event through Kafka to its visible status.
| Stage | Compare within the same peak window | Observation in the illustrative store |
|---|---|---|
| Producer | Time from order confirmation to event submission and Kafka acknowledgment | Publication stays within its normal range; retry counts remain stable |
| Brokers | Produce/fetch request latency, throttling, broker utilization, and partition distribution | Broker metrics remain within their normal ranges; no persistent partition skew appears |
| Consumer group | Read and completion rates, lag by partition, time between polls, and group state | Lag grows across several partitions as completed processing slows |
| Status write and API | Time from receipt to database commit, then from commit to API visibility | Most additional delay occurs before database commit; API visibility after commit stays normal |
Make the origin of each signal explicit. Application traces supply producer, handler, and database timings; the API observer supplies visibility timestamps. Broker JMX request metrics supply broker request latency and queue time. Consumer instrumentation supplies poll intervals and completed-processing counts. A group-offset collector compares partition end offsets with committed offsets to report consumer group lag separately; offset differences need not equal an exact count of records.
This distinction matters when dashboards include the client metric records-lag-max. Apache Kafka 4.1 monitoring documentation defines it using the current position, rather than the committed offset. It is not interchangeable with the group's committed-offset lag.
In this store, the consumer opens a separate database transaction for every event. Traces show transaction completion slowing during the peak, limiting the rate of finished status updates. This supports testing a change to writes. It does not establish that every Kafka delay has the same cause.
Persistent broker-side request waiting or throttling aligned with the start of lag would prioritize a broker or quota investigation instead. Here, healthy broker observations and delayed database commits give the team a concrete competing hypothesis to test before buying capacity.
Test broker capacity and consumer writes on the same workload
Use an isolated environment to replay 5,000 order confirmations spanning the recorded normal and peak intervals. Each candidate receives the same load replay, including arrival timing and key distribution. Keep partition count, replication, write semantics, API observation, and database limits unchanged. Restore the initial database state, group offsets, and relevant cache state between runs.
The broker candidate must represent usable additional capacity. Redistribute the existing partitions and leaders beforehand, verify that traffic reaches the added resources, and finish redistribution before measuring. Otherwise, unchanged results could simply mean the new brokers received no meaningful work.
| Candidate | Correct status visible within 15 seconds | What the test establishes |
|---|---|---|
| Current configuration | 4,100 / 5,000 – 82% | The original delay is reproduced |
| Added broker capacity, current consumer | 4,150 / 5,000 – 83% | Added capacity does not meet the requirement for this workload |
| Same brokers, bounded batches of consumer writes | 4,940 / 5,000 – 98.8% | This candidate passes the threshold on the test workload |
Passing requires 4,900 timely results out of 5,000. All confirmations remain in the denominator, including those without a result at the deadline. Preserve the input manifest and event-level outcomes so the backend lead can reproduce these counts.
Bounded batches help this example by reducing the number of separate database commits. Set both a maximum batch size and a maximum accumulation time; waiting indefinitely to fill a batch would undermine the latency requirement. Select those limits through measurements under the agreed database constraints.
These illustrative counts support a consumer-write pilot for this flow. They establish neither universal superiority for batching nor that broker capacity can never become limiting. Repeat comparable runs to assess variability, record database pressure and recovery time after the peak, and retain failed outcomes. A passing sample becomes a release candidate only after the correctness checks below.
Verify correctness before changing the production consumer
Treat speed and recovery as separate acceptance gates. The backend lead owns the consumer tests; the database owner verifies durable writes and resource limits. Both retain event IDs and expected statuses so a lower lag graph cannot conceal missing or incorrect results.
First, interrupt processing before the database transaction commits. After recovery and redelivery, every expected status must appear. Inspect committed offsets for each affected partition to confirm that the consumer did not advance beyond unprocessed records. Include a failed batch, rather than testing only a clean shutdown, and reconcile the final table against the complete input manifest.
Second, stop the consumer after database commit but before offset acknowledgment. Redeliver the affected events and verify that the write path recognizes the stable event ID, or uses equivalent durable protection. Persist duplicate detection and the status update atomically so a crash cannot separate their outcomes. A repeat must create no second result. Include a pre-existing newer status for an affected order and verify that replay cannot overwrite it. Record deduplication and version-check behavior at the database boundary; successful consumption alone does not prove either property.
In this design, automatic offset commits are disabled. The consumer advances the committed offset within each partition only after confirmed database writes cover a continuous sequence of processed records. It commits the next position after that sequence and never skips a failed record because later work finished. Offsets need not be consecutive. Partition ownership changes must preserve that rule.
The Kafka 4.2 KafkaConsumer API describes the failure window between database insertion and offset commit: recovery can repeat the insert. The store therefore tests repeat-safe database behavior without claiming a universal exactly-once guarantee for an external database. For the broader consistency design, see data synchronization best practices.
Third, run the peak-window acceptance test separately from these interruption drills. Verify the 98% deadline, reconcile all eventual statuses, and check approved database limits. Passing recovery drills cannot substitute for passing the latency test, and faster writes cannot waive recovery failures.
Scope the fix and define the rollout decision
Fund the consumer change in this illustrative store. The tested scope includes bounded database batches, durable duplicate protection, ordering checks, recovery tests, and rollout preparation. Additional broker capacity stays outside this project because the tested expansion did not achieve the customer threshold.
Compare the expense categories before approval. Added cluster capacity introduces recurring cloud charges and operational work. The consumer option requires implementation, testing, and deployment effort, followed by maintenance of the changed write path. The replay supports choosing the latter scope here; it supplies no price estimate or guaranteed savings. Ask for an estimate against the tested design and its acceptance gates.
Begin with one preselected traffic segment only if routing and record ownership allow isolation. The consumer owner must show that the pilot and existing version cannot concurrently own conflicting writes for the same orders. If that cannot be established, redesign the pilot boundary before launch. Assign the consumer owner responsibility for deployment and offsets, the database owner responsibility for load and stored results, and the process owner responsibility for the customer deadline.
Agree on the production observation window and what constitutes a sustained breach before starting. Stop expansion for incorrect statuses, database-limit violations, or sustained failure of the latency threshold. Execute the rehearsed rollback to the previous consumer version. Before restarting, reconcile open records, database state, and processing positions so the rollback does not skip unfinished work or corrupt a newer status.
The previous version restores known behavior and may restore the original peak-time lateness. The process owner must accept that residual delay beforehand. Keep the replay package, recovery evidence, configuration, and rollback instructions with the release record.
The decision is specific: the passing replay and recovery checks authorize a limited consumer-write pilot. Expansion requires production evidence that the same correctness, latency, and database conditions hold.
Decide what to hand to a delivery partner
Before committing to implementation, commission a diagnosis with inspectable outputs. A partner should reconstruct this one flow, reproduce its peak workload, and compare the broker-capacity and consumer-write hypotheses. The deliverable is a measured limiting stage, reproducible comparison, and recommended scope with acceptance criteria. Request the event manifest, observation method, and test configuration alongside the recommendation so your team can challenge the conclusion.
After the decision, implementation can cover bounded batches, replay protection, load validation, and the release and rollback procedure. Handover should identify who investigates late confirmations, how to reconcile unfinished work, and which measurements trigger escalation. If the evidence instead identifies a cluster constraint, configuration and infrastructure changes become a separate scope with their own validation.
You can retain implementation internally and purchase only measurement or independent acceptance testing. Separate those responsibilities in the statement of work, including who provides test access and who signs off on correctness. This makes the paid outcome clear even when the partner does not change production code.
External work of this kind has a public precedent. In its Paysolut case study, SoftKraft describes reviewing an existing Kafka system and carrying out stabilization and data-storage and processing improvements. That supplier-published account supports the scope of an external engagement. It does not substantiate the hypothetical store's measurements or represent a Mad Devs Kafka project.
Conclusion
Take one recent production peak window and select the order-confirmation events that missed the customer deadline. Match their IDs to source confirmation, publication, completed database writes, and API visibility. Use that evidence to name the first limiting-stage hypothesis and define the user-visible threshold its test must pass. Then compare the proposed change under the same input and database constraints. A budget request can now identify the flow, the observed constraint, the tested improvement, and the conditions for a limited release.
Backend Development Fix your Kafka pipeline bottleneck Mad Devs can improve event processing and verify throughput and latency under peak load. Discuss your project |






