Skip to content

AxonOps — AI-Native Control Plane for Open Source Data Platforms

Kafka Memory Management

Memory architecture and optimization for Apache Kafka brokers and clients.


Broker memory layout: JVM heap, off-heap memory, and OS page cacheBroker memory layout: JVM heap, off-heap memory, and OS page cacheServer MemoryJVM HeapOff-HeapOS Page CacheRequestHandlingMetadataCacheIndexStructuresDirectBuffersMappedFilesLogSegmentsIndexFilesSized via -XmxManaged by GCManaged by OSCritical for performance

ComponentDescriptionMemory Impact
Request buffersIncoming/outgoing request dataProportional to connections
Metadata cacheTopic/partition metadataProportional to partitions
Index structuresIn-memory index pointersProportional to partitions
Producer stateIdempotent producer trackingProportional to producers × partitions
Group coordinatorConsumer group stateProportional to groups/members

Heap Footprint Estimates (Repository Guidance)

Section titled “Heap Footprint Estimates (Repository Guidance)”
AreaRule of Thumb
Broker heap per partition replica~1-2 MB
Controller metadata heap~5 GB for typical clusters
Cluster SizePartitionsHeap Size
Small< 1,0004-6 GB
Medium1,000-10,0006-8 GB
Large10,000-50,0008-12 GB
Very Large> 50,00012-16 GB
Terminal window
# Example JVM settings (tune per workload)
export KAFKA_HEAP_OPTS="-Xms6g -Xmx6g"
# GC settings (example values)
export KAFKA_JVM_PERFORMANCE_OPTS="-server \
-XX:+UseG1GC \
-XX:MaxGCPauseMillis=20 \
-XX:InitiatingHeapOccupancyPercent=35 \
-XX:+ExplicitGCInvokesConcurrent \
-XX:G1HeapRegionSize=16M \
-XX:MetaspaceSize=96m \
-XX:MinMetaspaceFreeRatio=50 \
-XX:MaxMetaspaceFreeRatio=80"

Kafka relies heavily on the OS page cache for performance. The page cache stores recently accessed disk data in RAM.

Consumer fetch served from the OS page cacheConsumer fetch served from the OS page cacheRead PathConsumerBrokerPage CacheDiskHot data served from memoryNo disk I/O for recent messagesfetch requestresponseread datareturn datacache miss

Rule of thumb: Reserve at least as much RAM for page cache as data you want to keep “hot” (typically last few hours of data).

Page Cache = Total RAM - JVM Heap - OS Overhead
Example:
Total RAM: 64 GB
JVM Heap: 6 GB
OS/Other: 2 GB
Page Cache: ~56 GB available
Terminal window
# Check memory usage
free -g
# Check page cache usage
cat /proc/meminfo | grep -E "Cached|Buffers|MemFree|MemTotal"
# Monitor disk I/O (high I/O = cache misses)
iostat -x 1

Kafka uses buffer pools to reduce garbage collection overhead.

# Broker network buffer sizing
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600

Default Memory/Buffer Limits (Kafka Defaults)

Section titled “Default Memory/Buffer Limits (Kafka Defaults)”
ComponentSettingDefault
Brokersocket.send.buffer.bytes102400
Brokersocket.receive.buffer.bytes102400
Brokersocket.request.max.bytes104857600
Producerbuffer.memory33554432
Producerbatch.size16384
Producerlinger.ms0
Producermax.block.ms60000
Consumerfetch.min.bytes1
Consumerfetch.max.bytes52428800
Consumerfetch.max.wait.ms500
Consumermax.partition.fetch.bytes1048576
Topicindex.interval.bytes4096
Producer buffer pool and record accumulator recyclingProducer buffer pool and record accumulator recyclingProducerBuffer PoolRecordAccumulatorFreeBuffersBatch 1Batch 2Batch 3buffer.memory controls pool sizeReused to avoid GC pressureallocatebatchingrecycle after send
# Producer buffer configuration (example tuning)
buffer.memory=33554432 # 32MB total buffer pool
batch.size=16384 # 16KB per batch
linger.ms=5 # Wait time for batching
# Consumer fetch sizing
fetch.min.bytes=1 # Minimum bytes to fetch
fetch.max.bytes=52428800 # Maximum per fetch (50MB)
max.partition.fetch.bytes=1048576 # Per partition (1MB)

Symptoms:

  • OutOfMemoryError
  • GC taking > 10% of time
  • Request latency spikes

Causes:

CauseSolution
Too many partitionsReduce partitions or increase heap
Large metadata cacheReduce topic count
Producer state buildupReduce idempotent producers
Memory leakUpdate Kafka version

Symptoms:

  • High disk read I/O
  • Consumer latency increases
  • await time in iostat high

Causes:

CauseSolution
Heap too largeReduce heap, leave more for cache
Too much dataAdd more brokers
Random access patternsImprove consumer patterns

Terminal window
# Recommended G1GC settings
-XX:+UseG1GC
-XX:MaxGCPauseMillis=20
-XX:InitiatingHeapOccupancyPercent=35
-XX:G1HeapRegionSize=16M
ParameterPurpose
MaxGCPauseMillisTarget pause time (20ms recommended)
InitiatingHeapOccupancyPercentWhen to start concurrent GC
G1HeapRegionSizeRegion size (16M for larger heaps)
Terminal window
# Enable GC logging
-Xlog:gc*:file=/var/log/kafka/gc.log:time,tags:filecount=10,filesize=100M
# Monitor GC
jstat -gc <pid> 1000
# Analyze GC log
# Look for: pause times, frequency, throughput

GC Monitoring Targets (Repository Guidance)

Section titled “GC Monitoring Targets (Repository Guidance)”

Use GC pause time, frequency, and throughput as trend indicators rather than fixed SLAs.


Kafka uses direct memory for network I/O operations.

Terminal window
# Configure direct memory limit (example)
-XX:MaxDirectMemorySize=2g

Index files use memory-mapped I/O:

# These files are memory-mapped
# .index - offset index
# .timeindex - timestamp index

# Total memory for buffering
buffer.memory=33554432
# Memory allocation behavior
max.block.ms=60000 # Block when buffer full

Memory calculation:

Required memory = buffer.memory +
(partitions × batch.size overhead) +
compression buffers
# Fetch sizing
fetch.max.bytes=52428800
max.poll.records=500

Memory calculation:

Required memory = fetch.max.bytes +
deserialization buffers +
record processing buffers

  • Set heap size appropriately (6-12GB typical)
  • Leave sufficient RAM for page cache
  • Configure G1GC with appropriate pause target
  • Monitor GC pause times and frequency
  • Watch for page cache evictions
  • Size buffer.memory for throughput needs
  • Set appropriate batch.size
  • Monitor buffer-available-bytes metric
  • Configure fetch sizes appropriately
  • Set max.poll.records for processing capacity
  • Monitor memory usage in application