Client Libraries
| Language | Popular library | Notes |
| Python | confluent-kafka (librdkafka based) | Fast, full-featured, Schema Registry support |
| Node.js | kafkajs, @confluentinc/kafka-javascript | KafkaJS is pure JavaScript and easy to use. Check maintenance status before choosing for a new project |
| Go | segmentio/kafka-go, confluent-kafka-go, franz-go | kafka-go is simple, franz-go is feature-rich |
| .NET | Confluent.Kafka | Based on librdkafka |
| Any language | Kafka REST Proxy | HTTP access when no client fits (limited performance) |
Most non-Java clients use librdkafka settings, with the same names (acks, enable.idempotence, group.id, auto.offset.reset). The ideas from the producer and consumer lessons apply everywhere.
Python: Producer
bash
pip install "confluent-kafka[avro,schemaregistry]"
python
import json
from confluent_kafka import Producer
producer = Producer({
"bootstrap.servers": "localhost:9092",
"acks": "all",
"enable.idempotence": True,
"linger.ms": 10,
"compression.type": "lz4",
})
def delivered(err, msg): # called from poll() or flush()
if err is not None:
print(f"FAILED: {err}")
else:
print(f"OK {msg.topic()}[{msg.partition()}]@{msg.offset()}")
for i in range(5):
event = {"orderId": f"o-{i}", "customerId": "c-7", "total": 59.9}
producer.produce("shop.orders.created.v1", key=event["orderId"], value=json.dumps(event), callback=delivered)
producer.poll(0) # serve delivery callbacks
producer.flush(10) # wait for all messages before exiting
Python: Consumer
python
import json
from confluent_kafka import Consumer, KafkaError
consumer = Consumer({
"bootstrap.servers": "localhost:9092",
"group.id": "email-service",
"auto.offset.reset": "earliest",
"enable.auto.commit": False,
"partition.assignment.strategy": "cooperative-sticky",
})
consumer.subscribe(["shop.orders.created.v1"])
try:
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
if msg.error().code() == KafkaError._PARTITION_EOF:
continue
raise Exception(msg.error())
order = json.loads(msg.value())
print("processing", order["orderId"]) # your idempotent business logic
consumer.commit(message=msg, asynchronous=False) # commit after success
finally:
consumer.close() # leave group cleanly so rebalance is quick
Node.js with KafkaJS
bash
pm install kafkajs
javascript
const { Kafka, logLevel, CompressionTypes } = require('kafkajs');
const kafka = new Kafka({ clientId: 'orders-app', brokers: ['localhost:9092'], logLevel: logLevel.WARN });
async function produce() {
const producer = kafka.producer({ idempotent: true });
await producer.connect();
await producer.send({
topic: 'shop.orders.created.v1',
acks: -1, // all in-sync replicas
compression: CompressionTypes.GZIP,
messages: [{ key: 'o-1', value: JSON.stringify({ orderId: 'o-1', total: 59.9 }), headers: { source: 'web' } }],
});
await producer.disconnect();
}
async function consume() {
const consumer = kafka.consumer({ groupId: 'email-service' });
await consumer.connect();
await consumer.subscribe({ topic: 'shop.orders.created.v1', fromBeginning: true });
await consumer.run({
autoCommit: false,
eachMessage: async ({ topic, partition, message }) => {
const order = JSON.parse(message.value.toString());
console.log(`got ${order.orderId} from ${topic}[${partition}]@${message.offset}`);
await consumer.commitOffsets([{ topic, partition, offset: (Number(message.offset) + 1).toString() }]); // next offset to read
},
});
}
produce().then(consume).catch(console.error);
Commit the next offset: A committed offset means 'the next record to read'. When committing manually, commit message.offset + 1 (Java and Python helpers do this for you when you pass the message).
Go with kafka-go
go
package main
import (
"context"
"fmt"
"time"
"github.com/segmentio/kafka-go"
)
func main() {
w := &kafka.Writer{
Addr: kafka.TCP("localhost:9092"),
Topic: "shop.orders.created.v1",
Balancer: &kafka.Hash{}, // same key -> same partition
RequiredAcks: kafka.RequireAll,
BatchTimeout: 10 * time.Millisecond,
}
defer w.Close()
_ = w.WriteMessages(context.Background(), kafka.Message{Key: []byte("o-1"), Value: []byte(`{"orderId":"o-1"}`)})
r := kafka.NewReader(kafka.ReaderConfig{
Brokers: []string{"localhost:9092"}, GroupID: "email-service", Topic: "shop.orders.created.v1", MinBytes: 1, MaxBytes: 10e6,
})
defer r.Close()
for {
m, err := r.FetchMessage(context.Background()) // fetch without auto commit
if err != nil { break }
fmt.Printf("got %s at %d\n", string(m.Value), m.Offset)
_ = r.CommitMessages(context.Background(), m) // commit after processing
}
}
Why Schema Registry?
When teams publish events as plain JSON, a renamed field can silently break consumers. A Schema Registry stores versioned schemas (Avro, Protobuf, JSON Schema). Producers register or look up a schema and write only a schema id (5 bytes) in front of the data, and consumers fetch the schema by id.
text
Producer --(1) register/check schema--> Schema Registry
Producer --(2) bytes: [magic 0][schema id][avro data]--> Kafka topic
Consumer --(3) read bytes, fetch schema by id (cached)--> Schema Registry --> decode
json
{
"type": "record",
"name": "OrderCreated",
"namespace": "com.example.shop",
"fields": [
{ "name": "orderId", "type": "string" },
{ "name": "customerId", "type": "string" },
{ "name": "total", "type": "double" },
{ "name": "currency", "type": "string", "default": "USD" }
]
}
Python Producer with Avro
python
from confluent_kafka import SerializingProducer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroSerializer
from confluent_kafka.serialization import StringSerializer
schema_str = open("order_created.avsc").read()
sr = SchemaRegistryClient({"url": "http://localhost:8081"})
avro_ser = AvroSerializer(sr, schema_str, to_dict=lambda obj, ctx: obj)
producer = SerializingProducer({
"bootstrap.servers": "localhost:9092",
"key.serializer": StringSerializer("utf_8"),
"value.serializer": avro_ser,
})
producer.produce("shop.orders.created.v1", key="o-1",
value={"orderId": "o-1", "customerId": "c-7", "total": 59.9, "currency": "EUR"})
producer.flush()
Compatibility Modes
| Mode | Allowed change | Upgrade order |
BACKWARD (default) | Delete fields, add fields with defaults. New schema can read old data | Upgrade consumers first |
FORWARD | Add fields, delete fields that have defaults. Old schema can read new data | Upgrade producers first |
FULL | Both directions: add or remove only fields with defaults | Any order |
*_TRANSITIVE | Same checks against all earlier versions, not only the last | Safest when replaying old data |
NONE | No checking | Avoid in shared topics |
bash
# set compatibility for a subject and test a new schema before deploying
curl -X PUT -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data '{"compatibility":"FULL_TRANSITIVE"}' http://localhost:8081/config/shop.orders.created.v1-value
curl -X POST -H "Content-Type: application/vnd.schemaregistry.v1+json" \
--data "{\"schema\": $(jq -Rs . < order_created_v2.avsc)}" \
http://localhost:8081/compatibility/subjects/shop.orders.created.v1-value/versions/latest
# {"is_compatible":true}
Evolution rules of thumb: Always give new fields a default. Never change a field type or reuse a field name for a different meaning. Rename by adding a new field and deprecating the old one. Put the compatibility check in your CI pipeline so incompatible schemas never reach production.
Quick Comparison
| Format | Strength | Consider |
| JSON (no schema) | Easy to read, no tooling | Large, no enforcement, easy to break consumers |
| JSON Schema | Readable plus validation | Bigger than binary formats |
| Avro | Compact, strong evolution rules, widely used with Kafka | Binary, needs registry and tooling |
| Protobuf | Compact, strong typing, good multi-language support | Evolution rules by field numbers |
Conclusion
Kafka works from any language with librdkafka-based or native clients: produce with delivery callbacks, consume with manual commits after processing and close consumers cleanly. Use Schema Registry with Avro or Protobuf and a compatibility mode (BACKWARD or FULL) so teams can change events safely.
Quick Summary: confluent-kafka / KafkaJS / kafka-go; commit after processing; Schema Registry ids; BACKWARD/FULL; defaults on new fields.