Claude Code for Redpanda: Kafka-Compatible Event Streaming — Claude Skills 360 Blog
Blog / AI / Claude Code for Redpanda: Kafka-Compatible Event Streaming
AI

Claude Code for Redpanda: Kafka-Compatible Event Streaming

Published: August 12, 2027
Read time: 5 min read
By: Claude Skills 360

Redpanda is Kafka-compatible event streaming without ZooKeeper — lower latency, single binary, no JVM. KafkaJS connects identically: new Kafka({ clientId: "my-app", brokers: ["localhost:9092"] }). Redpanda Cloud: brokers: [process.env.REDPANDA_BROKERS!], ssl: true, sasl: { mechanism: "scram-sha-256", username, password }. Schema Registry URL: REDPANDA_SCHEMA_REGISTRY_URL — same API as Confluent Schema Registry. rpk topic create orders --partitions 6 --replicas 1 creates a topic. rpk topic consume orders --offset start reads from the beginning. rpk group list lists consumer groups; rpk group describe my-group shows lag. Redpanda Connect (formerly Benthos): input: kafka_franz, pipeline: processors, output: kafka_franz or output: http_client — pipelines configured in YAML, no code needed for transforms. Redpanda Wasm transforms: rpk transform build && rpk transform deploy --input-topic=raw-events --output-topic=clean-events runs a Wasm function inline in the broker. GET /v1/brokers and GET /v1/topics from the Redpanda Admin API. Redpanda Console: web UI for topics, consumer groups, schema registry, and connect — ships in redpandadata/console Docker image. Self-hosted Docker Compose: redpandadata/redpanda:latest with --mode dev-container. Claude Code generates Redpanda KafkaJS producers/consumers, Schema Registry integrations, Redpanda Connect pipelines, and rpk automation scripts.

CLAUDE.md for Redpanda

## Redpanda Stack
- Client: kafkajs >= 2.x (100% Kafka-compatible — no Redpanda-specific lib needed)
- Local: docker run redpandadata/redpanda:latest --mode dev-container --kafka-addr localhost:9092
- Cloud: brokers from Redpanda Cloud console + ssl: true + sasl: { mechanism: "scram-sha-256" }
- Schema Registry: same API as Confluent — REDPANDA_SCHEMA_REGISTRY_URL env var
- Admin API: GET /v1/topics, GET /v1/brokers (port 9644 default on self-hosted)
- rpk: rpk topic create/consume/produce, rpk group list/describe — standard CLI for ops

Redpanda Client (KafkaJS)

// lib/redpanda/client.ts — KafkaJS client for Redpanda
import { Kafka, type KafkaConfig, logLevel } from "kafkajs"

function buildConfig(): KafkaConfig {
  const brokers = (process.env.REDPANDA_BROKERS ?? "localhost:9092").split(",")

  // Redpanda Cloud requires SSL + SASL
  if (process.env.REDPANDA_SASL_USERNAME) {
    return {
      clientId:  process.env.SERVICE_NAME ?? "my-app",
      brokers,
      ssl:       true,
      sasl: {
        mechanism: "scram-sha-256",
        username:  process.env.REDPANDA_SASL_USERNAME!,
        password:  process.env.REDPANDA_SASL_PASSWORD!,
      },
      logLevel: logLevel.WARN,
    }
  }

  // Self-hosted (no auth)
  return {
    clientId: process.env.SERVICE_NAME ?? "my-app",
    brokers,
    logLevel: logLevel.WARN,
  }
}

export const redpanda = new Kafka(buildConfig())
export const admin    = redpanda.admin()

Topic Management

// lib/redpanda/topics.ts — topic creation and admin operations
import { admin } from "./client"

export type TopicSpec = {
  name:               string
  numPartitions?:     number
  replicationFactor?: number
  retentionMs?:       number
  cleanupPolicy?:     "delete" | "compact" | "compact,delete"
}

export async function ensureTopics(topics: TopicSpec[]): Promise<void> {
  await admin.connect()

  try {
    const existing   = new Set(await admin.listTopics())
    const toCreate   = topics.filter((t) => !existing.has(t.name))
    if (!toCreate.length) return

    await admin.createTopics({
      topics: toCreate.map((t) => ({
        topic:             t.name,
        numPartitions:     t.numPartitions     ?? 3,
        replicationFactor: t.replicationFactor ?? 1,
        configEntries: [
          ...(t.retentionMs    ? [{ name: "retention.ms",     value: String(t.retentionMs) }]    : []),
          ...(t.cleanupPolicy  ? [{ name: "cleanup.policy",   value: t.cleanupPolicy }]          : []),
        ],
      })),
    })

    console.log(`[Redpanda] Created topics: ${toCreate.map((t) => t.name).join(", ")}`)
  } finally {
    await admin.disconnect()
  }
}

export async function getConsumerGroupLag(groupId: string): Promise<
  Array<{ topic: string; partition: number; lag: number }>
> {
  await admin.connect()
  try {
    const offsets = await admin.fetchOffsets({ groupId, resolveOffsets: true })

    const lags: Array<{ topic: string; partition: number; lag: number }> = []
    for (const t of offsets) {
      const topicOffsets = await admin.fetchTopicOffsets(t.topic)
      for (const p of t.partitions) {
        const latest = topicOffsets.find((o) => o.partition === p.partition)
        if (latest) {
          lags.push({
            topic:     t.topic,
            partition: p.partition,
            lag:       parseInt(latest.offset) - parseInt(p.offset),
          })
        }
      }
    }

    return lags
  } finally {
    await admin.disconnect()
  }
}

Typed Producer and Consumer

// lib/redpanda/events.ts — typed event bus on Redpanda
import { redpanda } from "./client"
import type { Producer, Consumer, EachMessagePayload } from "kafkajs"
import { randomUUID } from "crypto"

// ── Event types ────────────────────────────────────────────────────────────

export type BaseEvent<T extends string, P> = {
  eventId:    string
  eventType:  T
  occurredAt: string
  payload:    P
}

export type OrderPlaced = BaseEvent<"OrderPlaced", {
  orderId:  string
  userId:   string
  amount:   number
  currency: string
  items:    Array<{ productId: string; quantity: number; price: number }>
}>

export type UserSignedUp = BaseEvent<"UserSignedUp", {
  userId: string
  email:  string
  plan:   "free" | "pro" | "enterprise"
}>

export type AppEvent = OrderPlaced | UserSignedUp

// ── Topic routing ──────────────────────────────────────────────────────────

const TOPIC_MAP: Record<AppEvent["eventType"], string> = {
  OrderPlaced:  "orders",
  UserSignedUp: "users",
}

// ── Producer ───────────────────────────────────────────────────────────────

let producer: Producer | null = null

async function getProducer(): Promise<Producer> {
  if (!producer) {
    producer = redpanda.producer({ idempotent: true })
    await producer.connect()
    process.once("SIGTERM", () => producer?.disconnect().catch(console.error))
    process.once("SIGINT",  () => producer?.disconnect().catch(console.error))
  }
  return producer
}

export async function publishEvent<E extends AppEvent>(
  event: Omit<E, "eventId" | "occurredAt">,
): Promise<void> {
  const p   = await getProducer()
  const full = { ...event, eventId: randomUUID(), occurredAt: new Date().toISOString() }
  const topic = TOPIC_MAP[event.eventType]

  await p.send({
    topic,
    messages: [{
      key:   `${event.eventType}-${randomUUID()}`,
      value: JSON.stringify(full),
      headers: { eventType: event.eventType, contentType: "application/json" },
    }],
  })
}

// ── Consumer ───────────────────────────────────────────────────────────────

export type EventHandler<E extends AppEvent> = (event: E) => Promise<void>

export async function startEventConsumer(
  groupId:  string,
  topics:   string[],
  handlers: Partial<{ [K in AppEvent["eventType"]]: EventHandler<Extract<AppEvent, { eventType: K }>> }>,
): Promise<() => Promise<void>> {
  const consumer: Consumer = redpanda.consumer({ groupId })
  await consumer.connect()
  await consumer.subscribe({ topics, fromBeginning: false })

  await consumer.run({
    autoCommit: true,
    eachMessage: async ({ message }: EachMessagePayload) => {
      const raw = message.value?.toString()
      if (!raw) return

      const event = JSON.parse(raw) as AppEvent
      const handler = handlers[event.eventType] as EventHandler<AppEvent> | undefined

      if (handler) {
        await handler(event).catch((err) =>
          console.error(`[Redpanda] Handler error for ${event.eventType}:`, err.message),
        )
      }
    },
  })

  const stop = async () => {
    await consumer.stop()
    await consumer.disconnect()
  }

  return stop
}

Redpanda Connect Pipeline

# redpanda-connect.yaml — no-code data pipeline (Benthos-compatible)
# Reads from Redpanda, transforms, and writes to HTTP endpoint
input:
  kafka_franz:
    seed_brokers: ["${REDPANDA_BROKERS}"]
    topics: ["raw-events"]
    consumer_group: connect-pipeline
    tls:
      enabled: true
    sasl:
      - mechanism: SCRAM-SHA-256
        username: "${REDPANDA_SASL_USERNAME}"
        password: "${REDPANDA_SASL_PASSWORD}"

pipeline:
  processors:
    - mapping: |
        root = this
        root.processedAt = now()
        root.payload.amount = root.payload.amount.number() * 100  # cents
    - catch:
      - log:
          level: ERROR
          message: 'Processing error: ${! error() }'

output:
  fallback:
    - kafka_franz:
        seed_brokers: ["${REDPANDA_BROKERS}"]
        topic: processed-events
        tls: { enabled: true }
        sasl:
          - mechanism: SCRAM-SHA-256
            username: "${REDPANDA_SASL_USERNAME}"
            password: "${REDPANDA_SASL_PASSWORD}"
    - kafka_franz:
        seed_brokers: ["${REDPANDA_BROKERS}"]
        topic: dead-letter-queue
        tls: { enabled: true }
        sasl:
          - mechanism: SCRAM-SHA-256
            username: "${REDPANDA_SASL_USERNAME}"
            password: "${REDPANDA_SASL_PASSWORD}"

Docker Compose

# docker-compose.yml — Redpanda self-hosted dev setup
services:
  redpanda:
    image: docker.redpanda.com/redpandadata/redpanda:v23.3.21
    command:
      - redpanda
      - start
      - --mode dev-container
      - --smp 1
      - --memory 512M
      - --reserve-memory 0M
      - --node-id 0
      - --kafka-addr PLAINTEXT://0.0.0.0:29092,OUTSIDE://0.0.0.0:9092
      - --advertise-kafka-addr PLAINTEXT://redpanda:29092,OUTSIDE://localhost:9092
      - --schema-registry-addr 0.0.0.0:8081
      - --pandaproxy-addr 0.0.0.0:8082
      - --rpc-addr 0.0.0.0:33145
      - --advertise-rpc-addr redpanda:33145
    ports:
      - "9092:9092"    # Kafka API (external)
      - "8081:8081"    # Schema Registry
      - "8082:8082"    # Pandaproxy (HTTP API)
      - "9644:9644"    # Admin API

  console:
    image: docker.redpanda.com/redpandadata/console:v2.5.2
    environment:
      CONFIG_FILEPATH: /tmp/config.yml
    volumes:
      - ./redpanda-console-config.yaml:/tmp/config.yml:ro
    ports:
      - "8080:8080"
    depends_on: [redpanda]

For the Apache Kafka alternative when needing the full Kafka ecosystem with the broadest tooling support (Kafka Streams, Kafka Connect ecosystem, ksqlDB, MirrorMaker 2, extensive managed options like Confluent Cloud and MSK) — Kafka is the industry standard with maximum operator familiarity while Redpanda is a drop-in replacement that eliminates ZooKeeper/KRaft complexity, achieves lower tail latency, and runs as a single binary ideal for smaller teams or self-hosting. For the NATS JetStream alternative when needing a lighter-weight cloud-native messaging system with sub-millisecond latency for request-reply patterns, a smaller operational footprint, and JetStream for optional persistence — NATS is excellent for service mesh RPC and fan-out while Redpanda excels at durable high-throughput event streaming with consumer group semantics. The Claude Skills 360 bundle includes Redpanda skill sets covering KafkaJS integration, topic management, and Redpanda Connect pipelines. Start with the free tier to try event streaming generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free