xiaohongshu
xiaohongshu
kafka-consumer-implementation
Implement type-safe Kafka consumers for event consumption with msgspec deserialization. Use when building async consumers that process domain events (order messages, transactions) with offset management, error recovery, graceful shutdown, and distributed tracing. Handles consumer configuration, m...
Full skill instructions
Implement production-grade Kafka consumers that reliably consume and process domain events with high performance, type safety, and comprehensive error recovery. Covers msgspec deserialization, confluent-kafka configuration, offset management, OpenTelemetry tracing, and anti-corruption layer patterns for translating message schemas to domain models.
Use when building event-driven systems that consume domain events from Kafka topics with "implement Kafka consumer", "consume events from Kafka", "process order messages", or "set up event consumer".
Do NOT use when mocking Kafka consumers in unit tests (use pytest-adapter-integration-testing), implementing producers (use kafka-producer-implementation), or testing with testcontainers (use kafka-integration-testing).
Create a high-performance Kafka consumer in 3 steps:
import msgspec
class OrderEventMessage(msgspec.Struct, frozen=True):
order_id: str
created_at: str
customer_name: str
total_price: float
from confluent_kafka import Consumer
import msgspec
class OrderEventConsumer:
def __init__(self, brokers: list[str], topic: str, group_id: str) -> None:
config = {
"bootstrap.servers": ",".join(brokers),
"group.id": group_id,
"auto.offset.reset": "earliest",
"enable.auto.commit": False,
}
self.consumer = Consumer(config)
self.consumer.subscribe([topic])
self.decoder = msgspec.json.Decoder(OrderEventMessage)
def consume(self, timeout: float = 1.0) -> OrderEventMessage | None:
msg = self.consumer.poll(timeout)
if msg is None or msg.error():
return None
return self.decoder.decode(msg.value())
def commit(self) -> None:
self.consumer.commit(asynchronous=False)
consumer = OrderEventConsumer(["localhost:9092"], "orders", "loader")
message = consumer.consume()
if message:
process(message)
consumer.commit()
Key configuration for exactly-once processing:
config = {
"bootstrap.servers": ",".join(brokers),
"group.id": group_id,
"auto.offset.reset": "earliest", # Start from beginning
"enable.auto.commit": False, # Manual offset management
"session.timeout.ms": 300000, # 5 minute timeout
"max.poll.interval.ms": 300000, # 5 minutes for processing
}
Implement consumer with error handling:
See references/detailed-implementation.md for complete consumer adapter code.
Translate Kafka messages to domain entities:
class OrderEventTranslator:
@staticmethod
def to_domain_order(message: OrderEventMessage) -> Order:
# Validate
if not message.order_id:
raise ValueError("order_id is required")
# Convert types (str -> OrderId, float -> Money)
created_at = datetime.fromisoformat(message.created_at)
order_id = OrderId(message.order_id)
total_price = Money(Decimal(str(message.total_price)))
return Order(order_id, created_at, message.customer_name, total_price, [])
Main consumer loop pattern:
See references/detailed-implementation.md for complete processing loop code.
Use context managers for clean shutdown:
@asynccontextmanager
async def managed_consumer(brokers, topic, group_id):
consumer = OrderEventConsumer(brokers, topic, group_id)
try:
yield consumer
finally:
consumer.close()
confluent-kafka>=2.3.0 - Production-grade Kafka clientmsgspec>=0.18.6 - Ultra-fast deserializationstructlog>=23.2.0 - Structured loggingopentelemetry-api>=1.22.0 - Distributed tracingConsumer Groups: Consumers in the same group share responsibility for topic partitions. Kafka automatically rebalances when members join/leave.
Manual Offset Management (exactly-once-per-restart):
"enable.auto.commit": Falseconsumer.commit()"auto.offset.reset": "earliest" starts from beginningSee references/detailed-implementation.md for complete offset management patterns, consumer lag monitoring, and rebalancing behavior.
Key error handling strategies:
See references/error-handling.md for comprehensive error handling strategies and dead letter queue patterns.
Use testcontainers for integration tests:
from testcontainers.kafka import KafkaContainer
@pytest.fixture
def kafka_container():
with KafkaContainer() as kafka:
yield kafka
def test_consumer_roundtrip(kafka_container):
brokers = [kafka_container.get_bootstrap_server()]
# Test consumer/producer workflow
See examples/integration-examples.md for complete integration test patterns.
references/detailed-implementation.md - Complete consumer adapter and processing loop codereferences/error-handling.md - Comprehensive error handling strategiesexamples/integration-examples.md - Real-world integration patternskafka-producer-implementation skill - For producing eventskafka-schema-management skill - For schema designxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience