Stream Ingestion with Amazon MSK and Apache Kafka
Kafka is useful at the boundary between systems that produce events and systems that process them. Amazon Managed Streaming for Apache Kafka (MSK) removes much of the broker-operating burden, but it does not choose partition keys, capacity, replication, retention, or consumer recovery policy for you.
This article is dated to Kafka’s mature 2017-era patterns. MSK itself launched later, so the managed-service details below are a current operational translation of the same Apache Kafka design.
A cluster that reflects ownership
Start with a small set of business topics rather than one topic per producer instance. A practical event topic name encodes the domain, entity, and optional major contract version:
orders.events
payments.events
inventory.events.v2
Use separate clusters when isolation is a requirement, not merely a preference. A production cluster commonly has three brokers across three Availability Zones, with client access restricted to private subnets. Keep lower environments in separate clusters or accounts. Place MSK Connect workers, Flink, or application consumers in subnets with routes to every broker subnet and DNS resolution enabled.
For each topic, decide four values explicitly:
| Setting | Initial choice | Why |
|---|---|---|
| Partitions | 12-48 | Enough parallelism for the measured consumer rate, with room to grow |
| Replication factor | 3 | Tolerates one broker or Availability Zone loss |
min.insync.replicas |
2 | Acknowledgements require more than one durable copy |
| Retention | 3-7 days | Allows replay without turning the log into permanent storage |
Partition count is not a throughput dial to turn arbitrarily. More partitions increase open connections, controller metadata, consumer groups, leader elections, and rebalancing work. Size from the busiest entity key and the slowest required consumer. A useful initial ceiling is:
required partitions =
ceil(max(producer MB/s / 10 MB/s, consumer MB/s / 5 MB/s))
Treat these values as load-test inputs, not universal constants. Then add 30 percent headroom and test with the actual message size and compressor.
The physical data path
Kafka ordering exists only within a partition. A key such as order_id sends every event for one order to one partition:
import org.apache.kafka.clients.producer.*;
import java.util.Properties;
Properties producerConfig = new Properties();
producerConfig.put("bootstrap.servers", "b-1.example.kafka.amazonaws.com:9098");
producerConfig.put("security.protocol", "SASL_SSL");
producerConfig.put("sasl.mechanism", "AWS_MSK_IAM");
producerConfig.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
producerConfig.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
producerConfig.put("acks", "all");
producerConfig.put("enable.idempotence", "true");
producerConfig.put("max.in.flight.requests.per.connection", "5");
producerConfig.put("retries", "2147483647");
producerConfig.put("compression.type", "lz4");
producerConfig.put("linger.ms", "10");
try (KafkaProducer<String, String> producer =
new KafkaProducer<>(producerConfig)) {
ProducerRecord<String, String> record =
new ProducerRecord<>("orders.events", orderId, json);
producer.send(record, (metadata, error) -> {
if (error != null) {
throw new IllegalStateException("produce failed", error);
}
});
}
For SASL/IAM, the deployed process also needs the matching Kafka IAM permission and the client library that implements AWS_MSK_IAM. For small teams, a private PLAINTEXT endpoint is easier to debug but is not an appropriate production default. Prefer TLS plus IAM or mutual TLS, and rotate credentials before expiry.
acks=all and idempotence protect against duplicate delivery after a retry at the Kafka producer level. They do not make a downstream database transaction exactly once. Carry a stable event_id and enforce a uniqueness key in the target.
Consumer groups and checkpoints
A consumer group distributes partitions; one partition is processed by at most one live member of a group at a time. Do not auto-commit before work completes:
from kafka import KafkaConsumer
consumer = KafkaConsumer(
"orders.events",
bootstrap_servers=["b-1.example.kafka.amazonaws.com:9098"],
security_protocol="SSL",
group_id="orders-indexer-v3",
enable_auto_commit=False,
auto_offset_reset="earliest",
max_poll_records=200,
)
for message in consumer:
persist_with_upsert(message.key, message.value, message.offset)
consumer.commit()
For a real sink, commit only after the sink transaction records both the business result and the processed topic-partition-offset. Better still, store that offset in the same relational transaction. The sample commit is deliberately simple; if the process crashes after persist_with_upsert but before commit, the event is replayed and must be idempotent.
Set max.poll.interval.ms above the maximum batch processing time, but not so large that a wedged member occupies a partition for hours. Export consumer lag by partition and alert on sustained lag growth, not lag alone: a steady offset is a symptom, while lag that grows faster than the headroom consumer can recover is an incident.
Retention and replay
Kafka retention is based on bytes and time, not application semantics. A seven-day retention.ms means the original event can disappear after seven days even if a consumer has not read it. For long outages, restore from the last compacted/object-store copy or increase retention before recovery begins.
Compacted topics are appropriate for latest-state change streams when every record has a key. They are not a substitute for event-time retention: compaction is asynchronous and null tombstones can eventually remove old keys. Event topics normally need delete retention; state topics can combine compaction with a long delete interval.
Network, security, and failure recovery
Recommended boundaries include:
- broker security groups allowing only client and control-plane traffic from approved source groups;
- private DNS and no public bootstrap endpoint for production;
- service principals with least-privilege topic and group permissions;
- TLS in transit and KMS encryption at rest;
- quotas or backpressure on noisy producers;
- an object-store dead-letter or raw archive for records that no consumer can process.
During an Availability Zone loss, a three-replica topic continues if the remaining replicas satisfy min.insync.replicas. An acks=all producer may receive NotEnoughReplicas until a second in-sync copy returns. Retrying indefinitely preserves future data only if the producer buffers and reestablishes leadership; it also risks exhausting memory. Bound queues and expose dropped/failed counts.
If the cluster is healthy but a consumer repeatedly fails, pause that partition, publish the bad record with topic, partition, offset, key, exception class, and correlation ID to a dead-letter topic, and advance the original offset only after durable quarantine. Never silently skip.
Trade-offs that operations can measure
| Goal | Stronger choice | Cost |
|---|---|---|
| Durability | acks=all, replication 3, ISR 2 |
Higher latency and reduced availability during double failure |
| Throughput | Larger batches, compression, linger | Larger append batches and slightly higher produce latency |
| Ordering | One key on one partition | Hot-key bottlenecks and limited parallelism |
| Long replay | Longer retention and larger storage | Higher broker storage and recovery traffic |
| Low broker cost | Fewer/larger partitions and shorter retention | Less isolation, concurrency, and replay |
Track at least:
- p99 produce latency below the producer service-level objective, for example 250 ms;
- request errors below 0.1 percent over five minutes;
BytesInPerSecbelow 60 percent of benchmarked sustained capacity;- consumer lag recovering within two normal peak hours;
- under-replicated partitions at zero outside maintenance;
- offline partitions at zero, paged immediately.
Kafka is an append-only recovery mechanism, not a queue where the broker owns business correctness. Correctness comes from partitioning, acknowledged writes, idempotent consumers, explicit checkpoints, and rehearsed recovery against measured limits.