Home / Data Platform / Streaming & CDC

Data PlatformTroubleshootingIntermediate

Kafka Connect JDBC sink connector failing - missing schemas, primary key modes, upserts and tables that won't evolve

Why a JDBC sink task goes FAILED - schemaless JSON, wrong pk.mode, upserts without keys, tombstones, auto.evolve limits and database errors - and the config that fixes each one.

Deepak Bhardwaj8 min read

Applies toConfluent JDBC sink connector 10.x on Apache Kafka Connect 3.x / 4.x and Confluent Platform; PostgreSQL, SQL Server, MySQL and Oracle targets

Symptom

The JDBC sink connector shows RUNNING but one or more tasks are FAILED, consumer lag on the source topic grows, and the target table stops receiving rows. The connector log has a stack trace ending in ConnectException, DataException or a java.sql.SQLException / BatchUpdateException.

Start by getting the actual error. Do not guess from the connector state alone.

# Task state and the first lines of the stack trace
curl -s http://connect:8083/connectors/orders-jdbc-sink/status | jq '.tasks[] | {id, state, trace: (.trace // "" | .[0:600])}'

# Effective config, including defaults you did not set
curl -s http://connect:8083/connectors/orders-jdbc-sink/config | jq .

Then look at a real record, key and value, so you know what the connector is being given:

kafka-console-consumer.sh --bootstrap-server broker:9092 --topic orders \
  --from-beginning --max-messages 3 \
  --property print.key=true --property print.headers=true

Error → cause → fix

Error text (abbreviated) Cause Fix
JsonConverter with schemas.enable requires "schema" and "payload" fields Converter has schemas.enable=true but the producer writes plain JSON Use Avro/Protobuf/JSON Schema with Schema Registry, or have producers send the schema envelope
requires records with a non-null Struct value and non-null Struct schema Value is schemaless (plain JSON with schemas.enable=false, or a String) The JDBC sink needs a schema. Switch converters; do not just flip schemas.enable
PK mode for table ... is RECORD_KEY, but record key schema is missing pk.mode=record_key with a null or schemaless key Produce keys with a schema, or use pk.mode=record_value and pk.fields
Sink connector ... is configured with 'delete.enabled=false' ... tombstone / null value A delete (tombstone) arrived and deletes are off Set delete.enabled=true (needs pk.mode=record_key), or drop tombstones with an SMT
Cannot ALTER TABLE ... to add missing field ... as it is not optional and does not have a default value auto.evolve=true but the new field is required Make the new field optional or give it a default in the schema
Table ... is missing and auto-creation is disabled auto.create=false and no table Create the table, or set auto.create=true for non-production
Duplicate key / unique constraint violation insert.mode=insert and the topic contains replays Use insert.mode=upsert with a real pk.mode
value too long for type / string truncation / data type mismatch Column smaller than the data, or a type the dialect maps differently Widen the column; check the dialect's type mapping

Warning

Setting errors.tolerance=all makes failures disappear, but it only applies to converter and transform errors. Database errors during the write still fail the task. Do not treat a quiet connector as a healthy one.

Fix 1: give the connector a schema

The JDBC sink writes typed columns, so it must know field names and types for every record. Plain JSON without a schema is the most common cause of a sink that fails on its first record.

Preferred: a schema-aware converter backed by Schema Registry.

{
  "key.converter": "io.confluent.connect.avro.AvroConverter",
  "key.converter.schema.registry.url": "http://schema-registry:8081",
  "value.converter": "io.confluent.connect.avro.AvroConverter",
  "value.converter.schema.registry.url": "http://schema-registry:8081"
}

io.confluent.connect.json.JsonSchemaConverter and io.confluent.connect.protobuf.ProtobufConverter work the same way. If producers cannot change, the fallback is org.apache.kafka.connect.json.JsonConverter with schemas.enable=true, which needs every message to carry a schema and payload envelope. That is heavy, and it means producer changes anyway.

Check what the registry holds for the topic before you switch:

curl -s http://schema-registry:8081/subjects | jq '.[] | select(startswith("orders"))'
curl -s http://schema-registry:8081/subjects/orders-value/versions/latest | jq -r .schema | jq .

Tip

If the topic mixes serialisation formats (old JSON records, newer Avro), the converter fails on the old records forever. Start a new connector name with consumer.override.auto.offset.reset=latest after the cut-over point, or route bad records to a dead letter queue (below) and replay them separately.

Fix 2: pick the right primary key mode

pk.mode decides where the key columns come from. Getting it wrong causes either key errors or silent duplicates.

pk.mode Key columns come from Use when
none No primary key Append-only logs; insert.mode=insert only
kafka __connect_topic, __connect_partition, __connect_offset You want exactly one row per Kafka record
record_key Fields of the record key (or the whole primitive key, named by pk.fields) Key holds the business id; needed for deletes
record_value Fields named in pk.fields from the value Key is null or unusable, id is in the value

A typical upsert config for a CDC-style topic:

{
  "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector",
  "topics": "orders",
  "connection.url": "jdbc:postgresql://pg01:5432/sales",
  "connection.user": "kc_writer",
  "connection.password": "${file:/opt/connect/secrets.properties:pg.password}",
  "insert.mode": "upsert",
  "pk.mode": "record_key",
  "pk.fields": "order_id",
  "delete.enabled": "true",
  "table.name.format": "${topic}",
  "auto.create": "false",
  "auto.evolve": "true",
  "batch.size": "1000",
  "max.retries": "10",
  "retry.backoff.ms": "3000",
  "tasks.max": "4"
}

insert.mode=upsert uses the dialect's native upsert (ON CONFLICT on PostgreSQL, MERGE on SQL Server and Oracle, ON DUPLICATE KEY UPDATE on MySQL). It needs a primary key or unique constraint on the target that matches pk.fields. Confirm the constraint exists:

-- PostgreSQL
SELECT conname, pg_get_constraintdef(oid)
FROM pg_constraint
WHERE conrelid = 'public.orders'::regclass AND contype IN ('p','u');

Caution

Changing pk.mode or pk.fields on a running connector against an existing table does not migrate the table. An upsert whose key no longer matches the table's constraint either errors or, with pk.mode=none, appends duplicates. Treat a key change as a new table plus backfill.

Deletes and tombstones

With delete.enabled=true and pk.mode=record_key, a record with a null value deletes the row matching the key. Debezium topics need the unwrap transform so the sink sees a flat row and a tombstone:

{
  "transforms": "unwrap",
  "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
  "transforms.unwrap.drop.tombstones": "false",
  "transforms.unwrap.delete.handling.mode": "none"
}

Option names of ExtractNewRecordState vary by Debezium version (newer releases add delete.tombstone.handling.mode); check the docs for your build.

Fix 3: schema changes and auto.evolve

auto.evolve=true only adds columns. It does not drop columns, rename them, change types or widen a VARCHAR. A new required field without a default cannot be added either, because existing rows would violate it.

When a producer changes a type or renames a field:

  1. Pause the connector so nothing else fails: curl -X PUT http://connect:8083/connectors/orders-jdbc-sink/pause
  2. Apply the DDL by hand on the target (add the new column, backfill, change the type).
  3. Resume: curl -X PUT http://connect:8083/connectors/orders-jdbc-sink/resume
  4. Restart the failed task: curl -X POST "http://connect:8083/connectors/orders-jdbc-sink/restart?includeTasks=true&onlyFailed=true"

The restart query parameters need Kafka Connect 3.0 or later. On older workers, restart each task with POST /connectors/<name>/tasks/<id>/restart.

Fix 4: database-side failures

When the trace ends in BatchUpdateException, the problem is in the database. Find the real cause in the nested exception (getNextException output). The usual ones:

  • Lock waits and deadlocks: several tasks upserting the same keys. Keys are spread by Kafka partition, so this is usually a target trigger or a foreign key to a hot parent row. Lower tasks.max or remove the contention.
  • Connection drops: idle timeouts on a firewall or proxy. max.retries and retry.backoff.ms cover short outages. Longer ones fail the task, and it needs a restart.
  • Permissions: the connector user needs INSERT, UPDATE and DELETE on the table, plus CREATE/ALTER if auto.create or auto.evolve is on.
-- SQL Server: what the connector login can do on the table
EXECUTE AS LOGIN = 'kc_writer';
SELECT permission_name FROM fn_my_permissions('dbo.orders', 'OBJECT');
REVERT;

Keep bad records from stopping the pipeline

For converter and SMT failures, send bad records to a dead letter queue instead of failing the task:

{
  "errors.tolerance": "all",
  "errors.deadletterqueue.topic.name": "dlq.orders-jdbc-sink",
  "errors.deadletterqueue.topic.replication.factor": "3",
  "errors.deadletterqueue.context.headers.enable": "true",
  "errors.log.enable": "true",
  "errors.log.include.messages": "false"
}

Recent JDBC sink versions also report failed database writes to the DLQ through the errant record reporter. Whether that happens depends on the connector version, so check your connector's release notes before you count on it.

Read the failure reason from the DLQ headers:

kafka-console-consumer.sh --bootstrap-server broker:9092 --topic dlq.orders-jdbc-sink \
  --from-beginning --max-messages 5 --property print.headers=true

Prevent it next time

  • Require a schema-aware converter for every sink. Reject connector configs that use schemaless JSON in review.
  • Set Schema Registry compatibility to BACKWARD (or stricter) on sink topics, and make new fields optional with defaults.
  • Pre-create production tables with explicit types and the primary key. Keep auto.create=false in production.
  • Alert on task state, not only connector state: any task in FAILED, plus consumer lag on the connector's group (connect-<connector-name>).
  • Alert on DLQ topic growth. A DLQ nobody watches just turns failures into quiet data loss.