LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 34 OF 42

Design Stack Overflow: Low-Level Design in Java

A question and answer site designed and coded: users, questions, answers, comments and tags, one vote per user per post with change and undo, reputation rules as a Strategy, privileges unlocked by reputation, one accepted answer, search by tag, Observer notifications, racing votes kept exact with an atomic ledger, and the follow-ups, with full Java 17 code.

Patterns usedObserverStrategyState

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 20

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 435 lines, with a small main() demo. Save it as QaSite.java, then run javac QaSite.java && java QaSite.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * A question and answer site: users ask, answer and comment, vote once per post (and can change or undo
 * that vote), earn reputation through pluggable rules, unlock privileges, accept one answer, search by
 * tag and get notified through observers. All point values here are example numbers for this lesson.
 */
public final class QaSite {

    // ---------- users and privileges ----------
    /** Example thresholds, chosen for this lesson. */
    enum Privilege {
        UPVOTE(10), COMMENT_ANYWHERE(20), DOWNVOTE(50), EDIT_ANY_POST(500);

        final int minReputation;

        Privilege(int minReputation) { this.minReputation = minReputation; }
    }

    static final class User {
        final long id;
        final String handle;
        // The raw sum of every reputation event. Undo subtracts exactly what was added.
        private final AtomicInteger raw = new AtomicInteger(1);

        User(long id, String handle) {
            this.id = id;
            this.handle = handle;
        }

        /** Shown with a floor of one; the raw sum stays exact so undoing a vote restores it perfectly. */
        int reputation() { return Math.max(1, raw.get()); }

        void addReputation(int delta) { if (delta != 0) raw.addAndGet(delta); }

        boolean can(Privilege p) { return reputation() >= p.minReputation; }

        @Override
        public String toString() { return handle + "(" + reputation() + ")"; }
    }

    // ---------- posts ----------
    enum PostType { QUESTION, ANSWER }

    enum VoteType {
        UP(1), DOWN(-1);

        final int value;

        VoteType(int value) { this.value = value; }
    }

    abstract static class Post {
        final long id;
        final User author;
        final String body;
        final AtomicInteger score = new AtomicInteger();
        // The vote ledger: one entry per voter, so one vote per user per post by construction.
        final ConcurrentHashMap<Long, VoteType> votes = new ConcurrentHashMap<>();
        final List<Comment> comments = new CopyOnWriteArrayList<>();

        Post(long id, User author, String body) {
            this.id = id;
            this.author = author;
            this.body = body;
        }

        abstract PostType type();

        abstract Question question();
    }

    static final class Question extends Post {
        final String title;
        final Set<String> tags;
        final List<Answer> answers = new CopyOnWriteArrayList<>();
        final AtomicReference<Answer> accepted = new AtomicReference<>();
        final Set<Long> followers = ConcurrentHashMap.newKeySet();

        Question(long id, User author, String title, String body, Set<String> tags) {
            super(id, author, body);
            this.title = title;
            this.tags = Set.copyOf(tags);
        }

        @Override
        PostType type() { return PostType.QUESTION; }

        @Override
        Question question() { return this; }
    }

    static final class Answer extends Post {
        final Question question;

        Answer(long id, User author, String body, Question question) {
            super(id, author, body);
            this.question = question;
        }

        @Override
        PostType type() { return PostType.ANSWER; }

        @Override
        Question question() { return question; }
    }

    record Comment(long id, long postId, User author, String text) {}

    // ---------- Strategy: reputation rules ----------
    interface ReputationRules {
        int authorDelta(PostType type, VoteType vote);

        int voterDelta(PostType type, VoteType vote);

        int acceptedAnswerBonus();

        int acceptorBonus();
    }

    /** Example rules for this lesson: simple, round numbers. */
    static final class SimpleRules implements ReputationRules {
        @Override
        public int authorDelta(PostType type, VoteType vote) {
            if (vote == VoteType.DOWN) return -2;
            return type == PostType.QUESTION ? 5 : 10;
        }

        @Override
        public int voterDelta(PostType type, VoteType vote) {
            // downvoting an answer costs the voter a little, so downvotes are not free
            return vote == VoteType.DOWN && type == PostType.ANSWER ? -1 : 0;
        }

        @Override
        public int acceptedAnswerBonus() { return 15; }

        @Override
        public int acceptorBonus() { return 2; }
    }

    // ---------- Observer: notifications ----------
    enum EventType { NEW_ANSWER, NEW_COMMENT, ANSWER_ACCEPTED }

    record Event(EventType type, long recipientId, String message) {}

    interface SiteListener {
        void onEvent(Event e);
    }

    // ---------- the service ----------
    private final ReputationRules rules;
    private final AtomicLong ids = new AtomicLong();
    private final Map<Long, User> users = new ConcurrentHashMap<>();
    private final Map<Long, Post> posts = new ConcurrentHashMap<>();
    private final Map<String, Set<Long>> questionsByTag = new ConcurrentHashMap<>();
    private final List<SiteListener> listeners = new CopyOnWriteArrayList<>();

    QaSite(ReputationRules rules) { this.rules = rules; }

    void subscribe(SiteListener l) { listeners.add(l); }

    User register(String handle) {
        User u = new User(ids.incrementAndGet(), handle);
        users.put(u.id, u);
        return u;
    }

    /** A one-off bonus, for example for a trusted account. The demo uses it to set users up. */
    void grantBonus(long userId, int points) { user(userId).addReputation(points); }

    Question ask(long userId, String title, String body, String... tags) {
        if (tags.length == 0 || tags.length > 5) throw new IllegalArgumentException("use one to five tags");
        Set<String> clean = new LinkedHashSet<>();
        for (String t : tags) clean.add(t.trim().toLowerCase());
        Question q = new Question(ids.incrementAndGet(), user(userId), title, body, clean);
        posts.put(q.id, q);
        for (String t : clean)
            questionsByTag.computeIfAbsent(t, k -> ConcurrentHashMap.newKeySet()).add(q.id);
        q.followers.add(userId); // the asker follows their own question
        return q;
    }

    void follow(long userId, long questionId) { question(questionId).followers.add(user(userId).id); }

    Answer answer(long userId, long questionId, String body) {
        Question q = question(questionId);
        Answer a = new Answer(ids.incrementAndGet(), user(userId), body, q);
        posts.put(a.id, a);
        q.answers.add(a);
        for (long f : q.followers)
            if (f != userId) publish(new Event(EventType.NEW_ANSWER, f, "new answer on '" + q.title + "'"));
        return a;
    }

    Comment comment(long userId, long postId, String text) {
        User u = user(userId);
        Post p = post(postId);
        boolean own = p.author == u || p.question().author == u; // always allowed on your own thread
        if (!own && !u.can(Privilege.COMMENT_ANYWHERE))
            throw new IllegalStateException(u.handle + " needs " + Privilege.COMMENT_ANYWHERE.minReputation
                    + " reputation to comment here");
        Comment c = new Comment(ids.incrementAndGet(), postId, u, text);
        p.comments.add(c);
        if (p.author != u) publish(new Event(EventType.NEW_COMMENT, p.author.id, u.handle + ": " + text));
        return c;
    }

    /**
     * One vote per user per post. Voting the same way again undoes it; voting the other way switches it.
     * Returns the vote now on record, or null when there is none.
     */
    VoteType vote(long userId, long postId, VoteType wanted) {
        User voter = user(userId);
        Post post = post(postId);
        if (post.author == voter) throw new IllegalArgumentException("cannot vote on your own post");
        Privilege need = wanted == VoteType.UP ? Privilege.UPVOTE : Privilege.DOWNVOTE;
        if (!voter.can(need))
            throw new IllegalStateException(voter.handle + " needs " + need.minReputation + " reputation to "
                    + (wanted == VoteType.UP ? "upvote" : "downvote"));
        VoteType[] before = new VoteType[1];
        // compute() is atomic per key: two racing clicks by one user are applied one after the other.
        VoteType after = post.votes.compute(userId, (k, old) -> {
            before[0] = old;
            return old == wanted ? null : wanted; // returning null removes the entry (undo)
        });
        apply(post, voter, before[0], -1); // take back the old vote's effect
        apply(post, voter, after, +1);     // add the new vote's effect
        return after;
    }

    private void apply(Post p, User voter, VoteType v, int sign) {
        if (v == null) return;
        p.score.addAndGet(sign * v.value);
        p.author.addReputation(sign * rules.authorDelta(p.type(), v));
        voter.addReputation(sign * rules.voterDelta(p.type(), v));
    }

    /** Only the asker accepts, one answer at a time; switching moves the bonus to the new answer. */
    void accept(long userId, long answerId) {
        if (!(post(answerId) instanceof Answer a)) throw new IllegalArgumentException("not an answer");
        Question q = a.question;
        if (q.author.id != userId) throw new IllegalStateException("only the asker can accept an answer");
        // Atomic swap: two racing accepts each see exactly one 'before', so the bonus moves cleanly.
        Answer previous = q.accepted.getAndSet(a);
        if (previous == a) return;
        if (previous != null && previous.author != q.author)
            previous.author.addReputation(-rules.acceptedAnswerBonus());
        if (a.author != q.author) a.author.addReputation(rules.acceptedAnswerBonus()); // no bonus for self
        if (previous == null) q.author.addReputation(rules.acceptorBonus());
        publish(new Event(EventType.ANSWER_ACCEPTED, a.author.id,
                "your answer on '" + q.title + "' was accepted"));
    }

    /** Newest first would be another Comparator; here: highest score first, then oldest. */
    List<Question> searchByTag(String... tags) {
        List<Set<Long>> sets = new ArrayList<>();
        for (String t : tags) sets.add(questionsByTag.getOrDefault(t.toLowerCase(), Set.of()));
        sets.sort(Comparator.comparingInt(Set::size)); // intersect starting from the smallest set
        List<Question> out = new ArrayList<>();
        for (long id : sets.get(0)) {
            boolean all = true;
            for (Set<Long> s : sets) all &= s.contains(id);
            if (all) out.add((Question) posts.get(id));
        }
        out.sort(Comparator.comparingInt((Question q) -> -q.score.get()).thenComparingLong(q -> q.id));
        return out;
    }

    /** Accepted answer first, then by score, then oldest first. */
    List<Answer> answersOf(long questionId) {
        Question q = question(questionId);
        Answer acc = q.accepted.get();
        List<Answer> out = new ArrayList<>(q.answers);
        out.sort(Comparator.comparingInt((Answer a) -> a == acc ? 0 : 1)
                .thenComparingInt(a -> -a.score.get()).thenComparingLong(a -> a.id));
        return out;
    }

    private void publish(Event e) { for (SiteListener l : listeners) l.onEvent(e); }

    User user(long id) {
        User u = users.get(id);
        if (u == null) throw new IllegalArgumentException("no user " + id);
        return u;
    }

    private Post post(long id) {
        Post p = posts.get(id);
        if (p == null) throw new IllegalArgumentException("no post " + id);
        return p;
    }

    private Question question(long id) {
        if (post(id) instanceof Question q) return q;
        throw new IllegalArgumentException("post " + id + " is not a question");
    }

    // ---------- demo ----------
    /** An observer that keeps an inbox per user; email or push would be other listeners. */
    static final class Inbox implements SiteListener {
        final Map<Long, List<String>> messages = new ConcurrentHashMap<>();

        @Override
        public void onEvent(Event e) {
            messages.computeIfAbsent(e.recipientId(), k -> new CopyOnWriteArrayList<>())
                    .add(e.type() + ": " + e.message());
        }

        List<String> of(User u) { return messages.getOrDefault(u.id, List.of()); }
    }

    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    static void expectRejected(Runnable action) {
        try {
            action.run();
            throw new AssertionError("should have been rejected");
        } catch (IllegalArgumentException | IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }

    static String titles(List<Question> qs) {
        return qs.stream().map(q -> q.title + " [" + q.score.get() + "]").toList().toString();
    }

    public static void main(String[] args) throws Exception {
        QaSite site = new QaSite(new SimpleRules());
        Inbox inbox = new Inbox();
        site.subscribe(inbox);

        User asker = site.register("new_dev");
        User helper = site.register("java_helper");
        User other = site.register("quick_fixer");
        User reviewer = site.register("reviewer");
        site.grantBonus(reviewer.id, 59); // 60 in total: may upvote and downvote

        Question q1 = site.ask(asker.id, "Why does my HashMap lose entries?",
                "Two threads put keys and some vanish.", "java", "concurrency");
        Question q2 = site.ask(other.id, "How do I index a text column?", "Queries are slow.", "sql");
        Question q3 = site.ask(asker.id, "Is ConcurrentHashMap size exact?", "It looks off.", "Java");
        Answer a1 = site.answer(helper.id, q1.id, "Use ConcurrentHashMap; HashMap is not thread safe.");
        Answer a2 = site.answer(other.id, q1.id, "Just add Thread.sleep between the puts.");
        System.out.println("Inbox of " + asker.handle + ": " + inbox.of(asker).get(0) + " (x2)");
        check(inbox.of(asker).size() == 2, "asker hears about both answers");

        expectRejected(() -> site.vote(asker.id, a1.id, VoteType.UP));        // reputation 1, needs 10
        expectRejected(() -> site.vote(helper.id, a1.id, VoteType.UP));       // own post

        site.vote(reviewer.id, a1.id, VoteType.UP);    // helper +10
        site.vote(reviewer.id, q1.id, VoteType.UP);    // asker +5
        site.vote(reviewer.id, a2.id, VoteType.DOWN);  // quick_fixer -2, reviewer -1
        System.out.println("After votes: " + helper + ", " + asker + ", " + other + ", " + reviewer);
        VoteType now = site.vote(reviewer.id, a2.id, VoteType.UP); // change: undo -2/-1, then +10
        System.out.println("Changed vote on a2 to " + now + ": score " + a2.score.get() + ", " + other);
        now = site.vote(reviewer.id, a2.id, VoteType.UP);          // same again: undo
        System.out.println("Same vote again undoes it (now " + (now == null ? "none" : now) + "): score "
                + a2.score.get() + ", " + other
                + ", " + reviewer);
        check(a2.score.get() == 0 && other.raw.get() == 1 && reviewer.raw.get() == 60, "undo is exact");

        site.accept(asker.id, a1.id);
        System.out.println("Accepted a1: " + helper + ", " + asker + "; " + helper.handle + " got: "
                + inbox.of(helper).get(0));
        site.accept(asker.id, a2.id); // changes their mind: the bonus moves
        site.accept(asker.id, a1.id); // and back again
        check(helper.reputation() == 26 && other.reputation() == 1 && asker.reputation() == 8,
                "accept bonus moves");
        expectRejected(() -> site.accept(other.id, a2.id));

        site.comment(asker.id, a1.id, "Thanks, that fixed it.");   // own thread: allowed at 8 reputation
        List<String> helperInbox = inbox.of(helper);
        System.out.println("Latest for " + helper.handle + ": " + helperInbox.get(helperInbox.size() - 1));
        expectRejected(() -> site.comment(other.id, q3.id, "Try harder."));
        System.out.println("Answers of q1: "
                + site.answersOf(q1.id).stream().map(a -> a.author.handle).toList());

        System.out.println("Tag java: " + titles(site.searchByTag("java")));
        System.out.println("Tags java + concurrency: " + titles(site.searchByTag("java", "concurrency")));
        System.out.println("Tag sql: " + titles(site.searchByTag("sql")));
        check(site.searchByTag("java").size() == 2 && site.searchByTag("rust").isEmpty(), "tag search");

        // Concurrency: 300 voters race on one answer, then switch or undo; one user spams toggles.
        Question q4 = site.ask(other.id, "Why is my stream not parallel?", "It uses one core.", "java");
        Answer hot = site.answer(helper.id, q4.id, "Call parallel() and check the source splits well.");
        int startRep = helper.raw.get();
        List<User> voters = new ArrayList<>();
        for (int i = 0; i < 300; i++) {
            User v = site.register("voter" + i);
            site.grantBonus(v.id, 99);
            voters.add(v);
        }
        ExecutorService pool = Executors.newFixedThreadPool(8);
        List<Future<?>> jobs = new ArrayList<>();
        for (User v : voters) jobs.add(pool.submit(() -> site.vote(v.id, hot.id, VoteType.UP)));
        for (Future<?> f : jobs) f.get();
        check(hot.score.get() == 300, "300 upvotes");
        jobs.clear();
        for (int i = 0; i < voters.size(); i++) {
            User v = voters.get(i);
            boolean even = i % 2 == 0;
            jobs.add(pool.submit(() -> {
                site.vote(v.id, hot.id, VoteType.DOWN);              // switch up to down
                if (even) site.vote(v.id, hot.id, VoteType.DOWN);    // then undo it
            }));
        }
        User spammer = site.register("double_clicker");
        site.grantBonus(spammer.id, 99);
        for (int t = 0; t < 4; t++) // 4000 clicks of the same vote: each one toggles, so it ends with none
            jobs.add(pool.submit(() -> {
                for (int k = 0; k < 1000; k++) site.vote(spammer.id, hot.id, VoteType.UP);
            }));
        for (Future<?> f : jobs) f.get();
        pool.shutdown();
        int ledger = hot.votes.values().stream().mapToInt(v -> v.value).sum();
        System.out.println("Concurrent: score " + hot.score.get() + ", ledger sum " + ledger + ", on record "
                + hot.votes.size() + ", author change " + (helper.raw.get() - startRep));
        check(hot.score.get() == -150 && ledger == -150 && hot.votes.size() == 150, "concurrent votes");
        check(helper.raw.get() - startRep == -300, "reputation matches the ledger");
    }
}

Notes

Requirements

Fix the scope. A user asks a question with one to five tags. Others answer, and anyone can comment on a question or an answer. Users vote up or down, but only once per post, and they can change or take back that vote. Votes and accepted answers change reputation, and reputation unlocks privileges. The asker accepts one answer. Questions are searchable by tag, and followers are notified when something happens.

Ask the questions that change the code. Can you vote on your own post? No. What happens if you click the same vote twice? It undoes it. Can the asker change which answer is accepted? Yes, and the bonus moves with it. Can reputation go below one? We show a floor of one, but keep the exact sum underneath. Full text search, edit history, moderation queues and badges are out of scope for now.

Requirements
  • ask a question with 1 to 5 tags
  • answer a question
  • comment on any post
  • upvote or downvote a post
  • one vote per user per post
  • change it or undo it
  • reputation from votes, accepts
  • privileges unlock with rep
  • asker accepts one answer
  • search questions by tag
  • notify followers of activity
Clarify first
  • vote on your own post?
  • no
  • click the same vote twice?
  • it undoes the vote
  • can the asker change accept?
  • yes, the bonus moves
  • reputation below one?
  • shown as one, sum kept exact
  • out of scope: full text search,
  • edits history, moderation,
  • bounties, badges

Entities

Underline the nouns: user, question, answer, comment, tag, vote. The key modelling move is to notice that questions and answers behave the same way for voting and comments. So both extend an abstract Post that holds the author, the body, the score, the vote ledger and the comments. A question adds a title, tags, a list of answers and the accepted answer. An answer points back to its question. A comment is a small record, and it has no votes in this version.

Class diagram

Here is the shape. Post is abstract and owns everything voting needs: an atomic score and a vote ledger, which is a concurrent map from user id to up or down. Question and Answer extend it and add their own fields. The type method tells the reputation rules whether a vote was on a question or an answer. Because one map entry exists per voter, the rule of one vote per user per post is true by construction, not by a check you might forget.

Post
abstract class Post {
  final long id; final User author;
  final AtomicInteger score;
  final ConcurrentHashMap<Long, VoteType>
      votes;          // userId to vote
  final List<Comment> comments;
  abstract PostType type();
}
class Question extends Post {..tags..}
class Answer extends Post {..question..}

Privileges

Privileges are just data. An enum lists each power with its minimum reputation, and the user has one method, can, that compares. These numbers are an example we made up for this lesson: ten to upvote, twenty to comment on other people's posts, fifty to downvote. Commenting on your own question, or on answers to it, is always allowed. Adding a new privilege is one enum line plus one check where the action happens.

Example thresholds
enum Privilege {
  UPVOTE(10), COMMENT_ANYWHERE(20),
  DOWNVOTE(50), EDIT_ANY_POST(500);
}
boolean can(Privilege p) {
  return reputation() >= p.minReputation;
}

numbers are an example for this
lesson, not any real site

Strategy: reputation

Reputation rules change over time, so they live behind a ReputationRules interface: the Strategy pattern. Our example rules are simple round numbers. An upvote gives the author five on a question and ten on an answer. A downvote costs the author two, and downvoting an answer also costs the voter one, so downvotes are not free. An accepted answer earns fifteen, and the asker gets two for accepting. A different community just plugs in a different rules class.

SimpleRules (an example)
  • upvote on a question: author +5
  • upvote on an answer: author +10
  • any downvote: author -2
  • downvote an answer: voter -1
  • answer accepted: author +15
  • asker who accepts: +2
  • self-accept earns nothing
  • shown reputation floor: 1

Flow: vote

Walk the vote flow. Reject a vote on your own post, and check the privilege for up or down. Then one atomic compute on the ledger decides the new state: if the old vote equals the wanted one, remove it, which is an undo; otherwise store the wanted vote. We remember what was there before. Finally take back the effect of the old vote and add the effect of the new one, to the score and to both reputations.

vote(user, post, wanted)
reject own post, check privilege
VoteType[] before = new VoteType[1];
after = votes.compute(userId, (k, old) -> {
  before[0] = old;
  return old == wanted ? null : wanted;
});
apply(post, voter, before[0], -1);
apply(post, voter, after, +1);
return after;  // null: no vote now

Change and undo

This one rule handles every case, which is why it is worth showing. A first vote only adds. An undo only removes. A switch from down to up removes the down, giving back two points to the author and one to the voter, and then adds the up, ten more. Clicking up again removes it. The demo checks that after this dance the score and both reputations are back exactly where they started. No special case code for switching at all.

One rule covers every case
  • none to UP: add UP
  • UP to none: remove UP (undo)
  • DOWN to UP: remove DOWN, add UP
  • reviewer switches on a2:
  • remove DOWN: author +2,
  • voter +1
  • add UP: author +10
  • click UP again: author -10
  • net result: exactly zero

Flow: accept

Accepting an answer. Only the asker may do it. The question holds the accepted answer in an atomic reference, and get-and-set swaps it in one step and hands back the previous one. If it was the same answer, nothing to do. If another answer was accepted before, take its fifteen points away, then give fifteen to the new one, unless the asker answered their own question. The asker's two point bonus is paid only the first time.

accept(userId, answerId)
if (q.author.id != userId) throw
prev = q.accepted.getAndSet(a);
if (prev == a) return;
if (prev != null) prev author -15
a author +15   // unless self-answer
if (prev == null) asker +2
notify a.author: accepted

Search by tag

Search by tag uses an inverted index: a concurrent map from each tag to the set of question ids that carry it. Tags are lower-cased on the way in, so Java and java are the same tag. For several tags, sort the sets by size, walk the smallest one, and keep ids found in every other set. Results are sorted by score, highest first, then oldest first. Full text search over titles and bodies is a separate search engine, and we say so.

searchByTag(tags...)
Map<String, Set<Long>> questionsByTag
  java -> {q1, q3}
  concurrency -> {q1}

sort the sets by size
walk the smallest, keep ids in all
sort: score high to low, then oldest

tags lower-cased on the way in

Observer: notifications

Notifications use the Observer pattern. Each question keeps a set of followers, and the asker follows automatically. When an answer arrives, the site publishes a new answer event for every follower except the person who answered. Comments notify the post's author, and accepts notify the answerer. The site never knows whether a listener writes to an in-app inbox, sends an email or a push message. Adding a channel is one more listener.

Observer
enum EventType { NEW_ANSWER,
  NEW_COMMENT, ANSWER_ACCEPTED }
record Event(type, recipientId, msg)
interface SiteListener {
  void onEvent(Event e);
}
listeners: CopyOnWriteArrayList

Inbox, EmailSender, PushSender:
  each is just one more listener

Concurrency

Now concurrency. A user double clicks, and two requests arrive together. With a naive check then put, both see no vote and the score goes up by two from one person. Instead, the ledger's compute method runs atomically for each key, so the second click sees the first one's result and undoes it. Score and reputation change with atomic adds, and since additions can happen in any order, the totals always match the ledger.

Give every shared field a safe home. The ledger is a concurrent map updated with compute. Score and reputation are atomic integers. The accepted answer is an atomic reference, swapped with get and set. The tag index uses concurrent key sets. Answers, comments and listeners are copy-on-write lists, because they are read far more often than written. Ids come from an atomic counter. There is no global lock, so one busy question never slows down another.

The demo proves it under load. Three hundred voters upvote one answer from eight threads, and the score is exactly three hundred. Then every voter switches to a downvote while half of them also undo it, and at the same time one user clicks up four thousand times from four threads. Each click toggles, so that user ends with no vote. The score equals the ledger sum, minus one hundred and fifty, and the author's reputation change is exactly what the rules predict.

The lost update
  • naive: if (!votes.contains(u))
  • votes.put(u, UP); score++
  • two clicks both see no vote:
  • score +2 from one user
  • fix: votes.compute(u, ...)
  • runs one at a time per key
  • score and reputation: atomic
  • adds, and adds commute
Thread safety checklist
  • vote ledger: ConcurrentHashMap
  • compute() per post and user
  • score, reputation: AtomicInteger
  • accepted answer: AtomicReference
  • getAndSet moves the bonus
  • tag index: concurrent key sets
  • answers, comments, listeners:
  • CopyOnWriteArrayList
  • ids: AtomicLong
  • no global lock anywhere
The race in main()
  • 300 voters upvote one answer
  • on 8 threads: score 300
  • then all switch to down,
  • and even ones undo it
  • one user clicks UP 4000 times
  • from 4 threads: ends with none
  • score -150 = ledger sum -150
  • author change -300, exactly

Extensibility

Interviewers will add features. Votes on comments? Pull the voting part into a Votable interface that both posts and comments implement. Bounties? A bounty object on the question, paid out on accept through the rules. Badges? Another listener that counts events per user, so the core never changes. Edit history? A list of revisions, gated by the edit privilege. Closing a question as a duplicate? A small state enum on the question.

Extension points
  • votes on comments: Comment
  • becomes a Post-like Votable
  • bounties: a Bounty on a question
  • paid on accept, a rules event
  • badges: one more listener
  • counting events per user
  • edit history: Revision list,
  • needs EDIT_ANY_POST
  • close / duplicate: a state enum
  • on Question (State pattern)

Testing

The full code is below the player. The demo registers four users, asks three questions and posts two answers. It shows a new user blocked from upvoting, a self vote rejected, a vote that is switched and then undone with exact numbers, an accept that moves back and forth, a comment blocked by low reputation, tag search with one and two tags, and the concurrent vote race. Each step checks its numbers, so a mistake fails loudly.

Run it
Rejected: new_dev needs 10 reputation
  to upvote
Rejected: cannot vote on your own post
Same vote again undoes it: score 0
Accepted a1: java_helper(26), new_dev(8)
Rejected: quick_fixer needs 20
  reputation to comment here
Tag java: [HashMap question [1],
          size question [0]]
Concurrent: score -150, ledger -150

Follow-ups

Expect follow-ups. At scale, the ledger moves to a database table with a unique key on post and user, so the database also enforces one vote. A very hot post can keep its counter in several shards that are summed when read. If the rules change, recompute reputation by replaying the stored vote and accept events. Fraud, like one account voting for a friend again and again, is detected later and those votes are reversed with the same undo path.

Follow-ups to expect
  • millions of votes per hour?
  • ledger in a DB, unique
  • key on post and user
  • hot question: shard counters
  • recompute reputation?
  • replay the event log
  • serial voting fraud?
  • detect and reverse votes
  • sort by hot: score with
  • time decay, precomputed

Say it like this

The short version to say out loud. Question and Answer extend Post, which owns the score, the votes and the comments. Votes live in a map from user to vote, changed with one atomic compute, then we subtract the old effect and add the new one, which covers new votes, switches and undos. Points come from a rules strategy, powers from a privilege enum, and notifications go to observers.

In the interview
  • "Question and Answer extend Post,
  • which owns score, votes and
  • comments. Votes live in a map of
  • user to vote, changed with an
  • atomic compute: subtract the old
  • effect, add the new. Points come
  • from a rules Strategy, powers
  • from a Privilege enum, and
  • notifications are observers."

Interview questions

How do you enforce one vote per user per post?

Store votes in a map keyed by user id on each post, so there can only ever be one entry per voter. In a database the same idea is a votes table with a unique key on post id and user id. Changing the vote updates that one entry instead of adding a row.

How do you handle changing or undoing a vote without special cases?

Treat every vote change as two steps: remove the effect of the old vote, if any, then apply the effect of the new vote, if any. A first vote, a switch from down to up and an undo all fall out of that one rule, and the numbers return exactly to where they were.

What goes wrong if two vote requests from the same user arrive together?

With check-then-put, both requests see no vote and both add one, so one person counts twice. Using ConcurrentHashMap.compute makes the read, decision and write atomic per key, so the second request sees the first and behaves correctly.

Why are Question and Answer subclasses of Post?

They share author, body, score, votes and comments, and the voting code should not care which one it is handling. The abstract parent holds that shared state once, and each subclass adds only its own fields, like tags on a question or the parent question on an answer.

Why put reputation points behind a Strategy?

Point values are a business policy that changes, and different communities may want different numbers. With a ReputationRules interface, the voting and accepting code stays the same and you swap the rules class, which follows the open-closed principle.

How do you implement privileges based on reputation?

An enum of privileges, each with a minimum reputation, and a can method on the user that compares. Each action checks the privilege it needs before doing any work, and adding a privilege is one enum constant plus one check.

How does accepting a different answer move the bonus safely?

Keep the accepted answer in an AtomicReference and use getAndSet. It returns the previous answer in the same atomic step, so you take the bonus away from that author and give it to the new one, even if two accepts race.

How would you implement search by tag efficiently?

Keep an inverted index from tag to the set of question ids. For a multi-tag query, intersect starting from the smallest set, then sort by score or recency. Full text search over titles and bodies belongs in a separate search engine fed by events.

How do notifications work, and why the Observer pattern?

The site publishes events such as a new answer, a new comment or an accepted answer to registered listeners. Followers of a question receive answer events. The core never knows about inboxes, email or push, so a new channel is just a new listener.