Event Flattening
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A Debezium change event is an envelope. Its value has before, after, source, op and timestamps, as described
on Anatomy of a Change Event. That richness is what a migration
needs in Kafka: the operation type tells a consumer whether to insert, update or delete, before allows comparisons,
and source gives the position in the legacy transaction log.
Many consumers outside Debezium expect something simpler: one record per row, whose fields are the row’s columns.
Generic Kafka Connect sinks (search indexes, object storage, analytics databases, other vendors' JDBC sinks), ksqlDB
or Flink tables, and a lot of hand-written consumers read records in that shape. Event flattening is the Debezium
SMT that produces it. The official name is New Record State Extraction, and the class is
io.debezium.transforms.ExtractNewRecordState. For MongoDB there are two counterparts:
ExtractNewDocumentState, which flattens a document event, and MongoToRelationalMapper, which projects documents to
fixed relational columns.
This page explains when to flatten during a migration, every option of the three transformations, and what each delete-handling mode does to the target database. SMTs in general, and the other Debezium transformations, are on Debezium Transformations.
Checked on 2026-11-09 against Debezium 3.7.1.Final. The configuration on this page is derived from the official
documentation and was not run against a live connector, except the MongoToRelationalMapper sink, which the lab on
MongoDB Connector ran.
Do you need it at all?
The most common reason to flatten, writing change events to a relational table with a JDBC sink, does not apply to
the Debezium JDBC sink. The official JDBC sink documentation says that the connector consumes native Debezium change
events directly, extracting the after section of inserts and updates and using delete events and tombstones for
deletes. bookshop-pg-mirror-sink, which copies BOOK, AUTHOR and SUPPLIER_CATALOGUE into the legacy_* tables,
therefore has no transforms at all (see JDBC Sink Connector).
Flattening is needed for:
-
Other sink connectors that only understand flat records.
-
Consumers that only want state, such as a cache or a search index that is rebuilt from the latest value of each key.
-
Compacted "current state" topics, where each key’s last record (or tombstone) is the row’s state.
It is usually not what the anti-corruption layer wants. LegacyBookTranslator and LegacyOrderProjector decide
what to do from op, compare before and after, and record source positions in processed_change for
idempotency (see Listening to Events in
Applications). Flattening removes all of that unless you add it back with add.fields.
Where to apply it: source or sink
You can configure ExtractNewRecordState on the Debezium source connector or on a sink connector that reads its
topics. The official page recommends the sink when you want Kafka to keep the original events, and that is the right
choice in a migration:
-
With the SMT on
bookshop-oracle-source, every consumer oflegacy.BOOKSHOP.*receives flat records. The JDBC sink still works, but the translators loseopandbefore, and replaying the topic can never recover them. -
With the SMT on the sink, Kafka holds the full events and only that sink sees the flat version.
If a consumer that is not a Kafka Connect sink needs flat records, either flatten in its code, or run a second, cheap pipeline (for example a Kafka Streams application, or Debezium Server with the SMT) that writes flat copies to separate topics. Never flatten the source topics of a migration just to make one consumer simpler.
What the transformation does
For each data change event the SMT replaces the value with the content of after, and the value schema with the
schema of after. The key is not changed. What happens to a delete depends on delete.tombstone.handling.mode,
explained below. Records that are not change events (heartbeats, schema change events) pass through unchanged, but
apply the SMT selectively with a predicate anyway, as the official page recommends.
A legacy price change in BOOKSHOP.BOOK arrives as this value (JSON converter, embedded schema omitted):
{
"before": { "BOOK_ID": "1001", "ISBN": "9780000000017", "TITLE": "Patterns of Legacy", "AUTHOR_ID": "17",
"PRICE": "12.50", "CURRENCY": "EUR", "PUBLISHED": 1262304000000, "ACTIVE_FLG": "Y",
"SUPPLIER_ID": "3", "LAST_UPD": 1762646400000 },
"after": { "BOOK_ID": "1001", "ISBN": "9780000000017", "TITLE": "Patterns of Legacy", "AUTHOR_ID": "17",
"PRICE": "13.90", "CURRENCY": "EUR", "PUBLISHED": 1262304000000, "ACTIVE_FLG": "Y",
"SUPPLIER_ID": "3", "LAST_UPD": 1762689600000 },
"source": { "connector": "oracle", "name": "legacy", "db": "FREEPDB1", "schema": "BOOKSHOP", "table": "BOOK",
"ts_ms": 1762689600000, "scn": "3017264", "...": "..." },
"op": "u",
"ts_ms": 1762689601234
}
Reference: Debezium — Oracle connector update events
Every NUMBER column, BOOK_ID and PRICE included, is a JSON string, because the Bookshop source uses
decimal.handling.mode=string. With the precise default, BOOK_ID would be a number and PRICE the Base64
encoding of the unscaled decimal bytes. The trade-offs of the decimal modes are on
Data Types & Precision. The real value is wrapped as
{"schema":...,"payload":...}, because the source keeps schemas embedded; the example shows the payload part.
After ExtractNewRecordState with add.fields=op,table,source.ts_ms:
{
"BOOK_ID": "1001", "ISBN": "9780000000017", "TITLE": "Patterns of Legacy", "AUTHOR_ID": "17",
"PRICE": "13.90", "CURRENCY": "EUR", "PUBLISHED": 1262304000000, "ACTIVE_FLG": "Y",
"SUPPLIER_ID": "3", "LAST_UPD": 1762689600000,
"__op": "u",
"__table": "BOOK",
"__source_ts_ms": 1762689600000
}
Reference: Debezium — Event flattening, adding metadata
A complete sink-side configuration
The configuration below adds flattening to a sink connector that reads the three mirrored legacy topics. Only the
transforms and predicates keys are Debezium-specific; replace the connector class and its own properties with
those of the sink you use.
{
"name": "bookshop-legacy-search-sink",
"config": {
"connector.class": "<the sink connector class>",
"topics": "legacy.BOOKSHOP.BOOK,legacy.BOOKSHOP.AUTHOR,legacy.BOOKSHOP.SUPPLIER_CATALOGUE",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "true",
"value.converter.schemas.enable": "true",
"transforms": "unwrap",
"transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
"transforms.unwrap.delete.tombstone.handling.mode": "rewrite",
"transforms.unwrap.add.fields": "op,table,source.ts_ms,source.scn",
"transforms.unwrap.add.headers": "op",
"transforms.unwrap.predicate": "isLegacyTable",
"predicates": "isLegacyTable",
"predicates.isLegacyTable.type": "org.apache.kafka.connect.transforms.predicates.TopicNameMatches",
"predicates.isLegacyTable.pattern": "legacy\\.BOOKSHOP\\..*"
}
}
The sink’s Connect worker needs the Debezium SMT classes. They ship in every Debezium connector archive and in the
quay.io/debezium/connect:3.7.1.Final image. On a worker that runs only a third-party sink, put the JARs of a
Debezium connector (or the Debezium core JARs) in that sink’s plug-in directory, because Kafka Connect isolates
plug-ins from each other.
Adding metadata: add.fields and add.headers
Flattening removes op, source and the timestamps. add.fields puts selected metadata back into the value and
add.headers puts it into Kafka headers. Both take a comma-separated list without spaces.
-
A plain name such as
op,table,lsnorscnis looked up in the event and in itssourceblock. -
When a name exists twice (for example
ts_msat the top level and insource), qualify it:source.ts_ms. -
A name can be renamed with
<field_name>:<new_field_name>, for examplesource.ts_ms:EVENT_TIMESTAMP. -
Added fields and headers are prefixed with
__(change it withadd.fields.prefixandadd.headers.prefix), and for a qualified name an underscore is inserted between the struct and the field:source.ts_msbecomes__source_ts_ms. -
A field listed in
add.fieldsthat does not exist in the event is still added (with anullvalue). A header listed inadd.headersthat does not exist is not added. -
Metadata is added to deletes only when
delete.tombstone.handling.modekeeps the delete as a record, that isrewriteorrewrite-with-tombstone.
Useful metadata for a migration:
| Field | Why you want it |
|---|---|
|
Distinguishes a snapshot read ( |
|
Lets one sink handle several topics, or route by table after a topic routing SMT has merged them. |
|
When the change was committed in the legacy database, which is what replication lag is measured against (see Monitoring, Logging & Tracing). |
|
The log position. A consumer can store it to skip duplicates after a restart, as the |
delete.tombstone.handling.mode
A delete in the legacy database produces two records: a delete event (op: "d", with before and after: null)
and a tombstone (same key, null value) that lets Kafka log compaction remove the key. ExtractNewRecordState must
decide what to keep, because a flat record cannot say "deleted" on its own. In Debezium 3.7 this is controlled by one
option, delete.tombstone.handling.mode. The older drop.tombstones and delete.handling.mode options have been
removed, so old configurations that still use them must be rewritten.
| Value | Records left for one legacy delete | Effect on a target table written from the flat records |
|---|---|---|
|
The tombstone only (the delete event is dropped). |
A sink that deletes on a |
|
Nothing. |
The target never learns about deletes. Only acceptable for append-only legacy tables or when deletes are handled another way. |
|
One record: the |
The sink upserts the row with |
|
The rewritten record, then the tombstone. |
The sink first marks the row as deleted, then (if it deletes on tombstones) removes it. Compaction still works. |
|
One tombstone, converted from the delete event; the original tombstone is removed. |
Like |
The mode is the most important flattening decision in a migration, because it decides whether deletes in the legacy database reach the new one at all. Test it with a real delete (see the verification section) before you trust a pipeline.
Dropping unchanged fields
drop.fields.header.name names a header that contains a list of fields to remove from the flat value. Combined with
the event changes SMT, which writes the list of unchanged fields into a header, it produces records that contain only
the columns an update changed. A sink that applies partial updates then does not overwrite columns that the legacy
statement did not touch.
transforms=changes,unwrap
transforms.changes.type=io.debezium.transforms.ExtractChangedRecordState
transforms.changes.header.unchanged.name=Unchanged
transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState
transforms.unwrap.drop.fields.header.name=Unchanged
transforms.unwrap.drop.fields.from.key=false
transforms.unwrap.drop.fields.keep.schema.compatible=true
The order matters: changes must run before unwrap, because it needs before and after.
drop.fields.keep.schema.compatible=true (the default) removes only optional fields, so a NOT NULL column such as
BOOK_ID stays. drop.fields.from.key=true would remove listed fields from the key as well, which you rarely want.
Partial records only help if every update has a complete before image: for Oracle, enable supplemental logging of all
columns on the captured tables.
Routing by a column value: route.by.field
route.by.field sends each flattened record to the topic named by a field of after (or of before for a delete).
If a legacy SUPPLIER_CATALOGUE table had a column naming the target feed, route.by.field=<that column> would
send each row to a topic of that name. On a sink connector, where the topic name often becomes the table name, this
lets one connector write to several tables. It is a blunt instrument: the topic names come straight from data, so
validate the values first, and prefer the content-based router (see
Debezium
Transformations) when you need an expression.
replace.null.with.default
replace.null.with.default (default true) replaces a null value with the default value that the source column
declares. This is usually what you want, but in a migration it can hide a difference: if a legacy column
ACTIVE_FLG CHAR(1) DEFAULT 'Y' contains a real NULL in some old rows, the flattened records show 'Y' and
reconciliation against the legacy table will report a mismatch that the pipeline introduced. Set it to false when
the target must reproduce NULL values exactly.
All options
| Option | Default | Description |
|---|---|---|
|
|
|
|
none |
Field of |
|
|
Prefix of the metadata fields added to the value. |
|
none |
Metadata fields to add to the value, comma-separated, no spaces, with optional
|
|
|
Prefix of the metadata headers. |
|
none |
Metadata fields to add as headers. |
|
none |
Header that lists fields to remove from the value. |
|
|
Also remove those fields from the key. |
|
|
Remove only optional fields. |
|
|
Replace |
A consumer that reads flat records
When a consumer reads flattened records, its code shrinks to a map of columns plus the metadata you added. The
listener below is a Spring for Apache Kafka 4.1 consumer for a hypothetical flattened copy of legacy.BOOKSHOP.BOOK
(topic legacy.flat.BOOK, JSON without schemas). It shows how the __op and __deleted fields replace the
envelope.
package com.example.bookshop.migration;
import java.util.Map;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class FlatLegacyBookListener {
private final BookCache cache;
public FlatLegacyBookListener(BookCache cache) {
this.cache = cache;
}
@KafkaListener(topics = "legacy.flat.BOOK", groupId = "bookshop-book-cache")
public void onBook(Map<String, Object> row) {
if (row == null) {
return; // tombstone: with rewrite-with-tombstone the delete was already handled
}
// decimal.handling.mode=string: every Oracle NUMBER, BOOK_ID included, arrives as a JSON string
long bookId = Long.parseLong(String.valueOf(row.get("BOOK_ID")));
if ("true".equals(String.valueOf(row.get("__deleted")))) {
cache.evict(bookId);
return;
}
// __op is "r" for snapshot reads, "c" for inserts and "u" for updates
cache.put(bookId, (String) row.get("TITLE"), "Y".equals(row.get("ACTIVE_FLG")));
}
/** The application's own cache abstraction. */
public interface BookCache {
void put(long bookId, String title, boolean active);
void evict(long bookId);
}
}
The listener assumes a JsonDeserializer-style value deserializer that produces a Map, and that __deleted is a
string, which is how the official examples show it. Check the exact JSON your converter writes before you rely on the
type. Consumer configuration, error handling and idempotency are covered on
Spring Boot and Kafka and
Listening to Events in Applications.
MongoDB: ExtractNewDocumentState
The MongoDB connector emits before and after as JSON strings that contain Extended JSON, not as structs, because
documents have no fixed schema. io.debezium.connector.mongodb.transforms.ExtractNewDocumentState parses after and
turns it into a typed Kafka Connect struct, so a typical sink can consume it. The official page shows it on sink
connectors that consume the MongoDB connector’s topics. In the Bookshop example it applies to
legacy-mongo.bookshop.reviews, produced by bookshop-mongo-source (see MongoDB
Connector).
transforms=unwrap
transforms.unwrap.type=io.debezium.connector.mongodb.transforms.ExtractNewDocumentState
transforms.unwrap.array.encoding=array
transforms.unwrap.flatten.struct=true
transforms.unwrap.flatten.struct.delimiter=_
transforms.unwrap.delete.tombstone.handling.mode=rewrite
transforms.unwrap.delete.tombstone.handling.mode.rewrite-with-id=true
transforms.unwrap.add.fields=op,collection,source.ts_ms
transforms.unwrap.add.headers=op
transforms.unwrap.field.name.adjustment.mode=avro
| Option | Default | Description |
|---|---|---|
|
|
|
|
|
|
|
|
Flatten nested documents into top-level fields ( |
|
|
Delimiter used by |
|
|
|
|
|
With |
|
|
As for |
|
|
As above; for example |
|
|
|
The main limitation for a document-to-table migration: fields with the same name must have the same type in every document of the collection, and nested documents and arrays produce nested or flattened fields whose set changes from document to document. A relational sink then sees a different schema for each event. When the target table has fixed columns, use the relational mapping SMT instead.
MongoDB: MongoToRelationalMapper
io.debezium.connector.mongodb.transforms.MongoToRelationalMapper converts the JSON strings in before and after into
structs and keeps the Debezium envelope: the key, op, source and headers are unchanged. Because the envelope is
kept, the Debezium JDBC sink applies its normal upsert and delete handling to the result. The official page recommends
applying it at the JDBC sink, so that Kafka keeps the original MongoDB events and a MongoDB sink can still consume them.
For each collection you configure a projection: a JSON object under schema.mapping.<database>.<collection> whose
members name output columns, with a JSON Pointer path into the document and a Kafka Connect type. The database and
collection are matched exactly against source.db and source.collection.
The Bookshop example is the legacy bookshop.reviews collection, which the lab of the
MongoDB Connector page moves into PostgreSQL. A review document looks
like this:
db.getSiblingDB("bookshop").reviews.insertOne({
bookId: NumberLong("1001"), // legacy BOOK.BOOK_ID
customerLegacyId: NumberLong("501"), // legacy CUSTOMER.CUST_ID
rating: 5,
title: "A classic",
body: "Read it twice.",
createdAt: ISODate("2019-03-14T10:15:00Z"),
helpfulVotes: 12,
tags: ["classic", "gift"]
});
The target is the PostgreSQL table book_review, the same table as on the MongoDB Connector page. The sink writes it
with primary.key.mode=record_key, so its primary key is the record key’s id field: the MongoDB connector’s
serialized identifier ({"$oid": "..."}), which the SMT does not re-key. The other columns come from the projection,
and document_json keeps the whole document, so that fields the new model does not use yet (such as tags) are not
lost.
CREATE TABLE book_review (
id text PRIMARY KEY, -- the Debezium key: the _id as extended JSON
book_id bigint,
customer_legacy_id bigint,
rating smallint,
title text,
body text,
helpful_votes integer,
created_at timestamptz,
document_json jsonb
);
Reference: Debezium — JDBC sink primary key handling
{
"name": "bookshop-pg-review-sink",
"config": {
"connector.class": "io.debezium.connector.jdbc.JdbcSinkConnector",
"tasks.max": "1",
"topics": "legacy-mongo.bookshop.reviews",
"connection.url": "jdbc:postgresql://postgres:5432/bookshop",
"connection.username": "bookshop",
"connection.password": "bookshop",
"insert.mode": "upsert",
"primary.key.mode": "record_key",
"primary.key.fields": "id",
"delete.enabled": "true",
"schema.evolution": "none",
"collection.name.format": "book_review",
"use.time.zone": "UTC",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "true",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": "true",
"transforms": "map",
"transforms.map.type": "io.debezium.connector.mongodb.transforms.MongoToRelationalMapper",
"transforms.map.schema.mapping.bookshop.reviews": "{\"book_id\":{\"path\":\"/bookId\",\"type\":\"int64\"},\"customer_legacy_id\":{\"path\":\"/customerLegacyId\",\"type\":\"int64\"},\"rating\":{\"path\":\"/rating\",\"type\":\"int16\"},\"title\":{\"path\":\"/title\",\"type\":\"string\"},\"body\":{\"path\":\"/body\",\"type\":\"string\"},\"helpful_votes\":{\"path\":\"/helpfulVotes\",\"type\":\"int32\"},\"created_at\":{\"path\":\"/createdAt\",\"type\":\"org.apache.kafka.connect.data.Timestamp\"},\"document_json\":{\"path\":\"\",\"type\":\"io.debezium.data.Json\"}}"
}
}
This is the configuration that the MongoDB Connector lab ran. The projection value, unescaped and readable:
{
"book_id": { "path": "/bookId", "type": "int64" },
"customer_legacy_id": { "path": "/customerLegacyId", "type": "int64" },
"rating": { "path": "/rating", "type": "int16" },
"title": { "path": "/title", "type": "string" },
"body": { "path": "/body", "type": "string" },
"helpful_votes": { "path": "/helpfulVotes", "type": "int32" },
"created_at": { "path": "/createdAt", "type": "org.apache.kafka.connect.data.Timestamp" },
"document_json": { "path": "", "type": "io.debezium.data.Json" }
}
How the rules of the SMT shape this configuration:
-
Converters must carry schemas. The SMT expects a schemaful envelope, so the MongoDB source connector must also write schema-enabled JSON (or Avro or Protobuf). Turning schemas on at the sink cannot recover them from schemaless records.
-
Paths are JSON Pointers into the document, not into the envelope.
/_idselects the id; Extended JSON wrappers are not fields, so/_id/$oidis wrong. An empty path ("") selects the whole document. -
Types are Kafka Connect types. Primitive names (
int32,int64,string,boolean, …) are case-insensitive; logical types such asorg.apache.kafka.connect.data.Timestamp,org.apache.kafka.connect.data.Decimal(withscaleand optionalprecision) andio.debezium.data.Jsonmust be fully qualified. An ObjectId converts tostring; documents and arrays needio.debezium.data.Json. -
Mixed-type arrays must be mapped to JSON. An array that holds a string and a number (
["classic", 2019]) cannot be a Connect array; map it toio.debezium.data.Json, or leave it todocument_jsonas the Bookshop projection does withtags. -
Missing paths become
null. All output fields are optional, so an upsert clears a column whose source field has disappeared. A value that exists but cannot be converted (for example aratingstored as"five") raises an error instead of becomingnull. -
Unmatched collections fall back to schema inference. If the database or collection name in
schema.mapping.<database>.<collection>is misspelt, the SMT does not complain: it infers a schema per event. Check the property name againstsource.dbandsource.collectionof a real event. -
Updates need full documents. Set
capture.mode=change_streams_update_full(orchange_streams_update_full_with_pre_image) onbookshop-mongo-source. Partial update events are not reconstructed. -
json.output.mode=input(default) keeps the incoming JSON text as it is;canonicalreserializes it as MongoDB Extended JSON v2 canonical. -
Output names must match
[A-Za-z_][A-Za-z0-9_]*.document_jsoncontains every field of the document, including fields that the projection leaves out, so do not rely on omission to keep personal data out of the target.
To know which projected columns an update changed, run ExtractChangedRecordState after map (with
change_streams_update_full_with_pre_image and MongoDB pre-images enabled, so that before is available).
Verifying a flattening configuration
Flattening bugs are silent: the pipeline runs, and the target slowly diverges. Check every operation type once, with a known row:
-
Insert, update and delete one row in the legacy table, for example a test
BOOKwithBOOK_ID = 999001. -
Read the sink’s input topic with a console consumer that prints keys, headers and
nullvalues, and confirm that the delete produces exactly the records the chosendelete.tombstone.handling.modepromises. -
Query the target: the row must exist after the insert, have the new values after the update, and be gone (or have
__deleted = true) after the delete. -
Look for
NULLversus default differences in columns withDEFAULTclauses (replace.null.with.default).
kafka-console-consumer.sh --bootstrap-server localhost:9092 \
--topic legacy.BOOKSHOP.BOOK --from-beginning \
--formatter-property print.key=true --formatter-property print.headers=true \
--formatter-property print.partition=true --formatter-property null.literal=TOMBSTONE
Reference: Apache Kafka 4.3 — Basic Kafka operations
Row-count and checksum reconciliation between the legacy and the new database is covered on Verification & Reconciliation.