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
- Use descriptive names with domain prefix
- Set retention based on needs
- Monitor lag and health
- Plan partition count carefully
- Document topic purposes
Practice Problems
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 & reliabilityHow 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 decompositionAnalyze 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 degradationQuiz
1. What is the benefit of entity-based topic naming?
2. Why use entity ID as partition key?
3. Can you decrease the number of partitions?
4. What is the hot partition problem?
5. What does 'cleanup.policy=compact' do?
Flashcards
Question
Topic naming best practices?
Click to reveal answer
Answer
Use entity-based naming (orders.created), descriptive names, consistent format across the system
Question
Why use entity ID as partition key?
Click to reveal answer
Answer
Ensures all events for same entity go to same partition, maintaining ordering for that entity
Question
Can you decrease partition count?
Click to reveal answer
Answer
No, only increase. Decreasing would break offset tracking and message ordering guarantees.
Question
What is topic compaction?
Click to reveal answer
Answer
Keeps only the latest message per key, removing older duplicates - useful for state topics
Question
How many partitions to start with?
Click to reveal answer
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