Designing a Pub/Sub Messaging System (Mini-Kafka)

Difficulty: Hard Patterns: Observer, Iterator, Factory Asked at: Uber, LinkedIn, Flipkart, Swiggy, Confluent


Functional Requirements

  1. Create topics with a configurable number of partitions for parallel message processing
    💡 A partition is one independent, ordered slice of a topic’s messages. Splitting a topic into partitions is what lets several consumers work the same topic at once instead of queueing behind each other.
  2. Publish messages to a topic; messages are routed to partitions via a key-based or round-robin strategy
    💡 Round-robin = hand each new message to the next partition in turn and wrap around at the end, which spreads load evenly when the message carries no key.
  3. Subscribe consumers to one or more topics and consume messages sequentially from assigned partitions
  4. Consumer groups — multiple consumers form a group; each partition is assigned to exactly one consumer within the group for load balancing
    💡 A consumer group is a set of consumers that share one subscription: the group collectively sees every message, but any single message is handled by just one member. Two different groups reading the same topic each get their own full copy.
  5. Offset tracking — each consumer (or consumer group) tracks its read position per partition independently, enabling replay
    💡 An offset is just the position number of a message inside a partition. Because messages are never removed, remembering an offset is all a consumer needs to resume where it stopped — or rewind and replay old messages.
  6. At-least-once delivery — messages are not removed after consumption; consumers must explicitly commit offsets to advance
    💡 At-least-once delivery = every message arrives one or more times, never zero times, so a crash costs you a repeat rather than a lost message. The price is that consumers must tolerate duplicates. Learn more →

Non-Functional Requirements

  1. Thread-safety — concurrent producers and consumers must not corrupt shared state (messages, offsets)
    💡 Thread-safety = the code still behaves correctly when several threads run it at the same instant. Two producers appending to one partition in the same millisecond must not both claim offset 42.
  2. Ordering guarantee within a partition — messages in a single partition are consumed in the exact order they were published
  3. Independent consumer progress — different consumer groups reading the same partition maintain separate offsets without interference

Core Entities

Entity Description
Topic Named channel that holds one or more partitions. Entry point for publishers.
Partition Ordered, append-only log of messages within a topic. Unit of parallelism.
Message Immutable payload with an offset, optional key, value, and timestamp.
Producer Publishes messages to a topic, selecting partition via key hash or round-robin.
Consumer Reads messages from assigned partitions, tracks its own offset.
ConsumerGroup Logical group of consumers; partitions are distributed among members.
Offset Integer position in a partition’s log, tracked per consumer-group per partition.

💡 Immutable (see Message) = once the object is constructed none of its fields ever change. That is why a single Message can be handed to every consumer group at once with no copying and no locking.

💡 An append-only log is a list that only ever grows at the end — nothing is edited or deleted in place. That property is what makes an offset a permanently valid address for a message.


Class Diagram

classDiagram
    class Message {
        -int offset
        -String key
        -String value
        -long timestamp
    }

    class Partition {
        -int id
        -List~Message~ messages
        -ReentrantReadWriteLock lock
        +append(Message) int
        +read(int offset, int count) List~Message~
        +getLatestOffset() int
    }

    class Topic {
        -String name
        -List~Partition~ partitions
        +publish(String key, String value)
        +getPartition(int id) Partition
        +getPartitionCount() int
    }

    class Producer {
        -String id
        +publish(Topic, String key, String value)
    }

    class Consumer {
        -String id
        -String groupId
        -Map~Partition, Integer~ currentOffsets
        +poll(Partition, int maxMessages) List~Message~
        +commitOffset(Partition, int offset)
        +getOffset(Partition) int
    }

    class ConsumerGroup {
        -String groupId
        -List~Consumer~ consumers
        -Map~Partition, Consumer~ assignment
        -Map~Partition, Integer~ committedOffsets
        +addConsumer(Consumer)
        +removeConsumer(Consumer)
        +rebalance(List~Partition~)
        +commitOffset(Partition, int offset)
        +getCommittedOffset(Partition) int
    }

    class PubSubBroker {
        -Map~String, Topic~ topics
        -Map~String, ConsumerGroup~ groups
        -ReentrantLock lock
        +createTopic(String name, int partitions) Topic
        +getTopic(String name) Topic
        +createConsumerGroup(String groupId) ConsumerGroup
        +subscribe(String groupId, String topicName)
    }

    PubSubBroker --> Topic
    PubSubBroker --> ConsumerGroup
    Topic --> Partition
    Partition --> Message
    ConsumerGroup --> Consumer
    ConsumerGroup --> Partition : assignment
    Producer --> Topic : publishes to
    Consumer --> Partition : reads from

💡 Read each arrow as “holds a reference to”: PubSubBroker --> Topic means the broker keeps the topic objects, and the labelled arrows (publishes to, reads from) name the relationship instead of ownership. Learn more →

Key classes:

  • PubSubBroker — the single front door, the “mini-Kafka” itself. It owns the registry of topics and consumer groups, and is the only place where either gets created, so nothing else has to know how they are wired together.
  • Topic — owns its list of partitions and the routing decision. When you publish, the topic is what picks which partition the message lands in (key hash or round-robin).
  • Partition — owns the actual messages and the lock that guards them. Everything about ordering lives here: a message gets its offset at append time and never moves.
  • Consumer — owns its own in-progress read position per partition, which is how one consumer can be mid-batch without affecting anybody else.
  • ConsumerGroup — owns two things the individual consumers must not own: the partition-to-consumer assignment, and the committed offsets. Keeping committed offsets at group level is why a replacement consumer can pick up exactly where a dead one left off.

Design Patterns

Pattern Where Why
Observer Consumers subscribe to topics; partitions notify on new messages (optional push mode) Decouples producers from consumers. Adding new consumers requires zero producer changes.
Iterator Consumer’s poll() method iterates over partition log from current offset Clean sequential access without exposing internal list. Offset acts as a cursor.
Factory PubSubBroker.createTopic() and createConsumerGroup() Centralizes creation logic, ensures consistent initialization and registration.

💡 Observer pattern = the thing being watched keeps a list of listeners and notifies them when something changes. It matters here because a producer can publish without knowing a single thing about who, or how many, will read. Learn more →