Kafka Complete Guide Javascript
Kafka Complete Guide Javascript
Complete Guide
The 20% of Kafka knowledge that covers 80% of daily usage in production environments,
technical interviews, and software engineering roles.
Table of Contents
1. Core Kafka Concepts & Architecture
1.3 Replication
3. JavaScript/NestJS Examples
Key Characteristics:
<domain>.<entity>.<event-type>
Examples:
- [Link]
- [Link]
- [Link]-changed
Real-World Example:
Partitions
Definition: A partition is the physical unit of storage and parallelism in Kafka. Each topic is divided
into one or more partitions, and each partition is an ordered, immutable sequence of records.
Key Characteristics:
• Ordered Sequence: Within a single partition, messages maintain strict ordering by offset
• Immutable: Once written, records cannot be modified (only appended or deleted by retention
policy)
• Distributed: Different partitions of the same topic can reside on different brokers
• Unit of Parallelism: Each partition can be consumed by only one consumer within a consumer
group
Scalability Example:
Topic: "user-events" with 1 partition → Throughput: 10 MB/s (limited by single partition)
Topic: "user-events" with 10 partitions → Throughput: 100 MB/s (10x parallelism)
Ordering Guarantees:
Formula:
Partitions = max(Target Throughput / Producer Throughput per Partition,
Target Throughput / Consumer Throughput per Partition)
Example:
Target: 100 MB/s throughput
Producer: 10 MB/s per partition
Consumer: 20 MB/s per partition
Best Practices:
Brokers
Definition: A Kafka broker is a server that stores data and serves client requests. It's the
fundamental building block of a Kafka cluster.
Responsibilities:
• Data Storage: Stores partition data on disk, manages log segments, handles retention
• Request Handling: Accepts produce requests, serves fetch requests, responds to metadata
requests
• Replication: Replicates data from leader partitions, serves as leader or follower
• Coordination: Participates in leader election, sends heartbeats to maintain membership
/var/lib/kafka/data/
■■■ payments-0/ (topic: payments, partition: 0)
■ ■■■ [Link] (segment file)
■ ■■■ [Link] (offset index)
■ ■■■ [Link]
■ ■■■ leader-epoch-checkpoint
■■■ payments-1/
■ ■■■ ...
■■■ payments-2/
■■■ ...
Hardware Considerations:
Cluster
Definition: A Kafka cluster is a group of brokers working together to provide high availability,
scalability, and fault tolerance.
Cluster Components:
Controller Role:
Cluster Coordination:
Traditional (ZooKeeper):
ZooKeeper Ensemble (3-5 nodes)
↓
Kafka Cluster (3+ brokers)
- Broker 1 (Controller)
- Broker 2
- Broker 3
Cluster Benefits:
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ KAFKA MESSAGE ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ Key (Optional) ■ Value (Required) ■
■ "user-123" ■ {"event": "purchase", ...} ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ Headers (Optional) ■
■ { ■
■ "source": "mobile-app", ■
■ "trace-id": "abc-123", ■
■ "version": "2.0" ■
■ } ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ Timestamp ■ Offset ■
■ 1706543210000 ■ 12345 ■
■ (Jan 29, 2024 10:00) ■ (within partition) ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ Partition ■ Topic ■
■ 2 ■ "user-events" ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
Key
Definition: An optional identifier used for message routing and log compaction.
Purpose:
Example:
key = "user-123"
hash("user-123") = 2147483647
2147483647 % 3 = 0
Important Notes:
• Changing partition count breaks key-to-partition mapping
• Hot keys can create uneven partition load
• Key size impacts network and storage (keep small)
Value
Definition: The actual message payload - the data you want to transmit.
Characteristics:
4. Plain String
"User 123 made a purchase of $99.99"
Pros: Simple
Cons: No structure, hard to parse
Headers
Definition: Key-value metadata pairs attached to messages, separate from the key and value.
// 2. Message Routing
headers: {
'destination': 'email-service',
'priority': 'high'
}
// 3. Schema Information
headers: {
'schema-version': '2.5',
'content-type': 'application/avro'
}
// 4. Source Metadata
headers: {
'source-system': 'mobile-app',
'source-version': '1.2.3',
'client-ip': '[Link]'
}
// 5. Business Context
headers: {
'tenant-id': 'acme-corp',
'region': 'us-east-1',
'environment': 'production'
}
Best Practices:
Timestamp
Definition: The time associated with a message, indicating when it was created or ingested.
Timestamp Uses:
1. Time-based Retention
Delete messages older than 7 days: [Link]=604800000
2. Time-based Seeking
// Seek to messages from specific time
const timestamp = new Date('2024-01-29T10:00:00Z').getTime();
await [Link]({ topic, partition, offset: timestamp });
3. Out-of-Order Detection
let lastTimestamp = 0;
for (const message of messages) {
if ([Link] < lastTimestamp) {
[Link]('Out-of-order message detected!');
}
lastTimestamp = [Link];
}
Offset
Definition: A unique, sequential identifier for each message within a partition. It's Kafka's primary
mechanism for tracking message position.
Key Characteristics:
Offset ■ Message
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0 ■ {"order": "A"}
1 ■ {"order": "B"}
2 ■ {"order": "C"}
3 ■ {"order": "D"}
4 ■ {"order": "E"}
■
↓ (new messages appended)
Replication Architecture:
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ REPLICATION EXAMPLE ■
■ Topic: orders, Partition: 0, RF: 3 ■
■ ■
■ ■■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■ ■
■ ■ Broker 1 ■ ■ Broker 2 ■ ■ Broker 3 ■ ■
■ ■ ■ ■ ■ ■ ■ ■
■ ■ Partition 0 ■ ■ Partition 0 ■ ■ Partition 0 ■ ■
■ ■ [LEADER] ■■■■■■ [FOLLOWER] ■ ■ [FOLLOWER] ■ ■
■ ■ ■ ■ (ISR) ■ ■ (Out of sync)■ ■
■ ■ Offsets: ■ ■ ■ ■ ■ ■
■ ■ 0-100 ■ ■ Offsets: ■ ■ Offsets: ■ ■
■ ■ ■ ■ 0-100 ■ ■ 0-85 ■ ■
■ ■ ■■■■■■■■■■■■ ■ ■ ■ ■ ■ ■
■ ■ ■Producer ■ ■ ■ ■ ■ ■ ■
■ ■ ■writes ■ ■ ■ ■ ■ ■ ■
■ ■ ■here ■ ■ ■ ■ ■ ■ ■
■ ■ ■■■■■■■■■■■■ ■ ■ ■ ■ ■ ■
■ ■ ↓ ■ ■ ↑ ■ ■ ↑ ■ ■
■ ■ [Write] ■■■■■■ [Replicate] ■ ■ [Replicate] ■ ■
■ ■ ■ ■ (fast) ■ ■ (lagging) ■ ■
■ ■■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■ ■
■ ■
■ ISR (In-Sync Replicas): {Broker 1, Broker 2} ■
■ Replicas: {Broker 1, Broker 2, Broker 3} ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
Replication Factor
Definition: The number of copies of each partition maintained across the cluster.
Calculation:
Total storage = Data size × Replication factor
Example: 1 TB data, RF=3 → 3 TB total storage needed
Leader & Followers
Leader:
• One per partition: Each partition has exactly one leader at a time
• Handles all I/O: All reads and writes go through the leader
• Maintains offset: Tracks the high watermark (HW) and log end offset (LEO)
• Coordinates followers: Manages follower replication
Followers:
• Passive replicas: Don't serve client requests (except with Kafka 2.4+ read-from-follower)
• Continuously fetch: Pull data from the leader
• Maintain copies: Keep up-to-date replicas of leader's log
• Ready to lead: Can become leader if current leader fails
2. High Availability
SLA Calculation:
RF=1: 99% availability (broker uptime)
RF=3: 99.99% availability (requires 2/3 brokers to fail simultaneously)
// Create producer
const producer = [Link]();
try {
const result = await [Link]({
topic: 'user-events',
messages: [
{
key: 'user-123',
value: [Link]({
userId: '123',
action: 'login',
timestamp: new Date().toISOString()
}),
headers: {
'trace-id': 'abc-123-def-456',
'source': 'web-app'
}
}
]
});
// Graceful shutdown
[Link]('SIGTERM', async () => {
await [Link]();
});
// Retry configuration
retry: {
initialRetryTime: 100,
retries: 8
}
});
await [Link]({
topic: 'user-events',
messages: messages,
acks: -1, // Wait for all ISR replicas
timeout: 30000
});
}
try {
// Send multiple messages in a transaction
for (const order of orders) {
await [Link]({
topic: 'orders',
messages: [{
key: [Link],
value: [Link](order)
}]
});
await [Link]({
topic: 'inventory',
messages: [{
key: [Link],
value: [Link]({
action: 'reserve',
quantity: [Link]
})
}]
});
}
// Commit transaction
await [Link]();
[Link]('Transaction committed');
} catch (error) {
// Abort on error
await [Link]();
[Link]('Transaction aborted:', error);
}
}
2.2 Consumer Examples
Basic Consumer:
// Subscribe to topic
await [Link]({
topic: 'user-events',
fromBeginning: false // Start from latest
});
// Process messages
await [Link]({
eachMessage: async ({ topic, partition, message }) => {
const key = [Link]?.toString();
const value = [Link]([Link]());
const headers = {};
// Extract headers
for (const [headerKey, headerValue] of [Link]([Link])) {
headers[headerKey] = [Link]();
}
[Link]({
topic,
partition,
offset: [Link],
key,
value,
headers,
timestamp: [Link]
});
// Process message
await processEvent(value);
}
});
}
await [Link]({
eachMessage: async ({ topic, partition, message }) => {
try {
// Process message
await processMessage(message);
await [Link]({
eachBatch: async ({
batch,
resolveOffset,
heartbeat,
isRunning
}) => {
const messages = [Link];
[Link](`Processing batch of ${[Link]} messages`);
try {
await processMessage(message);
// [Link]
import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { KafkaService } from './[Link]';
@Module({
imports: [
[Link]([
{
name: 'KAFKA_SERVICE',
transport: [Link],
options: {
client: {
clientId: 'nestjs-app',
brokers: ['localhost:9092']
},
consumer: {
groupId: 'nestjs-consumer-group'
}
}
}
])
],
providers: [KafkaService],
exports: [KafkaService]
})
export class KafkaModule {}
Kafka Service:
// [Link]
import { Injectable, Inject, OnModuleInit } from '@nestjs/common';
import { ClientKafka } from '@nestjs/microservices';
@Injectable()
export class KafkaService implements OnModuleInit {
constructor(
@Inject('KAFKA_SERVICE')
private readonly kafkaClient: ClientKafka
) {}
async onModuleInit() {
// Subscribe to topics for response
[Link]('[Link]');
await [Link]();
}
async sendMessageWithKey(
topic: string,
key: string,
message: any
) {
return [Link](topic, {
key,
value: [Link](message)
});
}
}
@Controller()
export class EventsController {
@MessagePattern('[Link]')
async handleUserEvent(
@Payload() message: any,
@Ctx() context: KafkaContext
) {
const originalMessage = [Link]();
const { headers, key, value, offset, timestamp } = originalMessage;
[Link]('Received message:', {
topic: [Link](),
partition: [Link](),
offset,
key: [Link](),
value: [Link](),
timestamp
});
@MessagePattern('[Link]')
async handleOrderCreated(@Payload() order: any) {
[Link]('New order:', order);
// Business logic here
}
// [Link]
import { Injectable, Logger } from '@nestjs/common';
import { KafkaService } from './kafka/[Link]';
interface Order {
orderId: string;
userId: string;
items: OrderItem[];
total: number;
}
interface OrderItem {
productId: string;
quantity: number;
price: number;
}
@Injectable()
export class OrderService {
private readonly logger = new Logger([Link]);
// [Link]
import { Injectable, Logger } from '@nestjs/common';
import { Kafka, Consumer, EachMessagePayload } from 'kafkajs';
@Injectable()
export class KafkaConsumerService {
private readonly logger = new Logger([Link]);
private consumer: Consumer;
private readonly maxRetries = 3;
async consume() {
await [Link]({
eachMessage: async (payload: EachMessagePayload) => {
const { topic, partition, message } = payload;
let retries = 0;
await [Link]({
topic: dlqTopic,
messages: [{
key: [Link],
value: [Link],
headers: {
...[Link],
'original-topic': originalTopic,
'error-message': [Link],
'failed-at': new Date().toISOString()
}
}]
});
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■ COMPLETE MESSAGE FLOW ■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
With this foundation, you're well-equipped to build scalable, fault-tolerant event-driven applications
using Apache Kafka. Remember to focus on understanding the fundamentals deeply, as they form
the basis for all advanced Kafka usage patterns.
Next Steps:
• Experiment with the code examples in your development environment
• Study Kafka Streams and Connect for stream processing and integration
• Explore monitoring tools like Kafka Manager, Burrow, or Confluent Control Center
• Practice troubleshooting common issues (consumer lag, rebalancing, etc.)
• Review Kafka's official documentation for advanced topics