LLD

Full Designs

Pub-Sub

A weak answer keeps a list of subscribers and calls each one when a message comes in. We build an in-memory broker that holds up when the interviewer pushes: how every subscriber reads at its own pace, what happens when one crashes before it acks, why a message that keeps failing must not block the rest, and what is deleted when the log is full.

"Design a pub-sub system" sounds like a map from topic names to lists of callbacks. A weak answer keeps that map, and publish loops over the list and calls each subscriber. That is the Observer pattern, and it breaks in the ways a broker exists to fix. A slow subscriber makes the publisher wait. A subscriber that crashes loses the message. A subscriber that joins late never sees what came before.

The interviewer is checking a few specific things. Every subscriber must read every message at its own pace. A message must survive a subscriber that crashes halfway through it, so the design must say when a message counts as done. A message that fails every time must not block the ones behind it. And many publishers and many workers touch the same topic at once, so the design must say which state each lock guards.

This article follows a 45 minute interview. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

A broker at a glance
The checkout service publishes order-9 to the orders topic (1), and it gets offset 8. The topic keeps its newest 5 messages, so offsets 0 to 3 are already deleted. The email and billing subscriptions each keep their own position in the same log (2). A Dispatcher on the subscriber's own thread polls for messages (3) and acks or nacks each one (4). A message that fails too many times goes to the subscription's dead-letter topic (5).The checkout service publishes order-9 to the orders topic (1), and it gets offset 8. The topic keeps its newest 5 messages, so offsets 0 to 3 are already deleted. The email and billing subscriptions each keep their own position in the same log (2). A Dispatcher on the subscriber's own thread polls for messages (3) and acks or nacks each one (4). A message that fails too many times goes to the subscription's dead-letter topic (5).
One log per topic. Each subscription keeps its own place in it. The checkout service publishes order-9 to the orders topic (1), and it gets offset 8. The topic keeps its newest 5 messages, so offsets 0 to 3 are already deleted. The email and billing subscriptions each keep their own position in the same log (2). A Dispatcher on the subscriber's own thread polls for messages (3) and acks or nacks each one (4). A message that fails too many times goes to the subscription's dead-letter topic (5).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Does each subscriber get every message, or do they share them?Each named subscription gets every message. Workers of one subscription share its messagesOne log per topic, and a position per subscription
Does the broker call the subscriber, or does the subscriber ask?The subscriber asks. A small worker class turns that into a callbackpoll, ack and nack on Subscription, and a Dispatcher
Can a message be lost, or seen twice?Seen twice is allowed. Lost is not, while the topic still keeps itLeases and acks: at-least-once delivery
How long does a subscriber have to finish a message?An ack timeout per subscription, from 1 second to 10 minutesA due time on every message handed out
What happens to a message that fails every time?After a set number of attempts, it goes to a dead-letter topicmaxAttempts, and a second topic per subscription
Does order matter?Billing needs strict order. Email does notA window of unacked messages, set per subscription, and an ack timeout longer than the slowest handler
Where does a new subscriber start?At the oldest kept message, or at the next one publishedThe StartFrom enum
How long are messages kept?The newest N per topic, up to 100,000A ring buffer, and a count of skipped messages
Do many publishers and workers run at once?YesA lock per topic, and a lock per subscription

The first question matters most. If subscribers share messages, the broker is a queue, and a message can be deleted once one worker acks it. If each subscriber gets every message, the broker must keep each message until every subscriber is done, or keep it for a fixed time and let each subscriber track its own place. We take the second answer and argue for it in "One log, a position each" below.

Requirements

Functional:

  1. A topic is created with the number of messages it keeps. publish appends a message and returns its offset, which counts up from 0.
  2. A subscription has a name and starts at the oldest kept message or at the next one published. Each subscription gets every message, and its position is its own.
  3. poll hands out up to a given number of messages, in offset order the first time, and never more unacked messages than the subscription's window.
  4. ack marks a message done. A message not acked within the ack timeout is handed out again. nack hands it out again after a backoff. An ack from a delivery that no longer holds the message changes nothing.
  5. A message handed out maxAttempts times without an ack goes to the subscription's dead-letter topic, and the subscription moves on.
  6. A topic keeps its newest N messages. A subscription that falls behind skips the deleted ones and counts them.
  7. seek moves a subscription to an offset, so it can replay.
  8. A Dispatcher runs the subscriber's handler on the subscriber's own thread. A handler that throws counts as a nack, a slow handler slows only its own subscription, and stopping a worker does not use up a message's attempts, up to maxAttempts times.

Out of scope: order per key with many workers, publishers that retry and publish twice, filters, delayed messages, unsubscribing, and keeping messages on disk. We come back to these at the end, because each is a likely follow-up.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Many threads at once. Publishers append while workers poll and ack the same topic.
  • Subscribers that fail. A handler can throw, hang or crash between finishing a message and acking it.
  • Rules that change. How long to wait before a retry sits behind an interface.
  • Testable time. Leases and retry waits depend on the time, so the broker takes a Clock.

Finding the classes

Picking the nouns out of the requirements gives a first list. Three of them hold state that changes and that several threads touch: the broker's set of topics, a topic's log, and a subscription's position and unacked messages. They become classes. The worker that runs a handler is a fourth class.

From nouns to classes
Broker, topic, subscription and worker become classes. Message, a hand-out of a message and the subscription's settings become records, and where to start becomes an enum. The retry wait and the subscriber's code become interfaces. Six nouns are dropped. A publisher is any caller of publish. A subscriber service is outside the code and gives a handler. An offset is a long. A queue per subscriber becomes a position in one shared log. A dead-letter queue is one more Topic. An ack timer is a due time that poll checks.Broker, topic, subscription and worker become classes. Message, a hand-out of a message and the subscription's settings become records, and where to start becomes an enum. The retry wait and the subscriber's code become interfaces. Six nouns are dropped. A publisher is any caller of publish. A subscriber service is outside the code and gives a handler. An offset is a long. A queue per subscriber becomes a position in one shared log. A dead-letter queue is one more Topic. An ack timer is a due time that poll checks.
Most nouns become classes, records or interfaces. Six do not. Broker, topic, subscription and worker become classes. Message, a hand-out of a message and the subscription's settings become records, and where to start becomes an enum. The retry wait and the subscriber's code become interfaces. Six nouns are dropped. A publisher is any caller of publish. A subscriber service is outside the code and gives a handler. An offset is a long. A queue per subscriber becomes a position in one shared log. A dead-letter queue is one more Topic. An ack timer is a due time that poll checks.
Decision

Should a publisher be a class?

A Publisher class that a service creates for each topic

It reads well in a diagram, and a publisher could batch its messages. But no rule in this design reads anything about who published. A Publisher would hold a topic name and forward one call.

No: a publisher is any caller of publishOur pick

Broker.publish(topic, payload) is the whole API. If a rule ever needs the publisher, such as a quota per service, a class can come then.

Data or behaviour?

Some classes only carry values that never change: a message, one hand-out of it, a subscription's settings. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString for free. Broker, Topic, Subscription and Dispatcher are ordinary classes, because their state changes and their methods guard those changes.

The class diagram

The classes and how they connect
Broker owns every Topic and every Subscription. It reads the time from a Clock and passes the same Clock to each of them. A Subscription reads its topic's log and appends dead letters to a second topic. It uses Backoff, which the records FixedBackoff and ExponentialBackoff implement. A Dispatcher polls one Subscription and calls one MessageHandler. Methods marked ~ are package-private, so only the broker package calls them. The records and the enum along the bottom are the values the classes above hold. NoSuchTopicException is not drawn.Broker owns every Topic and every Subscription. It reads the time from a Clock and passes the same Clock to each of them. A Subscription reads its topic's log and appends dead letters to a second topic. It uses Backoff, which the records FixedBackoff and ExponentialBackoff implement. A Dispatcher polls one Subscription and calls one MessageHandler. Methods marked ~ are package-private, so only the broker package calls them. The records and the enum along the bottom are the values the classes above hold. NoSuchTopicException is not drawn.
Broker coordinates. The log and each subscription have their own lock. Broker owns every Topic and every Subscription. It reads the time from a Clock and passes the same Clock to each of them. A Subscription reads its topic's log and appends dead letters to a second topic. It uses Backoff, which the records FixedBackoff and ExponentialBackoff implement. A Dispatcher polls one Subscription and calls one MessageHandler. Methods marked ~ are package-private, so only the broker package calls them. The records and the enum along the bottom are the values the classes above hold. NoSuchTopicException is not drawn.

The classes fall into three groups:

  • Data: the records Message, Delivery, SubscriptionConfig and SubscriptionStats, and the enum StartFrom.
  • The core: Broker, Topic and Subscription. Broker creates topics and subscriptions. Topic guards its log with its own lock, and each Subscription guards its position with its own lock.
  • Rules and outside code: the Backoff interface with two records behind it, and MessageHandler, the subscriber's code, which Dispatcher calls.

Building it

One log, a position each

There are two ways to give every subscriber every message. The broker can copy each message into a queue per subscriber. Or it can keep one log per topic and let each subscriber remember how far it has read.

A queue each, or one log
On the left, publish copies each message into the billing and email queues, and an ack removes the copy. A new audit subscriber gets an empty queue, so it has nothing to replay. On the right, publish appends once to a log that keeps 5 messages. Billing reads from 5 and email from 7. Audit starts at 3, the oldest kept message. Offsets 0 to 2 are gone whether or not anyone read them, so a subscriber still behind them skips them.On the left, publish copies each message into the billing and email queues, and an ack removes the copy. A new audit subscriber gets an empty queue, so it has nothing to replay. On the right, publish appends once to a log that keeps 5 messages. Billing reads from 5 and email from 7. Audit starts at 3, the oldest kept message. Offsets 0 to 2 are gone whether or not anyone read them, so a subscriber still behind them skips them.
A log lets a new subscriber read the past. On the left, publish copies each message into the billing and email queues, and an ack removes the copy. A new audit subscriber gets an empty queue, so it has nothing to replay. On the right, publish appends once to a log that keeps 5 messages. Billing reads from 5 and email from 7. Audit starts at 3, the oldest kept message. Offsets 0 to 2 are gone whether or not anyone read them, so a subscriber still behind them skips them.

Topic holds the log. It is a ring of fixed size, so keeping the newest N messages costs nothing extra:

broker/Topic.javalines 15–64 of 69
final class Topic {    private final String name;    private final Message[] ring;    private final Clock clock;    private long endOffset;     Topic(String name, int retain, Clock clock) {        this.name = name;        this.ring = new Message[retain];        this.clock = clock;    }     String name() {        return name;    }     int retain() {        return ring.length;    }     synchronized long append(String payload) {        Message message = new Message(name, endOffset, payload, clock.instant());        ring[slot(message.offset())] = message;        endOffset = message.offset() + 1;        return message.offset();    }     /** Up to max messages from offset from, or from the oldest kept message if from has been deleted. */    synchronized List<Message> read(long from, int max) {        List<Message> messages = new ArrayList<>();        for (long offset = Math.max(from, oldestKept()); offset < endOffset && messages.size() < max; offset++) {            messages.add(ring[slot(offset)]);        }        return messages;    }     /** The offset of the oldest message still kept. */    synchronized long firstOffset() {        return oldestKept();    }     /** The offset the next message will get. */    synchronized long endOffset() {        return endOffset;    }     /** Callers hold the topic's lock. */    private long oldestKept() {        return Math.max(0, endOffset - ring.length);    }

endOffset is the offset the next message gets. append builds the Message first, then writes it into slot offset % retain, then moves endOffset on. When the ring is full, the new message lands on the oldest one. oldestKept is the oldest offset still in the ring. read starts at from, or at the oldest kept offset if from has been deleted. Every method callers can reach takes the topic's lock, and the private helpers run under it. The only call out under that lock is append reading the clock.

Decision

One log per topic, or a queue per subscriber?

A queue per subscriber; publish copies the message into each

An ack deletes the copy, so memory follows what is still unread. But publish does work for every subscriber, a new subscriber cannot read anything published before it joined, and replaying last hour's messages is impossible.

One log per topic; each subscription keeps its own positionOur pick

Publish is one append, however many subscribers there are. A new subscriber can start at the oldest kept message, and replay is moving a number back. The cost is that reading no longer deletes anything, so the design must decide when messages go. That is "Retention and replay" below.

Subscribing

broker/Broker.javalines 62–82 of 106
    public synchronized Subscription subscribe(String topicName, String name, StartFrom start, SubscriptionConfig config) {        Topic topic = topic(topicName);        checkName(name, "subscription");        Objects.requireNonNull(start, "start");        Objects.requireNonNull(config, "config");        String key = topicName + "/" + name;        Subscription existing = subscriptions.get(key);        if (existing != null) {            if (!existing.config().equals(config)) {                throw new IllegalStateException(key + " already exists with other settings");            }            return existing;        }        // Dead-letter names have dots, which topic names cannot, so they never clash.        Topic deadLetters = new Topic(topicName + "." + name + ".dead-letter", topic.retain(), clock);        long position = start == StartFrom.EARLIEST ? topic.firstOffset() : topic.endOffset();        Subscription created = new Subscription(name, topic, deadLetters, config, position, clock, receipts);        topics.put(deadLetters.name(), deadLetters);        subscriptions.put(key, created);        return created;    }

A subscription starts at firstOffset for EARLIEST or at endOffset for LATEST. subscribe also creates the subscription's dead-letter topic, named orders.email.dead-letter for the email subscription on orders. Topic names allow only lower-case letters, digits and hyphens, so a dead-letter name, which has dots, never clashes with a topic someone creates.

A service that restarts calls subscribe again with the same name. It must not start from scratch. So subscribe returns the existing subscription, with its position, when the settings are equal, and start is ignored. Different settings are refused with IllegalStateException. createTopic follows the same rule for a topic's size. Both are programmer errors, so they throw.

Who calls whom

A subscriber's code has to run somewhere. The broker can call it, or the subscriber can ask the broker for messages.

Decision

Does the broker push to subscribers, or do they pull?

Push: publish calls every subscriber's handler

It is the simplest code, and it is Observer. But publish waits for the slowest handler, and a handler that throws or hangs breaks publish for everyone.

Push from the broker's own threads, one per subscription

Publish no longer waits. But the broker now owns threads it must size, start and stop, and it runs code it did not write.

Pull: the subscriber polls and acks; a Dispatcher on its own thread runs the handlerOur pick

The broker never runs subscriber code, so a slow or broken handler cannot block the broker or another subscription. Each subscriber decides how many threads to run. The cost is that an idle Dispatcher sleeps between empty polls, so a new message can wait up to that pause.

Dispatcher is that worker:

consumer/Dispatcher.javalines 39–115 of 122
    /** One round: polls once and handles what came back. Returns how many messages it was given. */    public int runOnce() {        List<Delivery> batch = subscription.poll(batchSize);        for (Delivery delivery : batch) {            if (stopping()) {                // Shutting down is not the message's fault, so it goes back without using up an attempt.                subscription.release(delivery);                continue;            }            switch (handle(delivery.message())) {                case DONE -> acknowledge(delivery);                case FAILED -> retryLater(delivery);                case INTERRUPTED -> subscription.releaseInterrupted(delivery);            }        }        return batch.size();    }    private Outcome handle(Message message) {        try {            handler.handle(message);            return Outcome.DONE;        } catch (InterruptedException e) {            Thread.currentThread().interrupt();            return Outcome.INTERRUPTED;        } catch (Exception e) {            if (Thread.currentThread().isInterrupted()) {                // Many interruptible calls throw something else, such as ClosedByInterruptException.                return Outcome.INTERRUPTED;            }            // A real system logs e with the topic and offset.            return Outcome.FAILED;        }    }

runOnce polls, calls the handler for each message, and acks or nacks it. handle treats any exception from the handler as a failure, except an InterruptedException, or any exception thrown while the thread is interrupted. We treat those as a shutdown of the worker. run loops over runOnce and sleeps idlePause when there was nothing. The caller hands a Dispatcher to its own thread or pool, as on the Thread pool page. Several dispatchers on one subscription share its messages.

Stopping must not hurt healthy messages. shutdownNow interrupts the worker, and a handler blocked in a call that answers interrupts, such as Thread.sleep or HttpClient.send, then throws at once, for this message and every later one in the batch. A plain socket read ignores the interrupt. If those counted as failures, a shutdown would use up attempts and could dead-letter good messages. So once stop has been called or the thread is interrupted, runOnce hands each remaining message back with Subscription.release, which makes it due at once and gives its attempt back, because its handler never ran. An interrupted handler's own message goes back with releaseInterrupted, which also gives its attempt back while it has refunds left, and the interrupt flag stays set for the caller. Stopping takes at most the handler that is running now plus one idlePause.

broker/Subscription.javalines 130–184 of 210
    /** Gives back a message whose handler never ran, due at once and with its attempt returned. */    public synchronized boolean release(Delivery delivery) {        return giveBack(delivery, false);    }     /** Gives back a message whose handler was interrupted. Its attempt is returned for the first maxAttempts of these. */    public synchronized boolean releaseInterrupted(Delivery delivery) {        return giveBack(delivery, true);    }    private boolean giveBack(Delivery delivery, boolean handlerRan) {        Unacked entry = heldBy(delivery);        if (entry == null) {            return false;        }        // Only interrupted handlers count toward the cap, so a message that keeps stopping workers is still dead-lettered.        if (!handlerRan || entry.interruptions < config.maxAttempts()) {            entry.attempts--;        }        if (handlerRan) {            entry.interruptions++;        }        entry.receipt = NOT_HELD;        entry.dueAt = clock.millis();        return true;    }

The dispatcher trusts an InterruptedException to mean shutdown, so a handler that throws one by itself stops its worker, and the worker stays stopped until the caller restarts it. Without a cap, each restart would get the message back with its attempt refunded. So giveBack counts only the releases whose handler ran, in interruptions, and refunds the attempt for the first maxAttempts of them. After that, each one uses up an attempt, so the message reaches the dead-letter topic after at most 2 × maxAttempts runs of its handler. A message handed back untouched never counts, so the healthy messages behind a bad one are never dead-lettered for it. A handler that throws an Error is different: it ends the worker like a crash, and the rest of its batch comes back by lease.

At-least-once: leases and acks

A message handed to a worker is not done until the worker says so. The worker can crash after taking it, and the broker must notice.

Decision

When is a message done for a subscription?

As soon as poll hands it out (at most once)

There is nothing to track after poll. But a worker that crashes halfway through loses the message for good.

When the subscriber acks it; until then it comes back (at least once)Our pick

A crash loses nothing: the message comes back when its lease runs out. The cost is duplicates. A worker can finish the work and crash just before acking, and the broker cannot tell that apart from a worker that never started. So handlers must be safe to run twice, for example by keeping the topic and offset of every order they have charged.

Exactly once

The broker cannot promise this alone. The gap between "the work is done" and "the ack arrived" is in the subscriber's code. Exactly-once needs the subscriber to store its result and its position together, in one transaction of its own.

poll does the bookkeeping:

broker/Subscription.javalines 50–86 of 210
    /** Hands out up to max messages: first any whose lease or retry wait is over, then new ones from the log. */    public synchronized List<Delivery> poll(int max) {        if (max < 1 || max > MAX_POLL) {            throw new IllegalArgumentException("poll takes 1 to " + MAX_POLL + " messages: " + max);        }        long now = clock.millis();        long leaseEnds = Math.addExact(now, config.ackTimeout().toMillis());        List<Delivery> batch = new ArrayList<>();        Iterator<Unacked> due = unacked.values().iterator();        while (due.hasNext() && batch.size() < max) {            Unacked entry = due.next();            if (entry.dueAt > now) {                continue;            }            if (entry.attempts >= config.maxAttempts()) {                deadLetter(entry);                due.remove();            } else {                batch.add(handOut(entry, leaseEnds));            }        }        int room = Math.min(max - batch.size(), config.maxInFlight() - unacked.size());        if (room > 0) {            List<Message> fresh = topic.read(position, room);            if (!fresh.isEmpty()) {                // Messages between position and the first one read were deleted before we got to them.                skipped += fresh.get(0).offset() - position;                position = fresh.get(fresh.size() - 1).offset() + 1;            }            for (Message message : fresh) {                Unacked entry = new Unacked(message);                unacked.put(message.offset(), entry);                batch.add(handOut(entry, leaseEnds));            }        }        return batch;    }
  1. Work out the lease end (line 56), before anything changes. Math.addExact throws on an overflowing clock, and the poll then takes nothing.
  2. Hand out what is due again (lines 59 to 70). unacked is a TreeMap by offset. An entry is due when its dueAt has passed. If it has used all its attempts, it is dead-lettered. Otherwise it goes out again.
  3. Fill the window from the log (lines 71 to 84). room is what the batch and the window both allow. Each new message gets an Unacked entry, and position moves past it.

handOut gives the entry a new attempt number, a new receipt and a due time 30 seconds away, for a 30 second ack timeout. There is no timer thread. A lease runs out because the next poll finds dueAt in the past.

Late acks and receipts

Worker A takes a message and stalls. Its lease runs out, and worker B gets the message. Then A wakes up and acks.

broker/Subscription.javalines 88–167 of 210
    /** The message is done. Returns false, and changes nothing, if this delivery no longer holds it. */    public synchronized boolean ack(Delivery delivery) {        Unacked entry = heldBy(delivery);        if (entry == null) {            return false;        }        unacked.remove(entry.message.offset());        return true;    }    private Unacked heldBy(Delivery delivery) {        Objects.requireNonNull(delivery, "delivery");        Unacked entry = unacked.get(delivery.message().offset());        if (entry == null || entry.receipt != delivery.receipt()) {            return null;        }        return entry;    }

Every delivery carries a receipt, a number from one AtomicLong that the broker shares across all its subscriptions. heldBy finds the entry by offset, and accepts the call only if the receipt is the entry's current one (line 163). A's ack carries the old receipt, so it returns false and changes nothing. B's ack works. A second ack of the same delivery finds no entry and also returns false, so acks are safe to repeat.

If A's lease has run out but nobody has polled since, the entry still has A's receipt, and A's ack is accepted. A message is A's until someone else is given it.

Decision

What does an ack name?

The offset

It is simple. But A's late ack would mark the message done while B is still working on it, and a late nack from A could push B's attempt to the dead-letter topic.

The delivery's receipt; an ack or nack from an older delivery changes nothingOur pick

Only the worker that holds the message now can settle it. The receipts come from one counter for the whole broker, so a delivery from the email subscription can never ack billing's message at the same offset. The cost is one more duplicate when a late worker did finish: B does the work again.

Retries and dead letters

A handler that throws means the message failed. Retrying at once often fails again, because a mail server that was down a millisecond ago is usually still down.

ExponentialBackoff doubles the wait up to a cap:

retry/ExponentialBackoff.javalines 16–28 of 29
    @Override    public Duration delayAfter(int attempt) {        if (attempt < 1) {            throw new IllegalArgumentException("Attempts start at 1: " + attempt);        }        long capMillis = cap.toMillis();        long delayMillis = first.toMillis();        // Stops doubling at the cap, so the value never grows past 20 minutes and cannot overflow.        for (int i = 1; i < attempt && delayMillis < capMillis; i++) {            delayMillis *= 2;        }        return Duration.ofMillis(Math.min(delayMillis, capMillis));    }

The loop stops doubling once the wait reaches the cap, so it never overflows, even for attempt 100. With a first wait of 1 second and a cap of 8, the waits are 1, 2, 4, 8, 8 seconds. Both backoffs are records, so two equal settings compare equal when a service subscribes again.

nack uses it:

broker/Subscription.javalines 98–117 of 210
    /** The subscriber failed. The message is retried after the backoff, or dead-lettered on its last attempt. */    public synchronized boolean nack(Delivery delivery) {        Unacked entry = heldBy(delivery);        if (entry == null) {            return false;        }        if (entry.attempts >= config.maxAttempts()) {            deadLetter(entry);            unacked.remove(entry.message.offset());            return true;        }        Duration delay = config.backoff().delayAfter(entry.attempts);        if (delay == null || delay.isNegative() || delay.compareTo(Backoff.MAX_DELAY) > 0) {            throw new IllegalStateException("The backoff gave a delay of " + delay);        }        long retryAt = Math.addExact(clock.millis(), delay.toMillis());        entry.receipt = NOT_HELD;        entry.dueAt = retryAt;        return true;    }

On the last attempt, the message goes to the dead-letter topic at once. Otherwise nack asks the backoff for the wait and checks the answer before changing anything. A null, a negative wait or one over 10 minutes is a bug in the backoff, so nack throws IllegalStateException, and the delivery still holds the message. Dispatcher catches that and moves on to its next message, and the lease brings the failed one back. Only after the checks does the entry lose its receipt and get a new due time.

One message in one subscription
poll hands out order-3 with a receipt, an attempt number and a 30 second lease (1). An ack ends it (2). A nack makes it due again after the backoff (3), and so does a lease that runs out with no ack (4). The next poll hands it out again with a new receipt and the next attempt number (5). When attempts reach maxAttempts, it goes to the dead-letter topic instead (6). A nack on the last attempt sends it there at once (7). An ack or nack carrying an old receipt returns false and changes nothing.poll hands out order-3 with a receipt, an attempt number and a 30 second lease (1). An ack ends it (2). A nack makes it due again after the backoff (3), and so does a lease that runs out with no ack (4). The next poll hands it out again with a new receipt and the next attempt number (5). When attempts reach maxAttempts, it goes to the dead-letter topic instead (6). A nack on the last attempt sends it there at once (7). An ack or nack carrying an old receipt returns false and changes nothing.
A message stays unacked until an ack, a dead letter or a seek. poll hands out order-3 with a receipt, an attempt number and a 30 second lease (1). An ack ends it (2). A nack makes it due again after the backoff (3), and so does a lease that runs out with no ack (4). The next poll hands it out again with a new receipt and the next attempt number (5). When attempts reach maxAttempts, it goes to the dead-letter topic instead (6). A nack on the last attempt sends it there at once (7). An ack or nack carrying an old receipt returns false and changes nothing.
Decision

What happens to a message that keeps failing?

Retry it forever

Nothing is lost. But one bad message, such as an order with a missing email address, is retried for ever, and in a window of 1 nothing behind it moves.

Drop it after N attempts, and log it

The subscription moves on. But the message is gone, and fixing the bug cannot bring it back.

After maxAttempts deliveries, publish it to the subscription's own dead-letter topicOur pick

The subscription moves on, and the newest N dead letters are kept, where N is the size of the topic. The dead-letter topic is an ordinary Topic, so a support tool can subscribe to it, read the failures, and publish them again once the bug is fixed. A dead letter carries only the payload, which costs two things. The support tool cannot see which topic and offset it came from, or why it failed. And once it is published again, it has a new offset, so a handler that removes duplicates by topic and offset cannot tell it was handled before.

deadLetter appends to the dead-letter topic before the entry is removed from unacked, so the message is always in one of the two places.

A dead letter is not always a failure. If a handler is still running when its last lease runs out, the next poll dead-letters the message. The handler may then succeed, and its ack returns false because it no longer holds the message. Dispatcher counts these in lateAcks(), and a real system logs each one. This is the same batch-time limit that "Many publishers, many workers" warns about below.

Order

Decision

What order does a subscription see?

Strict order always: one message unacked at a time, for everyone

Every subscription sees retries in order. But a subscription that sends emails waits for each one before starting the next.

Offset order on first delivery; each subscription picks its windowOur pick

maxInFlight caps how many messages a subscription holds unacked. With a window of 1, message 6 is not handed out until message 5 is acked or dead-lettered, so even retries are handed out in order. That is an order of hand-outs, not of work: if worker A is still on 5 when its lease runs out, B gets 5, acks it, and gets 6 while A is still running. So strict order also needs an ack timeout longer than the slowest handler. With a wider window, first deliveries are in offset order, but a retry of 5 can come after 6. Billing picks 1 and email picks 10.

Order per key, with many workers

Orders for one customer stay in order while different customers run in parallel. But it needs the topic split into partitions by key, and a way to give each partition to one worker. We come back to it in the follow-ups.

Retention and replay

A log that is never deleted from grows for ever. Something has to go.

Decision

When is a message deleted?

When every subscription has acked it

No subscriber ever misses a message. But one subscription that stops reading keeps every message in memory, and the broker runs out of memory because of one dead service.

Keep the newest N per topic, whatever the subscriptions have read; count what each one skipsOur pick

Memory has a limit known up front: N messages for the topic, plus a dead-letter ring of N for each subscription, made when it subscribes, and up to its window of unacked messages. A dead subscriber hurts nobody else. The cost is that a subscription that falls more than N behind loses messages. poll notices the gap, moves position to the oldest kept message, and adds the gap to skipped, so the loss shows up in stats() instead of passing silently.

A message already handed out is safe from this. Its Unacked entry holds the Message itself, so a redelivery works even after the ring has moved past it.

seek moves a subscription's position for a replay. It keeps the offset inside the log, from the oldest kept message to the end, and clears unacked. Any delivery from before the seek then holds a receipt that matches nothing. A seek forward also drops the messages that were held or waiting for a retry, without dead-lettering them, so a replay tool should seek only backwards or to the end on purpose.

broker/Subscription.javalines 119–128 of 210
    /** Moves the position to offset, kept inside the log, and forgets every unacked message. Returns the new position. */    public synchronized long seek(long offset) {        if (offset < 0) {            throw new IllegalArgumentException("An offset cannot be negative: " + offset);        }        long target = Math.max(topic.firstOffset(), Math.min(offset, topic.endOffset()));        unacked.clear();        position = target;        return target;    }

Many publishers, many workers

Two publishes, one slot
On the left there is no lock. Publisher A and publisher B both read endOffset 7. A writes order-9 into slot 7, then B writes order-10 into the same slot, so both get offset 7 and order-9 is lost. On the right, append() holds the topic lock. A writes slot 7 and moves endOffset to 8 in one step. B waits, then writes slot 8.On the left there is no lock. Publisher A and publisher B both read endOffset 7. A writes order-9 into slot 7, then B writes order-10 into the same slot, so both get offset 7 and order-9 is lost. On the right, append() holds the topic lock. A writes slot 7 and moves endOffset to 8 in one step. B waits, then writes slot 8.
Without the lock, two publishers can get the same offset. On the left there is no lock. Publisher A and publisher B both read endOffset 7. A writes order-9 into slot 7, then B writes order-10 into the same slot, so both get offset 7 and order-9 is lost. On the right, append() holds the topic lock. A writes slot 7 and moves endOffset to 8 in one step. B waits, then writes slot 8.

The design has two kinds of lock, and each guards one thing:

  • The topic's lock guards the ring and endOffset. append and read hold it for one write or one copy of at most 1,000 messages.
  • Each subscription's lock guards its position, unacked, skipped and deadLettered. poll, ack, nack, both releases, seek and stats hold it.

poll takes the topic's lock inside the subscription's lock, to read the log or to append a dead letter. Nothing takes them the other way round, because a topic never calls a subscription. So the two can never deadlock. Broker has a third lock, for createTopic and subscribe only. publish reads the topic map, a ConcurrentHashMap, without it.

No lock is held while a handler runs. Dispatcher calls the handler after poll has returned and before ack starts. A handler can publish, even to its own topic, without deadlock. A handler that hangs holds only its own dispatcher's thread. The rest of its batch waits too, so the batch size times the time per message should fit inside the ack timeout. Otherwise their leases run out, other workers get them as duplicates, and a message on its last attempt can end up dead-lettered after it was handled.

The project includes a check, demo/RaceCheck.java. Eight publishers send 5,000 messages each to one topic at the same moment. Billing reads with one dispatcher and a window of 1, and email reads with four dispatchers that share one subscription:

$ java demo.RaceCheck
8 publishers sent 40,000 messages; 4 email workers share one subscription
Distinct offsets: 40,000. End of the log: 40,000
billing handled 40,000, every offset in order from 0: true
email handled 40,000 distinct, 0 twice
Everything handled within the time limit: true

We also ran it in a scratch copy with synchronized removed from append. Publishers got the same offset and overwrote each other's slot, and each run we tried kept fewer than 20,000 of the 40,000 messages. With the lock removed from poll instead, most runs handed some messages, up to about 60, to two email workers at once, one run gave none, and one never finished. The numbers change from run to run and from machine to machine.

Decision

Where do the locks go?

One lock around the whole broker

It is correct and easy to explain. But every publisher waits for every poll on every topic.

One lock per topic, covering its log and all its subscriptions

Topics never wait for each other. But a busy subscription's polls make publishers to the same topic and every other subscription wait.

One lock per topic's log and one per subscription, always taken in that orderOur pick

Publishers wait only for another append or a short read of the log. Subscriptions wait for each other only while one of them reads the shared log, never for each other's bookkeeping. The cost is a rule to keep: a subscription may take its topic's lock, and a topic may never call a subscription.

The final design

Broker is the core. It owns every Topic and every Subscription, and it reads the time only from the Clock it is given. A Topic guards its ring with its own lock. A Subscription guards its position and its unacked messages with its own lock, and it reaches the retry rule only through Backoff. Subscriber code runs only in a Dispatcher, through MessageHandler, with no lock held. After subscribe returns, every poll and ack goes straight to the subscription, and the broker's own lock is never taken again on that path.

The design we built
This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Broker carries 1, Topic carries 2 and 8, and Subscription carries 4, 6 and 9. Dispatcher carries 3, Delivery carries 5, and SubscriptionConfig carries 7. Purple tags mark Backoff as a Strategy, and Topic and Dispatcher as the buffer and the consumer of Producer-Consumer.This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Broker carries 1, Topic carries 2 and 8, and Subscription carries 4, 6 and 9. Dispatcher carries 3, Delivery carries 5, and SubscriptionConfig carries 7. Purple tags mark Backoff as a Strategy, and Topic and Dispatcher as the buffer and the consumer of Producer-Consumer.
Each decision lands on one class. Two patterns carry the log and the retries. This figure shows the classes from the class diagram, in the same places, with names only. Amber badges match the rows of the table below. Broker carries 1, Topic carries 2 and 8, and Subscription carries 4, 6 and 9. Dispatcher carries 3, Delivery carries 5, and SubscriptionConfig carries 7. Purple tags mark Backoff as a Strategy, and Topic and Dispatcher as the buffer and the consumer of Producer-Consumer.
S.No.The questionWhat we choseWhy
1Should a publisher be a class?No: a publisher is any caller of publishNo rule reads anything about who published
2One log per topic, or a queue per subscriber?One log per topic; each subscription keeps its own positionOne append per message, and new subscribers can read the past
3Does the broker push to subscribers, or do they pull?Pull: the subscriber polls and acks; a Dispatcher on its own thread runs the handlerSubscriber code never runs inside the broker
4When is a message done for a subscription?When the subscriber acks it; until then it comes back (at least once)A crash never loses a handed-out message
5What does an ack name?The delivery's receipt; an ack or nack from an older delivery changes nothingOnly the current holder can settle a message
6What happens to a message that keeps failing?After maxAttempts deliveries, publish it to the subscription's own dead-letter topicThe subscription moves on, and the newest N dead letters are kept
7What order does a subscription see?Offset order on first delivery; each subscription picks its windowBilling gets strict order if its ack timeout beats its slowest handler; email gets speed
8When is a message deleted?Keep the newest N per topic, whatever the subscriptions have read; count what each one skipsMemory is fixed, and one dead subscriber hurts nobody else
9Where do the locks go?One lock per topic's log and one per subscription, always taken in that orderLocks cover short bookkeeping only, never subscriber code

Here is order-3 from the demo, as the email subscription fails it three times:

  1. The checkout service calls Broker.publish. Topic.append takes the orders lock, writes slot 2, and returns offset 2.
  2. Email's Dispatcher.runOnce calls Subscription.poll. It takes the email lock, reads the log under the orders lock inside it, and returns a Delivery with attempt 1 and a 30 second lease.
  3. runOnce calls MessageHandler.handle with no lock held. This is the subscriber's own code, and the mail server is down, so it throws.
  4. runOnce nacks it. Under the email lock, ExponentialBackoff.delayAfter(1) gives 1 second, and the entry waits for it.
  5. On attempt 3, nack appends order-3 to orders.email.dead-letter with Topic.append, and removes it from unacked.

If the handler had succeeded at step 3, ack would have removed the entry, and order-3 would be done for email but still waiting for billing. If the worker had crashed at step 3 instead, the lease would have run out, and the next poll would have handed order-3 out again as the next attempt.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

brokerBroker.java
package broker; import java.time.Clock;import java.util.HashMap;import java.util.Map;import java.util.Objects;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;import java.util.regex.Pattern; import config.StartFrom;import config.SubscriptionConfig;import exception.NoSuchTopicException; /** * The broker: topics, and the subscriptions that read them. Creating topics * and subscriptions takes the broker's lock. Publishing and reading do not. */public class Broker {    public static final int MAX_RETAINED = 100_000;    public static final int MAX_PAYLOAD_CHARS = 10_000;    private static final Pattern NAME = Pattern.compile("[a-z0-9-]{1,40}");     private final Clock clock;    private final Map<String, Topic> topics = new ConcurrentHashMap<>();    private final Map<String, Subscription> subscriptions = new HashMap<>();    private final AtomicLong receipts = new AtomicLong(1);     public Broker(Clock clock) {        this.clock = Objects.requireNonNull(clock, "clock");    }     /** Creates a topic that keeps its newest `retain` messages. Creating it again with the same size does nothing. */    public synchronized void createTopic(String name, int retain) {        checkName(name, "topic");        if (retain < 1 || retain > MAX_RETAINED) {            throw new IllegalArgumentException("A topic keeps 1 to " + MAX_RETAINED + " messages: " + retain);        }        Topic existing = topics.get(name);        if (existing != null) {            if (existing.retain() != retain) {                throw new IllegalStateException(name + " already exists and keeps " + existing.retain() + " messages");            }            return;        }        topics.put(name, new Topic(name, retain, clock));    }     /** Appends the payload to the topic's log and returns its offset. */    public long publish(String topicName, String payload) {        Objects.requireNonNull(payload, "payload");        if (payload.length() > MAX_PAYLOAD_CHARS) {            throw new IllegalArgumentException("A payload is at most " + MAX_PAYLOAD_CHARS + " characters");        }        return topic(topicName).append(payload);    }     /**     * Creates a subscription, or returns the one with this name if its settings     * match. `start` matters only when the subscription is created.     */    public synchronized Subscription subscribe(String topicName, String name, StartFrom start, SubscriptionConfig config) {        Topic topic = topic(topicName);        checkName(name, "subscription");        Objects.requireNonNull(start, "start");        Objects.requireNonNull(config, "config");        String key = topicName + "/" + name;        Subscription existing = subscriptions.get(key);        if (existing != null) {            if (!existing.config().equals(config)) {                throw new IllegalStateException(key + " already exists with other settings");            }            return existing;        }        // Dead-letter names have dots, which topic names cannot, so they never clash.        Topic deadLetters = new Topic(topicName + "." + name + ".dead-letter", topic.retain(), clock);        long position = start == StartFrom.EARLIEST ? topic.firstOffset() : topic.endOffset();        Subscription created = new Subscription(name, topic, deadLetters, config, position, clock, receipts);        topics.put(deadLetters.name(), deadLetters);        subscriptions.put(key, created);        return created;    }     public long firstOffset(String topicName) {        return topic(topicName).firstOffset();    }     public long endOffset(String topicName) {        return topic(topicName).endOffset();    }     private Topic topic(String name) {        Topic topic = topics.get(Objects.requireNonNull(name, "topic"));        if (topic == null) {            throw new NoSuchTopicException(name);        }        return topic;    }     private static void checkName(String name, String what) {        Objects.requireNonNull(name, what);        if (!NAME.matcher(name).matches()) {            throw new IllegalArgumentException("A " + what + " name is 1 to 40 of a-z, 0-9 and '-': " + name);        }    }}
Click a class name in the code to open its fileJava · 106 lines · 923 in the project

demo/Main.java runs a shop's orders topic, which keeps 5 messages, with a clock the demo moves by hand. Billing starts at the beginning with a window of 1. Email starts from now with a window of 10, and its mail server is down for order-3. Billing's worker A crashes holding order-2. Then five more orders arrive, billing restarts, and email replays:

$ java demo.Main
billing starts at offset 0, email starts at offset 2

-- billing holds one message at a time
billing asked for 10 and got order-1 (offset 0, attempt 1)
ack order-1: true
worker A takes order-2 (offset 1, attempt 1), then crashes
29 s later, billing gets nothing
30 s later, worker B gets order-2 (offset 1, attempt 2)
worker A's late ack: false
worker B's ack: true

-- email's mail server is down for order-3
attempt 1 failed. email: position 3, 1 unacked, 0 skipped, 0 dead-lettered
attempt 2 failed. email: position 3, 1 unacked, 0 skipped, 0 dead-lettered
attempt 3 failed. email: position 3, 0 unacked, 0 skipped, 1 dead-lettered
support reads orders.email.dead-letter: order-3 (offset 0, attempt 1)

-- five more orders; the topic keeps 5
orders keeps offsets 3 to 7
email sent [order-4, order-5, order-6, order-7, order-8]
billing gets order-4 (offset 3, attempt 1)
billing: position 4, 1 unacked, 1 skipped, 0 dead-lettered

-- billing restarts and subscribes again
same subscription: true, position 4

-- email replays from the start of the log
seek(0) moved email to offset 3
email sent again [order-4, order-5, order-6, order-7, order-8]

Notice three things in the output. Worker A's late ack is false and worker B's is true, because B holds the newer receipt. Order-3 failed three times, then moved to orders.email.dead-letter, where the support subscription read it as offset 0. And billing shows 1 skipped: order-3 at offset 2 was deleted before billing reached it, so billing jumped to offset 3.

Follow-up questions

After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Keep each customer's orders in order, with many workers."A topic becomes several logs (partitions), and publish takes a key and picks a log by its hash. A subscription keeps a position per partition, and gives each partition to one worker at a time.Backoff, MessageHandler and the dead-letter rule.
"Do not make idle workers sleep."poll takes a wait time and waits on a condition that append signals. It must not keep the subscription's lock while waiting.The ack, lease and retry rules.
"A publisher timed out and published twice."publish takes an idempotency key, and the topic remembers recent keys and returns the first offset.Subscriptions.
"Email only wants orders over $100."A filter in SubscriptionConfig, applied in poll, which moves past messages that do not match.Topic and the publishers.
"Deliver this message at 9 am tomorrow."A deliverAt on Message, and poll holds back messages that are not due. A window of 1 then waits for them, so order and delay trade off.The ack and dead-letter rules.
"Keep messages for 7 days, not the newest N."Topic deletes by publishedAt, so the fixed ring becomes a queue that grows and shrinks.Positions, skipped and replay.
"Survive a restart."Topic writes its log to files, and each subscription saves its position and unacked set.The public API of Broker and Subscription.
"Show where a dead letter came from, and why it failed."Message gains headers. deadLetter fills in the source topic, offset, attempts and the last error, and nack takes that error as a reason.Topic, the receipts and the ack rules.
"Let a service unsubscribe."Broker.unsubscribe removes the subscription, and decides whether its dead-letter topic stays.The topic and the other subscriptions.

In most rows the change lands in Topic or in poll, and the ack and receipt rules stay as they are. Partitions are the biggest change: they turn one position per subscription into one per partition, and add a step that hands partitions to workers.

What the interviewer looks for

Mid-level

A mid-level candidate shows topics, a publish method and subscribers that each get every message. They see that a slow subscriber should not block the publisher, and they add some locking, even if one lock covers the whole broker.

Senior

A senior candidate shows everything above and gives the reasons. They keep one log with a position per subscription, deliver at least once with acks and leases, and explain why exactly-once is not the broker's to promise. They dead-letter a message that keeps failing, and they keep subscriber code outside every lock.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They explain why a late ack must be ignored once someone else holds the message, and how the window trades order against speed. They say what retention costs a subscriber that falls behind, and they bring up partitions as the way to get order per key with many workers.

Common mistakes

  • Calling every subscriber inside publish. The publisher waits for the slowest one, and a subscriber that throws breaks publish for everyone.
  • Deleting a message when it is handed out. A worker that crashes halfway loses it for good.
  • Acking by offset. A worker whose lease ran out can settle a message that another worker now holds.
  • Retrying a failing message for ever. In a window of 1, nothing behind it ever moves.
  • Keeping every message until every subscriber has read it. One dead subscriber fills the broker's memory.
  • Holding a lock while the handler runs. A slow handler blocks every poll and ack on that subscription, so every other worker of that subscription waits behind it.
  • Promising exactly-once. The gap between doing the work and acking it is in the subscriber's code, so the broker can only promise at-least-once, for messages reached before retention deletes them.

Summary

  • Ask first whether subscribers share messages or each get all of them. That decides between a queue and a log.
  • Keep one log per topic, and let each subscription keep its own position in it.
  • Subscribers pull. A Dispatcher runs the handler on the subscriber's own thread, with no lock held.
  • A message is done only when acked. A lease brings it back after a crash, and the receipt makes late acks harmless.
  • A message that keeps failing goes to the subscription's dead-letter topic after maxAttempts.
  • A window of 1 keeps strict order, if the ack timeout is longer than the slowest handler. A wider window is faster, and a retry can come later.
  • Keep the newest N messages per topic, and count what a slow subscription skips.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.