Skip to content

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

Shock Absorber Pattern

The shock absorber pattern uses Kafka as a buffer between systems with different throughput capacities. Kafka absorbs traffic spikes, allowing downstream systems to process at their own sustainable rate without being overwhelmed.


Backend systems—databases, mainframes, third-party APIs—do not need to be provisioned for peak capacity. They only need to handle the average throughput, with Kafka absorbing the difference during spikes.

ComponentWithout KafkaWith Kafka
DatabaseProvisioned for peak loadProvisioned for average load
Application serversAuto-scale to handle spikesFixed pool at steady capacity
Downstream APIsRate limiting / request rejectionSteady, predictable load

This translates directly to:

  • Lower infrastructure costs — Smaller database instances, fewer application servers
  • Predictable performance — No degradation during traffic spikes
  • Simplified capacity planning — Plan for average, not peak
  • Reduced operational complexity — No auto-scaling policies to tune

The shock absorber pattern introduces latency between when data is produced and when it reaches the backend system. During traffic spikes, this delay can grow significantly as the buffer fills.

The pattern works best for short-lived spikes where the buffer can drain during quieter periods:

Spike PatternSuitabilityReason
Flash sales (minutes to hours)ExcellentBuffer drains overnight
Daily peaks (predictable hours)ExcellentOff-peak hours allow catch-up
Sustained high load (days/weeks)PoorBuffer never drains, lag grows indefinitely
Gradual permanent increasePoorRequires capacity increase, not buffering

Before adopting this pattern, assess whether traffic spikes are temporary or represent a sustained increase in load. If the latter, the solution is to scale the backend, not buffer indefinitely.

Systems where delayed updates are acceptable:

  • Analytics and reporting pipelines
  • Search index updates
  • Data warehouse loading
  • Notification delivery
  • Audit log processing
  • Cache warming
  • Real-time transaction processing requiring immediate confirmation
  • Systems where users expect instant visibility of changes
  • Low-latency trading or bidding systems
  • Sustained load increases (requires actual scaling)

A car’s suspension system provides the perfect analogy. When the wheel hits a speedbump (traffic spike), the spring compresses (Kafka buffers messages) and the damper controls the release rate (consumer processes at steady pace). The car body (backend system) experiences a smooth ride regardless of road conditions.

Spring and Damper Analogy

In signal processing terms, Kafka acts as a low-pass filter (or IIR filter). High-frequency spikes in the input signal are attenuated, while the underlying trend passes through smoothly to the output.

Input signal: producer message rate with spikes Output signal: consumer message rate smoothed by Kafka A consumer with a controlled processing rate can smooth bursts while records accumulate in Kafka. The buffer is finite, and Kafka does not set the consumer rate automatically.

The following chart illustrates the smoothing effect in practice:

Throughput Smoothing: Kafka as Shock Absorber

TimeProducer RateConsumer RateLag TrendBackend Load
00:001,000/s1,000/s—1,000/s
06:002,000/s2,000/s—2,000/s
12:0012,000/s2,000/s↑↑ Peak2,000/s
18:003,000/s2,000/s↑ Growing2,000/s
24:001,000/s1,000/s— Stable, not necessarily empty1,000/s

Key insight: Accumulated lag changes with the difference between producer and consumer rates. In this example the producer rate never falls below the consumer rate, so accumulated lag does not drain. Draining requires the consumer to process faster than new records arrive, within available retention and storage capacity.


Systems rarely produce and consume data at identical rates:

The Rate Mismatch Problem Common scenarios:

ScenarioProducer RateConsumer CapacityProblem
Flash sales100x normalFixed database IOPSDatabase saturation
Log ingestionVaries with trafficFixed Elasticsearch clusterIndex rejections
IoT telemetrySensor burstsLimited analytics pipelineProcessing delays
Batch jobsBulk exportsRate-limited APIsAPI throttling
Event-drivenCascading eventsLegacy system limitsSystem crashes

Kafka’s architecture naturally supports load leveling:

Kafka as Shock Absorber Key properties:

  1. Durable buffer - Messages persist until consumed (or retention expires)
  2. Decoupled rates - Producers and consumers operate independently
  3. Horizontal scaling - Add partitions for higher throughput
  4. Configurable retention - Buffer size measured in time or bytes

Legacy systems (mainframes, older databases) often cannot scale elastically. Kafka shields them from modern traffic patterns.

Protecting Legacy Backend Implementation:

public class RateLimitedConsumer {
private final RateLimiter rateLimiter;
private final LegacyClient legacyClient;
private final Consumer<String, Event> consumer;
public RateLimitedConsumer(int maxTps) {
this.rateLimiter = RateLimiter.create(maxTps);
}
public void consume() {
while (running) {
ConsumerRecords<String, Event> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, Event> record : records) {
// Block until rate limit allows
rateLimiter.acquire();
try {
legacyClient.process(record.value());
} catch (RateLimitException e) {
// Backend is struggling - pause consumption
consumer.pause(consumer.assignment());
Thread.sleep(backoffMs);
consumer.resume(consumer.assignment());
}
}
consumer.commitSync();
}
}
}

Collect events during high-traffic periods, process in efficient batches during low-traffic periods.

Batch Aggregation Pattern Configuration:

# Topic retention sized for batch window
log.retention.hours=48
log.retention.bytes=-1
# Consumer for batch processing
max.poll.records=10000
fetch.max.bytes=52428800
enable.auto.commit=false

Different consumers process the same events at different rates based on their capabilities.

Multi-Speed Consumers

In the shock absorber pattern, temporary consumer lag is expected. Monitor its size, age and drain rate against retention, storage and processing requirements.

Consumer Lag During Traffic Spike

Calculate required retention based on expected spike patterns:

Buffer Size = (Peak Rate - Consumer Rate) × Spike Duration
Example:
- Peak rate: 10,000 msg/s
- Consumer rate: 2,000 msg/s
- Spike duration: 2 hours
Buffer = (10,000 - 2,000) × 7,200 seconds = 57.6 million messages
With 1KB average message size:
Payload storage needed = 57.6M × 1KB = ~58 GB across the buffered records
Per-partition usage depends on distribution; allow for replication and overhead

Retention configuration:

# Time-based retention (for predictable spike patterns)
log.retention.hours=72
# Size-based retention (for storage constraints)
log.retention.bytes=107374182400 # 100 GB per partition
# Combined (whichever triggers first)
log.retention.hours=72
log.retention.bytes=107374182400
# Prometheus alerting rules for shock absorber pattern
groups:
- name: kafka-shock-absorber
rules:
# Alert on lag growth rate, not absolute lag
- alert: ConsumerLagGrowingTooFast
expr: |
rate(kafka_consumer_group_lag[5m]) > 1000
for: 15m
labels:
severity: warning
annotations:
summary: "Consumer lag growing rapidly"
description: "Lag increasing by {{ $value }}/s - verify this is expected"
# Alert if lag approaches retention limit
- alert: ConsumerLagApproachingRetention
expr: |
kafka_consumer_group_lag / kafka_topic_partition_current_offset
> 0.8
for: 30m
labels:
severity: critical
annotations:
summary: "Consumer may lose messages"
description: "Lag at 80% of available buffer - messages at risk"
# Alert if lag not draining during off-peak
- alert: ConsumerLagNotDraining
expr: |
kafka_consumer_group_lag > 1000000
and hour() >= 2 and hour() <= 6
for: 2h
labels:
severity: warning
annotations:
summary: "Lag not draining during off-peak"
description: "Expected lag to decrease overnight"

When consumers cannot keep up even during normal periods, implement backpressure.

public class BackpressureConsumer {
private static final long LAG_THRESHOLD = 1_000_000;
private static final long RESUME_THRESHOLD = 100_000;
private final AdminClient adminClient;
private boolean paused = false;
public void consumeWithBackpressure() {
while (running) {
long currentLag = getCurrentLag();
if (!paused && currentLag > LAG_THRESHOLD) {
// Too far behind - pause to let downstream recover
consumer.pause(consumer.assignment());
paused = true;
notifyUpstream("SLOW_DOWN");
log.warn("Paused consumption - lag {} exceeds threshold", currentLag);
}
if (paused && currentLag < RESUME_THRESHOLD) {
// Caught up enough to resume
consumer.resume(consumer.assignment());
paused = false;
notifyUpstream("READY");
log.info("Resumed consumption - lag {} below threshold", currentLag);
}
if (!paused) {
ConsumerRecords<String, Event> records = consumer.poll(Duration.ofMillis(100));
processRecords(records);
} else {
// Still paused - sleep to avoid busy loop
Thread.sleep(1000);
}
}
}
}
public class AdaptiveBatchConsumer {
private int currentBatchSize = 1000;
private static final int MIN_BATCH = 100;
private static final int MAX_BATCH = 10000;
public void consumeAdaptively() {
while (running) {
ConsumerRecords<String, Event> records = consumer.poll(Duration.ofMillis(100));
long startTime = System.currentTimeMillis();
int processed = processBatch(records, currentBatchSize);
long duration = System.currentTimeMillis() - startTime;
// Adjust batch size based on processing time
if (duration < 100 && currentBatchSize < MAX_BATCH) {
// Processing fast - increase batch size
currentBatchSize = Math.min(currentBatchSize * 2, MAX_BATCH);
} else if (duration > 1000 && currentBatchSize > MIN_BATCH) {
// Processing slow - decrease batch size
currentBatchSize = Math.max(currentBatchSize / 2, MIN_BATCH);
}
consumer.commitSync();
}
}
}

Route high-priority messages to a fast lane that’s always processed, while low-priority messages buffer.

The shock absorber pattern can smooth resource usage. Whether it saves money depends on the workload, instance pricing and Kafka storage costs.

Auto-Scaling Cost Pattern

Shock Absorber Cost Pattern In these illustrative examples, the steady pool uses 240 instance-hours versus 210 for auto-scaling, so it does not demonstrate a compute saving. At 1,500 messages/s per instance, ten consumers also have enough nominal capacity for the stated 10,000 messages/s peak.

Cost comparison:

ApproachCompute CostOperational ComplexityRisk
Auto-scalingVaries with capacity and pricingScaling policies requiredScale-up latency
Shock absorberVaries with steady capacity, pricing and Kafka storageFixed pool and buffer managementMust size buffer

Anti-Pattern: Undersized Buffer

// WRONG: Assuming consumer keeps up
@KafkaListener(topics = "events")
public void consume(Event event) {
// No rate limiting
// No health checks
// No backpressure
database.insert(event); // What if DB is slow?
}
// RIGHT: Health-aware consumption
@KafkaListener(topics = "events")
public void consume(Event event, Acknowledgment ack) {
if (!healthChecker.isDownstreamHealthy()) {
// Don't ack - message will be redelivered
throw new RetryableException("Downstream unhealthy");
}
rateLimiter.acquire();
try {
database.insert(event);
ack.acknowledge();
} catch (Exception e) {
// Let Kafka retry
throw new RetryableException(e);
}
}
AspectRecommendation
Buffer sizingPeak rate × spike duration × safety margin
RetentionTime or size based on drain requirements
Consumer rateMust exceed average producer rate
Lag alertingAlert on growth rate, not absolute value
BackpressurePause/resume, adaptive batching, or priority lanes
MonitoringBuffer utilization, drain time, rate delta

The shock absorber pattern transforms unpredictable traffic into predictable processing load, enabling cost optimization, protecting legacy systems, and improving overall system resilience.