Skip to content
intermediatePhase 47 · Messaging

Topics

Organize messages into topics for logical separation and routing.

30m
0 problems
Topic Progress0%

Topic Design

Topic Design

Naming Conventions

Topic Naming Patterns:

1. Entity-based:
   orders
   users
   products

2. Event-based:
   order.created
   order.updated
   user.registered

3. Domain-based:
   ecommerce.orders
   ecommerce.payments
   analytics.events

4. Purpose-based:
   orders-input
   orders-processed
   orders-dlq

Design Principles

Principle Description
Single Responsibility One topic per event type
Descriptive Names Clear purpose from name
Consistent Format Uniform naming convention
Separation of Concerns Different topics for different domains
Future-proof Consider evolution

Topic Structure

# Well-designed topics
topics = {
    # Core business events
    'orders.created': 'New orders',
    'orders.updated': 'Order status changes',
    'orders.cancelled': 'Cancelled orders',
    
    # User events
    'users.registered': 'New user signups',
    'users.updated': 'Profile changes',
    
    # System events
    'system.audit': 'Audit logs',
    'system.metrics': 'Application metrics'
}

Topic vs Queue

Aspect Topic (Pub-Sub) Queue (Point-to-Point)
Consumers Multiple get copy One gets message
Retention Messages retained Messages deleted
Replay Yes No
Use Case Event broadcasting Task distribution

Topic Partitioning

Topic Partitioning

Partitioning Strategy

Topic: orders (6 partitions)

Key-based:
order_id=1 → hash(1) % 6 = partition 3
order_id=2 → hash(2) % 6 = partition 1
order_id=3 → hash(3) % 6 = partition 4

Same key always → same partition (ordering guarantee)

Key Selection

# Good key choices
def get_partition_key(message):
    # Option 1: Entity ID (maintains entity ordering)
    return message['order_id']
    
    # Option 2: User ID (user-level ordering)
    return message['user_id']
    
    # Option 3: Null (round-robin, no ordering)
    return None

# Partition assignment
partition = hash(key) % num_partitions

Partition Count

Partition Count Guidelines:

- Start with: 2-3x target throughput
- Can increase: Yes (but not decrease)
- Consider: Consumer count, broker count
- Max per broker: ~4000 (file handles)

Example:
Target: 100K messages/sec
Broker: 10K messages/sec capacity
Need: 10 brokers minimum
Partitions: 20-30 (2-3x brokers)

Hot Partition Problem

Problem: One partition gets disproportionate traffic

Solution 1: Better key distribution
Solution 2: Shard hot key across partitions
Solution 3: Increase partitions and rebalance

Partition Reassignment

# Reassign partitions
kafka-reassign-partitions.sh \
  --reassignment-json-file reassignment.json \
  --execute

# JSON format
{
  "partitions": [
    {"topic": "orders", "partition": 0, "replicas": [1, 2, 3]}
  ]
}

Topic Management

Topic Management

Topic Lifecycle

1. Creation:
   kafka-topics.sh --create \
     --topic orders \
     --partitions 6 \
     --replication-factor 3

2. Configuration:
   kafka-topics.sh --alter \
     --topic orders \
     --config retention.ms=604800000

3. Deletion:
   kafka-topics.sh --delete --topic orders

Topic Configuration

# Key configurations
retention.ms=604800000      # 7 days retention
cleanup.policy=delete       # delete or compact
max.message.bytes=1048576   # 1MB max message
min.insync.replicas=2       # Durability requirement

Topic Monitoring

# Monitor topic health
def monitor_topic(topic, expected_partitions=6):
    # Check partition count
    partitions = kafka.partitions(topic)
    if len(partitions) != expected_partitions:
        alert(f"Partition count mismatch: {topic}")
    
    # Check consumer lag
    for partition in partitions:
        lag = get_consumer_lag(topic, partition)
        if lag > 10000:
            alert(f"High lag on {topic}:{partition}")
    
    # Check replication
    for partition in partitions:
        replicas = get_replica_count(topic, partition)
        if replicas < 2:
            alert(f"Low replication: {topic}:{partition}")

Topic Cleanup Policies

Policy Description Use Case
Delete Remove old data Standard topics
Compact Keep latest per key State topics
Compact+Delete Both State with TTL

Best Practices

  1. Use descriptive names with domain prefix
  2. Set retention based on needs
  3. Monitor lag and health
  4. Plan partition count carefully
  5. Document topic purposes

Practice Problems

0/3solved
Design Topics System

Design a scalable Topics system. Cover high-level architecture, data model, and API design.

Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliability
Topics Scaling

How would you scale Topics to handle 10x the current load? Identify bottlenecks and solutions.

Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decomposition
Topics Failure Modes

Analyze potential failure modes for Topics and design mitigation strategies.

Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradation

Quiz

1. What is the benefit of entity-based topic naming?

Question 1 options

2. Why use entity ID as partition key?

Question 2 options

3. Can you decrease the number of partitions?

Question 3 options

4. What is the hot partition problem?

Question 4 options

5. What does 'cleanup.policy=compact' do?

Question 5 options

Flashcards

Question

Topic naming best practices?

Answer

Use entity-based naming (orders.created), descriptive names, consistent format across the system

Question

Why use entity ID as partition key?

Answer

Ensures all events for same entity go to same partition, maintaining ordering for that entity

Question

Can you decrease partition count?

Answer

No, only increase. Decreasing would break offset tracking and message ordering guarantees.

Question

What is topic compaction?

Answer

Keeps only the latest message per key, removing older duplicates - useful for state topics

Question

How many partitions to start with?

Answer

2-3x target throughput / broker capacity. Can increase later but not decrease.

Revision Notes

Key Takeaways

  • 1.Topic naming should be descriptive and follow consistent conventions
  • 2.Partition key determines message routing and ordering
  • 3.You can only increase partitions, never decrease
  • 4.Topic compaction keeps latest per key for state topics
  • 5.Monitor partition health, lag, and replication

Interview Tips

  • Explain topic naming conventions and rationale
  • Discuss partition key selection strategy
  • Know partition count planning guidelines
  • Mention compaction for state management

Cheat Sheet

Cheat Sheet: Topics

Naming

  • Entity-based: orders.created
  • Domain prefix: ecommerce.orders
  • Descriptive and consistent

Partitioning

  • Key-based: same key → same partition
  • Entity ID for ordering guarantee
  • Start 2-3x target throughput
  • Can increase, not decrease

Configuration

  • retention.ms: Data retention
  • cleanup.policy: delete/compact
  • min.insync.replicas: Durability

Monitoring

  • Partition count health
  • Consumer lag
  • Replication status