Kafka
Message Updating
Data Streaming
Apache Kafka
Topic Management

How to update a message in a Kafka topic

Codemia Knowledge Hub ·

You can't edit a record that is already in a Kafka topic, because Kafka keeps an append-only log of immutable records. To "update" a message, publish a new message with the same key and the updated value, and let consumers treat the latest value for a key as current. This differs from a traditional database, where an update overwrites the existing row in place; in Kafka the consuming logic decides how to process and store updates based on their keys.

Topics, keys and records

A topic is a named feed that producers publish records to. Topics are multi-subscriber: zero, one or many consumers can read the same data independently. The data in a topic is stored as a series of records (messages), and each record has a key, a value and a timestamp. The key is what lets you express an update.

Publishing an update under the same key

Take a topic user_updates where each message key is a user ID and the value is the user's latest data (name, email and so on). When a user changes their email, the producer publishes a new message with the same user ID as key and the new email in the value.

Consumers of user_updates keep only the latest state per user ID, for example in a local store or a database, replacing the previous record for that user each time a newer one arrives.

Log compaction keeps the latest value per key

Kafka's log compaction guarantees that the log retains at least the last known value for each key. A key updated many times keeps only its most recent value; older values can be discarded. This suits "state" topics and any topic where the full history of changes is not needed.

FeatureDescription
Retention of latest valueOnly the most recent value for each key is retained.
Deletion of old recordsOlder records for a key are deleted, reducing storage requirements and improving read performance.
SuitabilityIdeal for state-oriented data where only the latest snapshot is necessary.

Practices for update-style topics

  1. Consistent keys: give every message about the same entity the same key, so updates map to the right entity.
  2. Compacted topics: enable log compaction on topics with frequent updates to save storage and speed up reads.
  3. Idempotent consumers: handle duplicates so processing an update twice does not change the outcome.
  4. Event sourcing: if you use event sourcing, record every change (updates included) as its own immutable event instead of overwriting state.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design