Estuary

Kafka to MotherDuck: Batch Loading, Message Keys & Tombstones Guide

Load Kafka to MotherDuck with Iceberg tables, an S3 sink, your own consumer or a managed pipeline. Compare 4 methods and how each batches topics.

Apache Kafka to MotherDuck integration guide cover showing the Apache Kafka and MotherDuck logos
Share this article

Apache Kafka topics reach MotherDuck in four ways: let the Kafka platform write them as Apache Iceberg tables that MotherDuck attaches (Confluent Tableflow, Redpanda Iceberg Topics), sink them to object storage as Parquet and read the files, run your own consumer or a code tool such as dlt or ingestr, or use a managed pipeline. Every path batches, and MotherDuck's own guidance is that latency is minutes, not milliseconds. Iceberg suits platforms that already write it, an S3 sink works with any Kafka distribution, code fits a few topics, and a managed pipeline fits many topics or several sources.

Two choices decide the result: whether each topic is keyed (one current row per key, tombstones as deletes) or an append-only event stream, and how many rows each load carries. Estuary supports this route with a Kafka capture that reads topics continuously into a durable collection and a MotherDuck materialization that stages files in your bucket and loads them on a sync schedule you set.

Choosing a Kafka to MotherDuck method

Which Kafka platform you run, whether it already writes Iceberg, and how many topics you load decide the method.

ApproachBest fitFreshnessOperational burdenExample implementation
Iceberg tables written by the Kafka platformConfluent Cloud; Redpanda on BYOC/BYOVPC or self-managed with an Enterprise licenseCommit interval (Tableflow: about every 5 minutes)Low: maintenance falls to the platformTableflow or Iceberg Topics, attached as an Iceberg database
Object storage sinkAny Kafka distribution, no catalogSink file rotation plus your load scheduleMedium: Connect cluster, file sizing, load jobsKafka Connect S3 sink, then read_parquet
Your own consumer or a code toolA few topics, a Python or CLI teamYour batch intervalMedium to high: you run the consumerPyArrow batches, dlt, ingestr --stream
Managed pipelineMany topics, or Kafka plus other sourcesContinuous capture, scheduled loadsLow: configuration and a bucketEstuary

How Kafka topics become MotherDuck tables

Per-message inserts are the most expensive way into MotherDuck, so every method batches in four stages and differs only in who runs them and where the batch waits.

  • Consume. A client reads partitions and records its position.
  • Decode. JSON needs nothing else. Avro and Protobuf from Confluent serializers carry a magic byte and a 4-byte schema ID, resolved against the schema registry.
  • Batch. Messages wait in a Parquet file, an Iceberg commit, or an in-memory Arrow table.
  • Load. MotherDuck runs INSERT INTO … SELECT over an Arrow batch, read_parquet over new files, or queries an attached Iceberg catalog.

The table design follows the topic. An event stream appends: each message is a row, identified by topic, partition and offset. A keyed topic carries state: a later message replaces the earlier one for its key, and a null-value message (a tombstone) deletes it, so one row per key needs a merge on the key, in the loader or a view.

Kafka partitions batched as Iceberg, Parquet or Arrow, then attached or loaded by MotherDuck.
Per-message inserts are the most expensive way into MotherDuck, so every method batches first.

Kafka requirements

Whatever loads MotherDuck connects to the brokers as an ordinary Kafka client, from its own network.

  • Reachable brokers. The bootstrap servers and every advertised broker address, not only the first one dialled.
  • Authentication over TLS. SASL/SCRAM or SASL/PLAIN when self-managed; PLAIN with a cluster API key on Confluent Cloud, whose Schema Registry has its own key; IAM on Amazon MSK (port 9098 inside AWS, 9198 public).
  • ACLs. Read and describe on each topic, plus the consumer group if the tool commits offsets.
  • Format per topic. Avro and Protobuf need the producers' schema registry; under Confluent's default TopicNameStrategy a <topic>-key subject describes the key.
  • Retention must outlast the longest outage you plan to recover from. Tombstones survive compaction only for delete.retention.ms (24 hours by default).

MotherDuck requirements

MotherDuck needs a database, a loader token and, for file and Iceberg paths, a bucket it can read.

  • Database and token.CREATE DATABASE for the target, and a Read/Write access token (the default type) for the loader.
  • Bucket and secret. The bucket belongs in your MotherDuck organization's AWS region (MotherDuck runs in six), without dots in its name, which break SSL; register it with CREATE SECRET.
  • Table per topic type. Event tables carry topic, partition and offset columns; latest-value tables are keyed on the message key. A PRIMARY KEY enables INSERT … ON CONFLICT, but its index slows writes and must fit in memory.
  • Iceberg catalogs attach as databases and accept merge-on-read writes, but MotherDuck can't compact them or expire snapshots.

Setting up Kafka to MotherDuck replication

This walk-through uses a Kafka Connect S3 sink, because MotherDuck documents it and it works with any Kafka distribution.

  1. Profile each topic: format, registry subjects, keyed or not, messages per hour.
  2. Configure the S3 sink with ParquetFormat and an Avro, Protobuf or JSON Schema converter; plain JsonConverter can't write Parquet. A time-based partitioner on record timestamps with flush.size and rotate.interval.ms keeps the sink's exactly-once file output; rotate.schedule.interval.ms flushes quiet topics on the clock but gives that up.
  3. Carry Kafka coordinates in the data with an InsertField transform (topic.field, partition.field, offset.field). Keys go only to separate files (store.kafka.keys), so latest-value tables need the key inside the value.
  4. Decide what tombstones do.behavior.on.null.values defaults to fail, stopping the sink at the first one; set ignore, or write with store.kafka.keys=true.
  5. Create the secret and load with the SQL below. union_by_name lines up files from before and after a schema change; DuckDB's filename column records what's loaded.
  6. Build latest-value tables with a view or scheduled rebuild that keeps the highest offset per key and drops keys whose last message was a tombstone.
  7. Validate. Compare row counts with partition offsets, look for repeated (topic, partition, offset) rows, and watch file counts per prefix.
sql
CREATE SECRET IN MOTHERDUCK ( TYPE S3, KEY_ID 'AKIA…', SECRET '…', REGION 'us-east-1' ); -- First load CREATE TABLE orders_events AS SELECT *, filename FROM read_parquet('s3://kafka-sink/topics/orders/**/*.parquet', union_by_name = true); -- Later loads: only files not seen before INSERT INTO orders_events BY NAME SELECT *, filename FROM read_parquet('s3://kafka-sink/topics/orders/**/*.parquet', union_by_name = true) WHERE filename NOT IN (SELECT DISTINCT filename FROM orders_events);

Skip the Sink and the Load Jobs

Estuary reads your Kafka topics and loads MotherDuck in batches on a schedule you set. Topics with a registered key schema merge into one row per key.

What happens after the initial load?

  • Replays. Consumers that commit offsets after writing are at-least-once, and producers retrying without idempotence can write a message twice. Deduplicate on (topic, partition, offset), or merge on a key in the data.
  • Updates on keyed topics replace earlier rows only where a merge on the key runs; appended files keep every version.
  • Tombstones. No file load deletes MotherDuck rows. Tableflow's upsert mode removes a key's row on a tombstone; its append mode keeps every record, and Redpanda documents no tombstone handling for Iceberg Topics.
  • Compacted topics. A reader far behind sees only each key's latest value, and misses deletes once tombstones expire.
  • Schema changes.read_parquet with union_by_name reads new fields as extra columns, Iceberg tables evolve, and native tables need ALTER TABLE … ADD COLUMN before INSERT … BY NAME fills them.
  • Small files from frequent flushes slow every scan; rewrite them periodically, or let the platform compact Iceberg.

Kafka to MotherDuck data type mapping

DuckDB types decide whether amounts, times and nested payloads stay usable after the load.

Kafka message fieldMotherDuck (DuckDB) typeNotes
Avro int, long; JSON integersINTEGER, BIGINTIntegers past 64 bits need HUGEINT
Avro decimalDECIMAL(p,s)DuckDB allows up to 38 digits
Avro float, double; JSON non-integer numbersFLOAT, DOUBLEInexact; DOUBLE holds about 15 significant digits
Avro timestamp-millis, timestamp-microsTIMESTAMPTZAn instant; display follows the session time zone
Avro record, nested JSON objectsSTRUCT or JSONJSON absorbs new nested fields
Avro array, JSON arraysLIST or JSON
Avro bytes, binary keysBLOB

Decimals that arrive as doubles

Amounts routed through JSON numbers or Python floats are rounded past about 15 significant digits, and sums drift. Keep Avro decimal as DECIMAL(p,s) end to end; if the field arrives as text, store VARCHAR and cast in a view. Values already rounded to DOUBLE can't be recovered.

Performance, latency and MotherDuck cost

Freshness is the time a batch waits (sink rotation, Iceberg commit, consumer buffer) plus the load interval. Cost comes mostly from how often compute wakes up and how many files each load reads.

Batch size and load interval

MotherDuck advises against single-row INSERT INTO … VALUES and executemany, which sends single-row inserts too. From a client library, load at least 100,000 rows per chunk, a million or more for throughput, and keep each transaction under about a minute. Set the load interval to the freshness people use; for the newest events within seconds, query Kafka or a stream processor such as Flink, which can also pre-aggregate high-volume topics.

File size on the sink path

MotherDuck's S3 guidance is 10–256 MB per Parquet file, loaded no more often than every 5–15 minutes. A sink rotating every few seconds on a quiet topic writes kilobyte files that each cost a request to list and open.

Production considerations

  • Retries and recovery. Resume from committed offsets or the loader's checkpoint, and keep loads idempotent: file-name tracking on the sink path, offset deduplication elsewhere.
  • Source impact. Each loader is one more consumer on the brokers; partitions cap how many can share a topic.
  • Deletes. Decide per keyed topic whether a tombstone removes, marks or is ignored, and test it.
  • Type changes. Changing a column's type on a large MotherDuck table runs an ALTER and an UPDATE over every row, which can exhaust the instance's memory; settle types before tables grow.
  • Backfills. A backfill of history needs a new consumer group or an offset reset, within retention.
  • Monitoring. Alert on consumer lag, time since the last load and files per prefix, not only row counts.
  • Security. TLS with SASL or IAM, a dedicated token, and a bucket policy scoped to the loader.

Common problems and troubleshooting

Duplicate rows after a consumer restart or replay

A consumer that crashes after writing a batch but before committing offsets writes it again. Find the copies:

sql
SELECT kafka_topic, kafka_partition, kafka_offset, count(*) AS copies FROM orders_events GROUP BY ALL HAVING count(*) > 1;

Delete the extras, or query through a view with QUALIFY row_number() OVER (PARTITION BY kafka_topic, kafka_partition, kafka_offset) = 1. To prevent it, track loaded files by name, or merge on those columns when loading from code.

Deleted keys still appear in MotherDuck

An S3 sink set to ignore drops tombstones and write stores them under a separate prefix; neither touches MotherDuck rows. Check whether the key's last message was a tombstone, then exclude those keys in the latest-value view or delete them in the scheduled merge. On Tableflow, deletes need a compacted topic in upsert mode.

S3 sink fails on Parquet, or scans slow down over time

ParquetFormat with JsonConverter fails with a NullPointerException; use the Avro, Protobuf or JSON Schema converter so records carry a schema. If read_parquet slows each week, count files under the prefix, raise flush.size or rotate.interval.ms, and compact old files.

Using Estuary for Kafka to MotherDuck

On this route, the Apache Kafka capture feeds the MotherDuck materialization, which stages gzipped JSON files in your S3, GCS or Azure bucket and loads them in one MotherDuck transaction per sync. Against the concepts above:

  • Keys. With a schema registry and a usable <topic>-key schema, the collection is keyed on the message key. Otherwise it's keyed on _meta/partition and _meta/offset: every message is its own row, and a tombstone is one more row with _meta/op = d, not a delete.
  • Offsets. New topics are read from the earliest retained offset. Positions live in Estuary's checkpoint, not in committed offsets, so consumer-group lag tools won't show the capture; its logs report how far behind it is every 5 minutes.
  • Loads. On standard bindings, each sync deletes the rows of changed keys and inserts their new versions, in the transaction that records the checkpoint. Delta Update bindings only insert, skipping the lookup of existing rows.
  • Sync schedule. 30 minutes by default once caught up, from 0s to 4 hours; backfills ignore it.
  • Deletes. Soft by default (_meta/op = d); Hard Delete removes rows on standard bindings. Delta bindings never delete: with Hard Delete off each delete becomes a row, and with it on, their delete events are dropped.
  • Types. Inferred from the messages, not the registered value schema: integers become BIGINT, other numbers and numeric strings (Avro decimals arrive as strings) DOUBLE, objects and arrays JSON, date-time strings TIMESTAMP WITH TIME ZONE. New top-level fields become columns. An Avro double that has only carried whole numbers is typed as an integer, so its first fraction converts the column to DOUBLE in place, rewriting the table; mixed types become JSON.
  • Limits. No mutual TLS, custom CA or SSH tunnel; no Avro or JSON schemas that reference other subjects (Protobuf imports work); a zero-length message value fails the capture.

Estuary's security page lists SOC 2 Type II, HIPAA and GDPR.

Implementing Kafka to MotherDuck with Estuary

These steps adapt Estuary's general data flow guide to this route.

  1. Complete the prerequisites in Kafka requirements and MotherDuck requirements. Estuary also needs:
    • Broker access from Estuary's IP addresses, and a <topic>-key schema for each topic that should keep one row per key.
    • A staging bucket in S3 (or Cloudflare R2), GCS or Azure Blob Storage, with read and write credentials.
  2. Create the Kafka capture. On the Sources page, click New Capture, choose Apache Kafka, name the capture, and fill in the endpoint properties:
    • Bootstrap Servers: comma-separated host:port pairs.
    • Credentials: SASL (User & Password) with SASL Mechanism (PLAIN for Confluent Cloud, or SCRAM-SHA-256/SCRAM-SHA-512; the form starts blank), Username and Password; or AWS MSK IAM with an access key pair and AWS Region.
    • TLS Settings: system_certificates, the only value.
    • Schema Registry: Confluent Schema Registry with its endpoint, username and password (the API key and secret on Confluent Cloud), or No Schema Registry for JSON-only topics.
Apache Kafka capture form with SASL credentials and a Confluent Schema Registry, secrets redacted.
  1. Select topics. Click Next. Estuary discovers the topics and lists one binding per topic under Output Collections, each with a Topic field.
    • Remove topics you don't want, including another broker's internal topics.
    • Keep Automatically keep schemas up to date on, for schema evolution as topics and fields appear.

Click Save and publish. Long retention means a large first backfill.

  1. Create the MotherDuck materialization. On the capture's details page, click Materialize, choose MotherDuck, and fill in the endpoint properties:
    • Motherduck Service Token (Read/Write), Database and Database Schema (default main).
    • Hard Delete: on to remove rows when a keyed topic sends a tombstone; off keeps them with _meta/op = d.
    • Staging Bucket Configuration: S3 (S3 Staging Bucket with no dots in the name, keys, S3 Bucket Region, and Custom Endpoint for R2), GCS or Azure.
MotherDuck endpoint form with the token redacted and the S3 staging bucket fields filled in.
  1. Choose the sync schedule. Under Sync Schedule, Sync Frequency defaults to 30 minutes, with options from 0s to 4h; shorter means fresher tables and more MotherDuck queries. Timezone, Fast Sync Start Time, Fast Sync Stop Time and Fast Sync Enabled Days confine the sync schedule to business hours, with 4-hour syncs outside.
MotherDuck Sync Schedule section with the Sync Frequency dropdown open.
  1. Set up each topic's table. Click Next and pick a naming convention. Each binding under Source Collections has Table, Alternative Schema and Delta Update:
    • Topics keyed on the message key: leave Delta Update off, so each key keeps one current row.
    • Event streams keyed on partition and offset: turn Delta Update on. Every key is already unique, so the rows are the same without the per-sync row lookup.
    • JSON topics without a registry that need one row per record: in Field Selection, click Group By and choose the identifying value field. Tombstones carry no value fields, so they won't delete those rows.
    • Kafka metadata:_meta/op and flow_published_at are selected automatically; click Require for others, such as _meta/topic or _meta/timestamp/creationTime.
    • Column types: in the binding's fields.include, set castToString: true on Avro decimal fields to keep their exact text (cast it in a view), and a DDL override of DOUBLE on fields that may carry fractions, so a later fraction doesn't rewrite the column. Overrides apply only when a column is created. JSON-number amounts are doubles already: DECIMAL(18,2) gives an exact column but can't restore lost digits.
  2. Publish. Click Save and publish. Estuary creates the MotherDuck tables and loads the backfill without waiting for the schedule.
  3. Verify that data is landing.
MotherDuck materialization Overview: Connector Status Running and a Data Read chart.

How Estuary handles message keys, topic retention and extra destinations

Each topic lands in a collection, whose history Estuary keeps as JSON files in a cloud storage bucket you can own. Materializations read that, not Kafka, so MotherDuck tables can be rebuilt or extended without touching the brokers.

Latest-value tables and event tables from one capture

Keyed topics and event streams share one capture and one materialization: registered-key topics reduce to one row per key, the rest append. The checkpoint is written in the same MotherDuck transaction as the table changes, so a restart never re-applies a committed sync. Duplicates a producer wrote to the topic still arrive, each with its own offset; a Group By on an event ID field, with Delta Update off, collapses them.

Rebuilding a MotherDuck table after topic retention has passed

SituationRe-reads Kafka?What to do
A MotherDuck table was dropped or its column types must changeNoBackfill that binding of the materialization; MotherDuck is refilled from stored documents
Another warehouse or database should get the same topicsNoA second materialization reads stored history first, then tails new messages
Messages already past Kafka retentionNo, while the collection holds themMaterialization backfill
New topic added to the captureYes, from the earliest retained offsetHistory older than retention isn't captured

The limits: replay depends on collection retention (trial buckets keep about 20 days; use your own bucket for full history), and a re-backfill duplicates delta-update tables.

MotherDuck and other destinations from one Kafka read

To send Kafka to MotherDuck and another system, add a second materialization on the same collections; the brokers serve one read. The MotherDuck connector also writes to a DuckLake database, detecting the type when it connects, and database or SaaS captures can feed the same MotherDuck database.

When another approach may make more sense

  • Already on Confluent Cloud or Redpanda BYOC: Tableflow or Iceberg Topics need no separate pipeline; MotherDuck attaches the catalog. Maintenance stays with the platform, since MotherDuck doesn't compact Iceberg, and Redpanda documents no tombstone handling.
  • A few topics and a Python team: dlt (verified Kafka source; merge into MotherDuck) or ingestr with --stream, which commits offsets only after a successful flush. Without --stream, ingestr reads the backlog present at start and stops, and its default replace strategy rebuilds the table each run.
  • Sub-second dashboards on the newest events: query Kafka or a stream processor; MotherDuck serves the analytical history.
  • An S3 sink already writing Parquet: add a read_parquet load job. You own file sizing, deduplication and tombstones, and recovery is bounded by topic retention.

To try the route, see the Apache Kafka to MotherDuck integration or create a Kafka capture in the Estuary dashboard. Pricing: estuary.dev/pricing.

FAQs

    What is the best tool to move data from Kafka to MotherDuck?

    It depends on your Kafka platform, whether it already writes Iceberg, how many topics you load, and who runs the consumer. Tableflow's Iceberg tables have been generally available on AWS since March 2025, and its upsert tables, which apply tombstones, since October 2025. Estuary fits when Kafka is one of several sources feeding MotherDuck.
    MotherDuck has no Kafka extension, and its Kafka documentation routes Kafka Connect users through an object storage sink whose Parquet files MotherDuck then reads. Streamkap, one of its listed ingestion partners, takes the same route through S3.
    You can, with the Tributary community extension's tributary_scan_topic function, but only in a local DuckDB client: MotherDuck doesn't run community extensions in its cloud or web UI. Tributary is experimental, has no write-back function, and each scan reads every partition from its first retained offset to the high watermark seen at the start.

Start streaming your data for free

Build a pipeline

About the author

Picture of Seán Whelan
Seán WhelanSolutions Engineer

Seán Whelan is a Solutions Engineer at Estuary, helping customers design, troubleshoot, and run production data pipelines. Seán works across change data capture, database replication, and SaaS integrations, and writes about what actually comes up when real teams move data.

Real-Time & Batch Pipelines.Simple to Deploy.Simply Priced.

  • $0.50/GB of data moved + $100/month per connector instance
  • Simple usage-based pricing with volume discounts
  • Sub-100ms end-to-end latency for real-time pipelines