Kafka consumers tripled our cross-AZ transfer bill: fixing it with fetch-from-follower
After adding four consumer groups to an MSK cluster, regional data transfer became our third-biggest AWS line item. Consumers always read from partition leaders, two-thirds of them in another AZ. How we measured it with flow logs and fixed it with client.rack set to the AZ ID.
The monthly cost review flagged a line that had never mattered before: EU-DataTransfer-Regional-Bytes in eu-west-1 had grown from about 900 USD to 2,800 USD in one month. Nothing in the architecture diagram had changed except that four new consumer groups (search indexing, fraud features, the data lake sink and an audit service) now read the orders and payments topics on our Amazon MSK cluster.
Our earlier post on cross-AZ traffic between Kubernetes services (post 167) dealt with service-to-service HTTP calls. This time the traffic was Kafka, and the Kubernetes routing fixes from that post do not apply: a Kafka client connects directly to the broker that leads each partition, wherever it is.
Reproducing it
The cluster has three brokers, one per AZ, and every topic uses replication factor 3. Consumer pods run on EKS nodes spread across the same three AZs. With default settings, a consumer fetches every partition from its leader. Leaders are spread evenly across brokers, so for any consumer, about two-thirds of the partitions it reads are led by a broker in another AZ.
What we ruled out
Replication traffic between brokers. MSK does not charge for data transfer between brokers within the cluster, so replication was not on our bill.
NAT gateway. The consumers reach MSK over private IPs in the same VPC; no NAT was involved, and the NAT processing line was flat.
Producers. Producers must write to the leader, so part of their traffic crosses AZs by design. Producer volume had not changed.
Inter-region traffic. The usage type was regional, not inter-region, and the data lake bucket is in the same region.
Root cause
Each consumed byte was being read once per consumer group, and about two-thirds of those reads crossed an AZ boundary, which AWS bills in both directions. Four new groups reading high-volume topics multiplied that traffic. Kafka has supported reading from the closest replica since 2.4 (KIP-392), but it is off by default: the broker needs a rack-aware replica selector, and each consumer must tell the broker where it is through client.rack.
What is happening under the hood
Each partition has one leader and some followers. By default, both producers and consumers talk to the leader. KIP-392 added "fetch from follower": if the broker is configured with replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector, a consumer that sends its client.rack gets redirected to a replica in the same rack, if one is in sync. In the cloud, "rack" means availability zone.
On MSK, the broker's broker.rack is already set by the service to the AZ ID of the broker, such as euw1-az1. AZ IDs are the same across accounts; AZ names such as eu-west-1a are mapped to different physical zones per account. The consumer's client.rack must therefore be the AZ ID too. A consumer that sends eu-west-1a matches no broker rack, and the broker silently falls back to the leader.
The trade-off: a follower only serves data up to the high watermark it has received from the leader, so end-to-end latency can rise slightly, typically by the replication delay. For our consumers (indexing, analytics, audit), a few extra milliseconds did not matter.
Environment
Component | Version / value |
|---|---|
Cluster | Amazon MSK provisioned, Kafka 3.7.x, 3 brokers |
Topics |
|
Consumers | EKS 1.31, Java services on kafka-clients 3.7, one Go service on librdkafka 2.6 via confluent-kafka-go |
Region | eu-west-1 |
Pricing | Cross-AZ data transfer billed per GB in each direction |
Minimal reproduction
Consumer config before the fix (relevant part):
bootstrap.servers=b-1.orders.abc123.c2.kafka.eu-west-1.amazonaws.com:9098
group.id=search-indexer
# no client.rack
Cluster configuration: default, without replica.selector.class.
Measuring it first
We wanted a number per consumer group before and after. VPC Flow Logs with a custom format include the AZ of the ENI that recorded the flow:
${version} ${interface-id} ${az-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${bytes} ${flow-direction} ${start} ${end}
We enabled it on the subnets of the MSK broker ENIs and queried in Athena, joining broker IPs to their AZ ID and pod CIDRs to node AZs:
SELECT b.az_id AS broker_az, c.az_id AS client_az,
sum(f.bytes) / 1e9 AS gb
FROM msk_flow_logs f
JOIN broker_ips b ON f.srcaddr = b.ip
JOIN client_subnets c ON contains(c.cidr, f.dstaddr)
WHERE f.srcport = 9098 AND f.flow_direction = 'egress'
AND f.day = '2027-01-24'
GROUP BY 1, 2
ORDER BY gb DESC;
About 64 percent of broker-to-client bytes went to a client in a different AZ, close to the two-thirds we expected.
The fix
1. Enable the rack-aware selector on the cluster. Create a new MSK configuration revision:
replica.selector.class=org.apache.kafka.common.replica.RackAwareReplicaSelector
aws kafka update-cluster-configuration \
--cluster-arn arn:aws:kafka:eu-west-1:111122223333:cluster/orders/abc123 \
--configuration-info Arn=arn:aws:kafka:eu-west-1:111122223333:configuration/orders-rack/def456,Revision=2 \
--current-version K3AEGXETSR30VB
MSK applies it with a rolling broker restart, so do it in a quiet window.
2. Give each consumer its AZ ID. Pods cannot read node labels through the downward API, so an init container reads the AZ ID from instance metadata and writes it to a shared file:
initContainers:
- name: az-id
image: public.ecr.aws/aws-cli/aws-cli:2.22.0
command: ["sh", "-c"]
args:
- |
T=$(curl -s -X PUT http://169.254.169.254/latest/api/token \
-H 'X-aws-ec2-metadata-token-ttl-seconds: 60')
curl -s -H "X-aws-ec2-metadata-token: $T" \
http://169.254.169.254/latest/meta-data/placement/availability-zone-id > /az/id
volumeMounts:
- { name: az, mountPath: /az }
IMDSv2 from a pod needs the node's metadata hop limit set to 2; check your launch template. The application reads /az/id at startup:
String azId = Files.readString(Path.of("/az/id")).trim(); // e.g. "euw1-az2"
props.put(ConsumerConfig.CLIENT_RACK_CONFIG, azId);
For the Go service, librdkafka uses the same property name, client.rack.
Alternatives and trade-offs
Zone-pinned consumers. Run consumer deployments per AZ and assign partitions by leader location. Fragile: leaders move during broker restarts.
Fewer consumer groups. Fan out once into a stream processor and serve downstream systems from it. Useful, but a bigger redesign.
Compression. Producer-side
compression.type=zstdcut bytes on the wire for both producers and consumers by about 60 percent for our JSON payloads. We did this as well; it stacks with fetch-from-follower.
How to test the fix
Check that a consumer is really fetching from a follower. KIP-392 added a per-partition consumer metric, preferred-read-replica, in the consumer-fetch-manager-metrics group. It reports the broker ID the consumer fetches from, or -1 when it uses the leader. We exported it through the JMX exporter and compared it with the broker-to-AZ map:
kafka.consumer:type=consumer-fetch-manager-metrics,client-id=search-indexer-1,topic=orders,partition=7
preferred-read-replica = 2 # broker 2 is in euw1-az2, same as this pod
A value of -1 on most partitions means client.rack did not match any broker rack. Then compare the flow-log query per AZ pair for a day before and a day after. In staging we also logged client.rack at startup so a wrong value (an AZ name) is visible immediately.
Confirming in production
Three days after rollout, the flow-log query showed 9 percent of broker-to-client bytes crossing AZs (the remainder comes from partitions whose local follower was briefly out of sync, and from producers). In Cost Explorer, daily EU-DataTransfer-Regional-Bytes dropped from about 92 USD to 31 USD per day. End-to-end latency p99 from produce to index rose from 40 ms to 55 ms, within the indexing service's budget.
Regression guard
A startup check in the shared Kafka client library fails fast if
client.rackis empty or does not match the pattern of an AZ ID.The MSK configuration lives in Terraform; a policy test asserts that
replica.selector.classis set for every cluster.A daily cost anomaly monitor on the
DataTransfer-Regional-Bytesusage type alerts the platform team when it grows more than 30 percent week over week.
Security implications
None beyond the usual: the init container only reads instance metadata, and we kept IMDSv2 required. Raising the hop limit to 2 allows pods on the node to reach instance metadata, which they already could through the node role on these nodes. If you use IRSA or EKS Pod Identity and block metadata for pods, read the AZ ID from a node label exposed by a small controller instead.
Prevention checklist
Ask "how many bytes cross an AZ per consumed byte" for every new consumer group.
Enable the rack-aware replica selector on any multi-AZ Kafka cluster with heavy reads.
Use AZ IDs, not AZ names, for
client.rackon AWS.Add compression on producers for text payloads.
Watch regional data transfer as its own cost line with an anomaly monitor.
References
Apache Kafka: KIP-392 Allow consumers to fetch from closest replica — https://cwiki.apache.org/confluence/display/KAFKA/KIP-392%3A+Allow+consumers+to+fetch+from+closest+replica
Apache Kafka: Consumer configs, client.rack — https://kafka.apache.org/documentation/#consumerconfigs_client.rack
AWS: Reduce network traffic costs of your Amazon MSK consumers with rack awareness — https://aws.amazon.com/blogs/big-data/reduce-network-traffic-costs-of-your-amazon-msk-consumers-with-rack-awareness/
AWS: Availability Zone IDs for your AWS resources — https://docs.aws.amazon.com/ram/latest/userguide/working-with-az-ids.html
AWS: VPC Flow Logs records — https://docs.aws.amazon.com/vpc/latest/userguide/flow-log-records.html
AWS: Amazon MSK pricing — https://aws.amazon.com/msk/pricing/
Add a label
Embed this post
<iframe src="https://hibug.me/kafka-cross-az-transfer-cost-fetch-from-follower" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I am an application and cloud security engineer. Most of my day is spent with development teams: reviewing designs, untangling IAM policies, hardening AWS accounts and making security checks fast enough that nobody wants to skip them. I believe security works best when it is concrete. Instead of long lists of best practices, my posts look at one decision at a time: a policy that granted more than intended, a design reviewed before the first line of code, a deletion that did not delete. Each one ends with checks you can run on your own systems.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.