On this page

Design Stack Overflow (LLD)

A Q&A site looks like CRUD: users post questions, others post answers, everyone votes. The interview gets interesting in the second layer. Votes move reputation, and reputation unlocks privileges such as closing questions. A vote can be changed or withdrawn, and the reputation it caused must come back exactly. The asker can accept one answer, then change their mind. A popular answer gets hundreds of votes in a minute, and none can be lost.

So this problem tests whether you can keep the core model (posts and votes) separate from the rules that react to it (reputation, badges, notifications), and whether you can make a counter correct under concurrency without one global lock. This page follows the LLD interview framework and leans on Observer, State and thread-safe class design.

1. Requirements

Clarifying questions and the answers we'll assume:

QuestionAssumption
Can users change their vote?Yes. Up, down or none, at any time. Reputation follows the current vote.
Can you vote on your own post?No.
Do comments carry votes or reputation?No. Comments are plain text attached to a post.
Who can close a question?Users with 3,000+ reputation. Closing as a duplicate must point at a canonical question.
Can the asker change the accepted answer?Yes, including un-accepting.
Search?By tags (all must match), sorted by votes or newest. Full-text search is a separate service.
Bounties?Treat as an extension.

Functional requirements

  1. Register users. Ask questions with a title, body and 1 to 5 tags. Post answers and comments.
  2. Vote up or down on questions and answers. One vote per user per post, changeable and retractable.
  3. Maintain reputation from votes and accepted answers, reversing exactly when the cause is undone.
  4. The asker accepts at most one answer, and may switch or un-accept.
  5. Close a question (with a reason), close it as a duplicate of another, or reopen it. Closed questions take no new answers.
  6. Find questions by tag.

Reputation rules. These follow Stack Overflow's published values at the time of writing (help centre: reputation). Treat them as configuration, because the site has changed them before. For example, question upvotes went from +5 to +10 in 2019.

EventEffect
Your question or answer is upvoted+10
Your question or answer is downvoted−2
You downvote an answer−1 to you (downvoting questions is free)
Your answer is accepted+15 to you, +2 to the asker (nothing for self-accepts)
A vote or acceptance is undonethe exact opposite of what it caused

Non-functional requirements

  • No lost votes. Concurrent votes on one post all count, and score always equals the sum of current votes.
  • Exact reversal. Any sequence of vote changes leaves reputation as if only the final vote had been cast.
  • Open for new reactions. Badges, notifications or anti-fraud checks can react to votes without editing the voting code.

2. Core entities

EntityResponsibility
UserIdentity and a reputation counter that's safe to adjust from many threads.
PostShared base of questions and answers: author, body, comments, a vote map and a score.
QuestionTitle, tags, status (OPEN, CLOSED, DUPLICATE), answers, the accepted answer.
AnswerBelongs to exactly one question.
CommentA (author, text) pair on a post. Small enough not to need a class here.
VoteChanged, AcceptChangedImmutable events that say what changed, from what, to what.
EventBusDelivers events to subscribers by type.
ReputationServiceThe observer that turns events into reputation deltas.
QAServiceThe facade: asking, answering, voting, accepting, closing, searching. Owns the tag index.

Two modelling decisions do most of the work.

A vote is stored as a value, not as a history. Each post keeps voter id → +1 or −1. The operation is setVote(user, value), which says "my vote is now X", not toggleUpvote. Setting is idempotent: a double-click sends "+1" twice, and the second is a no-op. Toggling turns a double-click into a retraction.

Reputation is derived from transitions. The voting code only reports old → new. The reputation service knows the rules and applies effects(new) − effects(old). A flip from up to down is "undo +10, apply −2, voter pays 1". Retraction is "undo whatever the old vote did". No special cases.

3. Class diagram

classDiagram
    class User {
        +String id
        +reputation() int
        +adjust(int)
    }
    class Post {
        <<abstract>>
        +long id
        +User author
        +String body
        +List comments
        -Map votes
        -int score
        +setVote(User, int) int
    }
    class Question {
        +String title
        +Set tags
        +Status status
        +Question duplicateOf
        +Answer accepted
    }
    class Answer {
        +Question question
    }
    class Status {
        <<enumeration>>
        OPEN
        CLOSED
        DUPLICATE
    }
    class EventBus {
        +subscribe(Class, Consumer)
        +publish(Object)
    }
    class VoteChanged {
        +Post post
        +User voter
        +int oldValue
        +int newValue
    }
    class AcceptChanged {
        +Question question
        +Answer oldAnswer
        +Answer newAnswer
    }
    class ReputationService {
        +voteEffects(Post, User, int) List
        +acceptEffects(Question, Answer) List
    }
    class QAService {
        +ask(User, String, String, Set) Question
        +answer(User, Question, String) Answer
        +vote(User, Post, int)
        +accept(User, Answer, Question)
        +close(User, Question, String, Question)
        +reopen(User, Question)
        +search(Set, boolean, int) List
    }
    Post <|-- Question
    Post <|-- Answer
    Post --> User : author
    Question "1" o-- "many" Answer
    Question --> Status
    QAService --> EventBus : publishes
    ReputationService --> EventBus : subscribes
    EventBus ..> VoteChanged
    EventBus ..> AcceptChanged
    ReputationService ..> User : adjusts

4. Key flows

Changing a vote

sequenceDiagram
    participant V as Voter
    participant S as QAService
    participant P as Post
    participant B as EventBus
    participant R as ReputationService
    participant A as Author
    V->>S: vote(post, -1)
    S->>P: setVote(voter, -1)
    P->>P: lock, old = +1, store -1, score += -2, unlock
    P-->>S: old = +1
    S->>B: publish VoteChanged(+1 to -1)
    B->>R: on vote
    R->>A: adjust(-10) undoes the old upvote
    R->>A: adjust(-2) for the new downvote
    R->>V: adjust(-1) cost of downvoting an answer

The post updates its vote map and score under its own lock, then returns the old value. The event is published after the lock is released, so a slow subscriber never blocks voting.

Accepting, then switching

sequenceDiagram
    participant Q as Asker
    participant S as QAService
    participant B as EventBus
    participant R as ReputationService
    Q->>S: accept(answer A1)
    S->>B: AcceptChanged(none to A1)
    B->>R: A1 author +15, asker +2
    Q->>S: accept(answer A2)
    S->>B: AcceptChanged(A1 to A2)
    B->>R: A2 author +15, asker +2
    B->>R: undo A1 author -15, asker -2

Question lifecycle

stateDiagram-v2
    [*] --> OPEN : ask
    OPEN --> CLOSED : close with reason
    OPEN --> DUPLICATE : close as duplicate of a canonical question
    CLOSED --> OPEN : reopen
    DUPLICATE --> OPEN : reopen

Votes, comments and acceptance work in every state. Only answering requires OPEN. A duplicate must point at a question that isn't itself a duplicate, so readers are never sent down a chain.

One user's vote on one post

stateDiagram-v2
    [*] --> NONE
    NONE --> UP : set +1
    NONE --> DOWN : set -1
    UP --> DOWN : set -1
    DOWN --> UP : set +1
    UP --> NONE : set 0
    DOWN --> NONE : set 0

Setting the value you already have is a self-loop with no event and no reputation change.

5. Patterns and why

PatternWhereWhy it fitsRejected alternative
Observer (event bus)VoteChanged, AcceptChanged → ReputationServiceVoting shouldn't know reputation rules. New reactions (badges, notifications, fraud checks) subscribe without touching voting.vote() calls author.rep += 10 directly. Every rule change and every new reaction edits the vote path.
State (enum with guarded transitions)Question.statusThree states and four transitions, and the only behaviour difference is "can it be answered?".One class per state. Too much ceremony for one rule. Switch to it if states start to differ in many operations.
FacadeQAServiceOne entry point that enforces cross-object rules (only the asker accepts, privileges for closing).Clients mutating Question directly, with rules scattered through callers.
Value object eventsimmutable event recordsThey carry old and new, which is what makes exact reversal possible.An event that only says "voted". The listener would have to re-read state that may already have changed again.

Why the diff trick beats event-specific handlers. You could write handlers for "upvote added", "upvote removed", "flipped down to up" and so on: six transitions for votes alone. Each one is a chance to get a sign wrong. With effects(new) − effects(old), there's one rule table and one subtraction. It also makes the effects commutative. Two events for the same voter can be applied in either order and the total is the same, which matters for concurrency below.

Why not compute reputation on read? You could, by summing over all votes and accepts for a user's posts every time. That's always correct, but it's expensive for a user with 50,000 posts, and reputation is shown next to every username on every page. Keep the incremental counter for reads, and keep the ability to recompute from votes as an audit job. You'll need it: when Stack Overflow raised question upvotes to +10 in 2019, the change was applied retroactively, which means recomputing everyone's reputation from vote history.

6. The code

The demo follows one question through its life. Bo's answer is upvoted, the same upvote is sent again (no effect), flipped to a downvote and retracted, and the asserts check reputation at every step. Then the asker accepts Bo's answer and switches to Cy's. A second question is closed as a duplicate and rejects new answers. Finally, tag search returns questions sorted by votes.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.Consumer;

final class QAException extends RuntimeException { QAException(String m) { super(m); } }

final class User {
    final String id;
    private final AtomicInteger rep;
    User(String id, int reputation) { this.id = id; this.rep = new AtomicInteger(reputation); }
    int reputation() { return rep.get(); }
    void adjust(int delta) { rep.addAndGet(delta); }
}

abstract class Post {
    final long id;
    final User author;
    final String body;
    final List<String> comments = new CopyOnWriteArrayList<>();
    private final Map<String, Integer> votes = new HashMap<>();   // voter id -> +1 or -1, guarded by this
    private int score;
    Post(long id, User author, String body) { this.id = id; this.author = author; this.body = body; }

    synchronized int score() { return score; }

    /** Set this voter's vote to value (+1, -1 or 0). Returns the previous value. */
    synchronized int setVote(User voter, int value) {
        if (value < -1 || value > 1) throw new QAException("vote must be -1, 0 or 1");
        if (voter == author) throw new QAException("cannot vote on your own post");
        int old = votes.getOrDefault(voter.id, 0);
        if (value == 0) votes.remove(voter.id); else votes.put(voter.id, value);
        score += value - old;
        return old;
    }
}

enum Status { OPEN, CLOSED, DUPLICATE }

final class Question extends Post {
    final String title;
    final Set<String> tags;
    final List<Answer> answers = new ArrayList<>();               // guarded by this
    Status status = Status.OPEN;                                   // guarded by this
    Question duplicateOf;
    String closeReason = "";
    Answer accepted;
    Question(long id, User author, String title, String body, Set<String> tags) {
        super(id, author, body); this.title = title; this.tags = tags;
    }
    synchronized Status status() { return status; }
}

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

// ---------- events and the bus (Observer) ----------
record VoteChanged(Post post, User voter, int oldValue, int newValue) {}
record AcceptChanged(Question question, Answer oldAnswer, Answer newAnswer) {}

final class EventBus {
    private final Map<Class<?>, List<Consumer<Object>>> subs = new ConcurrentHashMap<>();
    @SuppressWarnings("unchecked")
    <E> void subscribe(Class<E> type, Consumer<E> handler) {
        subs.computeIfAbsent(type, k -> new CopyOnWriteArrayList<>()).add(e -> handler.accept((E) e));
    }
    void publish(Object event) { subs.getOrDefault(event.getClass(), List.of()).forEach(h -> h.accept(event)); }
}

record Delta(User user, int amount) {}

/** A change from old to new applies effects(new) minus effects(old), so any reversal is exact. */
final class ReputationService {
    static final int UPVOTE_GAIN = 10, DOWNVOTE_LOSS = 2, ANSWER_DOWNVOTE_COST = 1, ACCEPTED_GAIN = 15, ACCEPTER_GAIN = 2;

    ReputationService(EventBus bus) {
        bus.subscribe(VoteChanged.class, e -> apply(voteEffects(e.post(), e.voter(), e.newValue()), voteEffects(e.post(), e.voter(), e.oldValue())));
        bus.subscribe(AcceptChanged.class, e -> apply(acceptEffects(e.question(), e.newAnswer()), acceptEffects(e.question(), e.oldAnswer())));
    }

    static List<Delta> voteEffects(Post post, User voter, int value) {
        if (value == 1) return List.of(new Delta(post.author, UPVOTE_GAIN));
        if (value == -1) return post instanceof Answer
                ? List.of(new Delta(post.author, -DOWNVOTE_LOSS), new Delta(voter, -ANSWER_DOWNVOTE_COST))
                : List.of(new Delta(post.author, -DOWNVOTE_LOSS));
        return List.of();
    }

    static List<Delta> acceptEffects(Question q, Answer a) {
        if (a == null || a.author == q.author) return List.of();    // self-accept earns nothing
        return List.of(new Delta(a.author, ACCEPTED_GAIN), new Delta(q.author, ACCEPTER_GAIN));
    }

    private static void apply(List<Delta> gain, List<Delta> undo) {
        gain.forEach(d -> d.user().adjust(d.amount()));
        undo.forEach(d -> d.user().adjust(-d.amount()));
    }
}

// ---------- the facade ----------
final class QAService {
    static final int CLOSE_PRIVILEGE = 3000;
    final EventBus bus;
    final Map<String, User> users = new ConcurrentHashMap<>();
    private final Map<String, Set<Question>> byTag = new ConcurrentHashMap<>();
    private final AtomicLong ids = new AtomicLong();

    QAService(EventBus bus) { this.bus = bus; }

    User register(String id, int reputation) { return users.computeIfAbsent(id, k -> new User(id, reputation)); }

    Question ask(User author, String title, String body, Set<String> rawTags) {
        Set<String> tags = new TreeSet<>();
        rawTags.forEach(t -> tags.add(t.strip().toLowerCase()));
        if (tags.isEmpty() || tags.size() > 5) throw new QAException("a question needs 1 to 5 tags");
        Question q = new Question(ids.incrementAndGet(), author, title, body, Set.copyOf(tags));
        tags.forEach(t -> byTag.computeIfAbsent(t, k -> ConcurrentHashMap.newKeySet()).add(q));
        return q;
    }

    Answer answer(User author, Question q, String body) {
        synchronized (q) {
            if (q.status != Status.OPEN) throw new QAException("question is " + q.status);
            Answer a = new Answer(ids.incrementAndGet(), author, body, q);
            q.answers.add(a);
            return a;
        }
    }

    void comment(User author, Post post, String text) { post.comments.add(author.id + ": " + text); }

    void vote(User voter, Post post, int value) {
        int old = post.setVote(voter, value);
        if (old != value) bus.publish(new VoteChanged(post, voter, old, value));   // outside every lock
    }

    /** Accept an answer, switch to another, or pass null to un-accept. */
    void accept(User by, Answer answer, Question q) {
        if (by != q.author) throw new QAException("only the asker can accept");
        if (answer != null && answer.question != q) throw new QAException("answer belongs to another question");
        Answer old;
        synchronized (q) { old = q.accepted; q.accepted = answer; }
        if (old != answer) bus.publish(new AcceptChanged(q, old, answer));
    }

    void close(User by, Question q, String reason, Question duplicateOf) {
        if (by.reputation() < CLOSE_PRIVILEGE) throw new QAException("closing needs 3000 reputation");
        if (duplicateOf != null && (duplicateOf == q || duplicateOf.status() == Status.DUPLICATE))
            throw new QAException("point duplicates at a canonical question");
        synchronized (q) {
            if (q.status != Status.OPEN) throw new QAException("question is already " + q.status);
            q.status = duplicateOf != null ? Status.DUPLICATE : Status.CLOSED;
            q.closeReason = reason;
            q.duplicateOf = duplicateOf;
        }
    }

    void reopen(User by, Question q) {
        if (by.reputation() < CLOSE_PRIVILEGE) throw new QAException("reopening needs 3000 reputation");
        synchronized (q) {
            if (q.status == Status.OPEN) throw new QAException("question is already open");
            q.status = Status.OPEN; q.closeReason = ""; q.duplicateOf = null;
        }
    }

    /** Questions carrying every tag, intersecting from the rarest tag. */
    List<Question> search(Set<String> tags, boolean byVotes, int limit) {
        List<Set<Question>> sets = tags.stream().map(t -> byTag.getOrDefault(t.toLowerCase(), Set.of()))
                .sorted(Comparator.comparingInt(Set::size)).toList();
        if (sets.isEmpty()) return List.of();
        Set<Question> found = new HashSet<>(sets.get(0));
        sets.subList(1, sets.size()).forEach(found::retainAll);
        Comparator<Question> newest = Comparator.comparingLong((Question q) -> q.id).reversed();
        Comparator<Question> order = byVotes ? Comparator.comparingInt((Question q) -> -q.score()).thenComparing(newest) : newest;
        return found.stream().sorted(order).limit(limit).toList();
    }
}

public class Main {
    static void expectFailure(Runnable r) {
        try { r.run(); } catch (QAException e) { return; }
        throw new AssertionError("expected QAException");
    }

    public static void main(String[] args) {
        QAService so = new QAService(new EventBus());
        new ReputationService(so.bus);
        User ann = so.register("ann", 1), bo = so.register("bo", 1), cy = so.register("cy", 1), mod = so.register("mod", 5001);

        Question q = so.ask(ann, "Why is my HashMap slow?", "...", Set.of("java", "Performance"));
        Answer a1 = so.answer(bo, q, "Bad hashCode."), a2 = so.answer(cy, q, "Resize churn.");

        so.vote(cy, a1, 1);
        so.vote(cy, a1, 1);                                        // same vote again: no change, no event
        assert a1.score() == 1 && bo.reputation() == 11;
        so.vote(cy, a1, -1);                                       // flip: undo +10, apply -2, voter pays 1
        assert a1.score() == -1 && bo.reputation() == -1 && cy.reputation() == 0;
        so.vote(cy, a1, 0);                                        // retract: everything back
        assert a1.score() == 0 && bo.reputation() == 1 && cy.reputation() == 1;

        so.accept(ann, a1, q);
        assert bo.reputation() == 16 && ann.reputation() == 3;
        so.accept(ann, a2, q);                                     // switch: bo loses 15, cy gains 15
        assert bo.reputation() == 1 && cy.reputation() == 16 && ann.reputation() == 3;

        Question q2 = so.ask(bo, "HashMap slow lookups", "...", Set.of("java"));
        so.close(mod, q2, "duplicate", q);
        expectFailure(() -> so.answer(cy, q2, "late"));
        so.vote(bo, q, 1);
        assert so.search(Set.of("java"), true, 10).equals(List.of(q, q2));
        assert so.search(Set.of("java", "performance"), true, 10).equals(List.of(q));
        assert so.search(Set.of("rust"), true, 10).isEmpty();
        System.out.println("Main.java: all assertions passed");
    }
}
from __future__ import annotations

import itertools
import threading
from collections import defaultdict
from dataclasses import dataclass
from enum import Enum
from typing import Callable

UPVOTE_GAIN, DOWNVOTE_LOSS, ANSWER_DOWNVOTE_COST = 10, 2, 1
ACCEPTED_GAIN, ACCEPTER_GAIN, CLOSE_PRIVILEGE = 15, 2, 3000


class QAError(Exception):
    pass


class User:
    def __init__(self, user_id: str, reputation: int = 1) -> None:
        self.id = user_id
        self._rep = reputation
        self._lock = threading.Lock()

    @property
    def reputation(self) -> int:
        return self._rep

    def adjust(self, delta: int) -> None:
        with self._lock:                    # += is not atomic across threads
            self._rep += delta


class Post:
    def __init__(self, post_id: int, author: User, body: str) -> None:
        self.id, self.author, self.body = post_id, author, body
        self.comments: list[tuple[str, str]] = []          # (author id, text)
        self.lock = threading.Lock()
        self._votes: dict[str, int] = {}                   # voter id -> +1 or -1
        self.score = 0

    def set_vote(self, voter: User, value: int) -> int:
        """Set this voter's vote to value (+1, -1 or 0). Returns the previous value."""
        if value not in (-1, 0, 1):
            raise QAError("vote must be -1, 0 or 1")
        if voter is self.author:
            raise QAError("cannot vote on your own post")
        with self.lock:                                    # read old, write new, fix score: one step
            old = self._votes.get(voter.id, 0)
            if value:
                self._votes[voter.id] = value
            else:
                self._votes.pop(voter.id, None)
            self.score += value - old
            return old


class Status(Enum):
    OPEN = "open"
    CLOSED = "closed"
    DUPLICATE = "duplicate"


class Question(Post):
    def __init__(self, post_id: int, author: User, title: str, body: str, tags: frozenset[str]) -> None:
        super().__init__(post_id, author, body)
        self.title, self.tags = title, tags
        self.status, self.close_reason, self.duplicate_of = Status.OPEN, "", None
        self.answers: list[Answer] = []
        self.accepted: Answer | None = None


class Answer(Post):
    def __init__(self, post_id: int, author: User, body: str, question: Question) -> None:
        super().__init__(post_id, author, body)
        self.question = question


# ---------- events and the bus (Observer) ----------
@dataclass(frozen=True)
class VoteChanged:
    post: Post
    voter: User
    old: int
    new: int


@dataclass(frozen=True)
class AcceptChanged:
    question: Question
    old: Answer | None
    new: Answer | None


class EventBus:
    def __init__(self) -> None:
        self._subs: dict[type, list[Callable]] = defaultdict(list)

    def subscribe(self, event_type: type, handler: Callable) -> None:
        self._subs[event_type].append(handler)

    def publish(self, event: object) -> None:
        for handler in self._subs[type(event)]:
            handler(event)


class ReputationService:
    """Turns events into reputation. A change from old to new applies effects(new) - effects(old),
    so retracting or flipping a vote reverses exactly what the earlier vote did."""

    def __init__(self, bus: EventBus) -> None:
        bus.subscribe(VoteChanged, self.on_vote)
        bus.subscribe(AcceptChanged, self.on_accept)

    @staticmethod
    def vote_effects(post: Post, voter: User, value: int) -> list[tuple[User, int]]:
        if value == 1:
            return [(post.author, UPVOTE_GAIN)]
        if value == -1:
            cost = [(voter, -ANSWER_DOWNVOTE_COST)] if isinstance(post, Answer) else []
            return [(post.author, -DOWNVOTE_LOSS)] + cost
        return []

    @staticmethod
    def accept_effects(q: Question, a: Answer | None) -> list[tuple[User, int]]:
        if a is None or a.author is q.author:              # self-accept earns nothing
            return []
        return [(a.author, ACCEPTED_GAIN), (q.author, ACCEPTER_GAIN)]

    def on_vote(self, e: VoteChanged) -> None:
        self._apply(self.vote_effects(e.post, e.voter, e.new), self.vote_effects(e.post, e.voter, e.old))

    def on_accept(self, e: AcceptChanged) -> None:
        self._apply(self.accept_effects(e.question, e.new), self.accept_effects(e.question, e.old))

    @staticmethod
    def _apply(gain: list[tuple[User, int]], undo: list[tuple[User, int]]) -> None:
        for user, delta in gain:
            user.adjust(delta)
        for user, delta in undo:
            user.adjust(-delta)


# ---------- the facade ----------
class QAService:
    def __init__(self, bus: EventBus | None = None) -> None:
        self.bus = bus or EventBus()
        self.users: dict[str, User] = {}
        self.posts: dict[int, Post] = {}
        self._by_tag: dict[str, set[int]] = defaultdict(set)
        self._ids = itertools.count(1)
        self._lock = threading.Lock()                      # guards the maps above, never held while publishing

    def register(self, user_id: str, reputation: int = 1) -> User:
        with self._lock:
            return self.users.setdefault(user_id, User(user_id, reputation))

    def ask(self, author: User, title: str, body: str, tags: set[str]) -> Question:
        tags = frozenset(t.strip().lower() for t in tags)
        if not 1 <= len(tags) <= 5:
            raise QAError("a question needs 1 to 5 tags")
        with self._lock:
            q = Question(next(self._ids), author, title, body, tags)
            self.posts[q.id] = q
            for t in tags:
                self._by_tag[t].add(q.id)
        return q

    def answer(self, author: User, q: Question, body: str) -> Answer:
        with self._lock:
            a = Answer(next(self._ids), author, body, q)
        with q.lock:
            if q.status is not Status.OPEN:
                raise QAError(f"question is {q.status.value}")
            q.answers.append(a)
        with self._lock:
            self.posts[a.id] = a
        return a

    def comment(self, author: User, post: Post, text: str) -> None:
        with post.lock:
            post.comments.append((author.id, text))

    def vote(self, voter: User, post: Post, value: int) -> None:
        old = post.set_vote(voter, value)
        if old != value:
            self.bus.publish(VoteChanged(post, voter, old, value))   # outside every lock

    def accept(self, by: User, answer: Answer | None, q: Question) -> None:
        """Accept an answer, switch to another, or pass None to un-accept."""
        if by is not q.author:
            raise QAError("only the asker can accept")
        if answer is not None and answer.question is not q:
            raise QAError("answer belongs to another question")
        with q.lock:
            old, q.accepted = q.accepted, answer
        if old is not answer:
            self.bus.publish(AcceptChanged(q, old, answer))

    def close(self, by: User, q: Question, reason: str, duplicate_of: Question | None = None) -> None:
        if by.reputation < CLOSE_PRIVILEGE:
            raise QAError("closing needs 3000 reputation")
        if duplicate_of is not None and (duplicate_of is q or duplicate_of.status is Status.DUPLICATE):
            raise QAError("point duplicates at a canonical question")
        with q.lock:
            if q.status is not Status.OPEN:
                raise QAError(f"question is already {q.status.value}")
            q.status = Status.DUPLICATE if duplicate_of else Status.CLOSED
            q.close_reason, q.duplicate_of = reason, duplicate_of

    def reopen(self, by: User, q: Question) -> None:
        if by.reputation < CLOSE_PRIVILEGE:
            raise QAError("reopening needs 3000 reputation")
        with q.lock:
            if q.status is Status.OPEN:
                raise QAError("question is already open")
            q.status, q.close_reason, q.duplicate_of = Status.OPEN, "", None

    def search(self, tags: set[str], sort: str = "votes", limit: int = 10) -> list[Question]:
        """Questions carrying every tag. Intersect starting from the rarest tag."""
        with self._lock:
            sets = sorted((self._by_tag.get(t.lower(), set()) for t in tags), key=len)
            ids = set(sets[0]).intersection(*sets[1:]) if sets else set()
            found = [self.posts[i] for i in ids]
        key = (lambda q: (-q.score, -q.id)) if sort == "votes" else (lambda q: -q.id)
        return sorted(found, key=key)[:limit]


if __name__ == "__main__":
    so = QAService()
    ReputationService(so.bus)
    ann, bo, cy, mod = (so.register(u) for u in ["ann", "bo", "cy", "mod"])
    mod.adjust(5000)

    q = so.ask(ann, "Why is my HashMap slow?", "...", {"java", "Performance"})
    a1, a2 = so.answer(bo, q, "Bad hashCode."), so.answer(cy, q, "Resize churn.")

    so.vote(cy, a1, 1)
    so.vote(cy, a1, 1)                                     # same vote again: no change, no event
    assert a1.score == 1 and bo.reputation == 11
    so.vote(cy, a1, -1)                                    # flip: undo +10, apply -2, voter pays 1
    assert a1.score == -1 and bo.reputation == -1 and cy.reputation == 0
    so.vote(cy, a1, 0)                                     # retract: everything back
    assert a1.score == 0 and bo.reputation == 1 and cy.reputation == 1

    so.accept(ann, a1, q)
    assert (bo.reputation, ann.reputation) == (16, 3)
    so.accept(ann, a2, q)                                  # switch: bo loses 15, cy gains 15
    assert (bo.reputation, cy.reputation, ann.reputation) == (1, 16, 3)

    q2 = so.ask(bo, "HashMap slow lookups", "...", {"java"})
    so.close(mod, q2, "duplicate", duplicate_of=q)
    try:
        so.answer(cy, q2, "late")
        raise AssertionError("answers on a duplicate must be rejected")
    except QAError:
        pass
    so.vote(bo, q, 1)
    assert [x.id for x in so.search({"java"})] == [q.id, q2.id]
    assert so.search({"java", "performance"}) == [q] and so.search({"rust"}) == []
    print("qa.py: all assertions passed")
import assert from "node:assert/strict";

export const RULES = { upvoteGain: 10, downvoteLoss: 2, answerDownvoteCost: 1, acceptedGain: 15, accepterGain: 2, closePrivilege: 3000 };

export class QAError extends Error {}

export class User {
  constructor(readonly id: string, public reputation = 1) {}
  adjust(delta: number): void { this.reputation += delta; }   // single-threaded event loop: no lock needed
}

export abstract class Post {
  readonly comments: string[] = [];
  private readonly votes = new Map<string, number>();        // voter id -> +1 or -1
  score = 0;
  constructor(readonly id: number, readonly author: User, readonly body: string) {}

  /** Set this voter's vote to value (+1, -1 or 0). Returns the previous value. */
  setVote(voter: User, value: number): number {
    if (![-1, 0, 1].includes(value)) throw new QAError("vote must be -1, 0 or 1");
    if (voter === this.author) throw new QAError("cannot vote on your own post");
    const old = this.votes.get(voter.id) ?? 0;
    if (value) this.votes.set(voter.id, value); else this.votes.delete(voter.id);
    this.score += value - old;
    return old;
  }
}

export type Status = "OPEN" | "CLOSED" | "DUPLICATE";

export class Question extends Post {
  status: Status = "OPEN";
  closeReason = "";
  duplicateOf: Question | null = null;
  readonly answers: Answer[] = [];
  accepted: Answer | null = null;
  constructor(id: number, author: User, readonly title: string, body: string, readonly tags: ReadonlySet<string>) {
    super(id, author, body);
  }
}

export class Answer extends Post {
  constructor(id: number, author: User, body: string, readonly question: Question) { super(id, author, body); }
}

// ---------- events and the bus (Observer) ----------
export type QAEvent =
  | { kind: "VoteChanged"; post: Post; voter: User; old: number; next: number }
  | { kind: "AcceptChanged"; question: Question; old: Answer | null; next: Answer | null };

export class EventBus {
  private readonly subs = new Map<string, Array<(e: QAEvent) => void>>();
  subscribe<K extends QAEvent["kind"]>(kind: K, handler: (e: Extract<QAEvent, { kind: K }>) => void): void {
    const list = this.subs.get(kind) ?? [];
    list.push(handler as (e: QAEvent) => void);
    this.subs.set(kind, list);
  }
  publish(e: QAEvent): void { for (const h of this.subs.get(e.kind) ?? []) h(e); }
}

type Delta = [User, number];

/** A change from old to new applies effects(new) minus effects(old), so any reversal is exact. */
export class ReputationService {
  constructor(bus: EventBus) {
    bus.subscribe("VoteChanged", (e) => apply(voteEffects(e.post, e.voter, e.next), voteEffects(e.post, e.voter, e.old)));
    bus.subscribe("AcceptChanged", (e) => apply(acceptEffects(e.question, e.next), acceptEffects(e.question, e.old)));
  }
}

export function voteEffects(post: Post, voter: User, value: number): Delta[] {
  if (value === 1) return [[post.author, RULES.upvoteGain]];
  if (value === -1) {
    const cost: Delta[] = post instanceof Answer ? [[voter, -RULES.answerDownvoteCost]] : [];
    return [[post.author, -RULES.downvoteLoss], ...cost];
  }
  return [];
}

export function acceptEffects(q: Question, a: Answer | null): Delta[] {
  if (!a || a.author === q.author) return [];                  // self-accept earns nothing
  return [[a.author, RULES.acceptedGain], [q.author, RULES.accepterGain]];
}

function apply(gain: Delta[], undo: Delta[]): void {
  for (const [u, d] of gain) u.adjust(d);
  for (const [u, d] of undo) u.adjust(-d);
}

// ---------- the facade ----------
export class QAService {
  readonly users = new Map<string, User>();
  private readonly byTag = new Map<string, Set<Question>>();
  private nextId = 1;
  constructor(readonly bus = new EventBus()) {}

  register(id: string, reputation = 1): User {
    const u = this.users.get(id) ?? new User(id, reputation);
    this.users.set(id, u);
    return u;
  }

  ask(author: User, title: string, body: string, rawTags: string[]): Question {
    const tags = new Set(rawTags.map((t) => t.trim().toLowerCase()));
    if (tags.size < 1 || tags.size > 5) throw new QAError("a question needs 1 to 5 tags");
    const q = new Question(this.nextId++, author, title, body, tags);
    for (const t of tags) this.byTag.set(t, (this.byTag.get(t) ?? new Set()).add(q));
    return q;
  }

  answer(author: User, q: Question, body: string): Answer {
    if (q.status !== "OPEN") throw new QAError(`question is ${q.status}`);
    const a = new Answer(this.nextId++, author, body, q);
    q.answers.push(a);
    return a;
  }

  comment(author: User, post: Post, text: string): void { post.comments.push(`${author.id}: ${text}`); }

  vote(voter: User, post: Post, value: number): void {
    const old = post.setVote(voter, value);
    if (old !== value) this.bus.publish({ kind: "VoteChanged", post, voter, old, next: value });
  }

  /** Accept an answer, switch to another, or pass null to un-accept. */
  accept(by: User, answer: Answer | null, q: Question): void {
    if (by !== q.author) throw new QAError("only the asker can accept");
    if (answer && answer.question !== q) throw new QAError("answer belongs to another question");
    const old = q.accepted;
    q.accepted = answer;
    if (old !== answer) this.bus.publish({ kind: "AcceptChanged", question: q, old, next: answer });
  }

  close(by: User, q: Question, reason: string, duplicateOf: Question | null = null): void {
    if (by.reputation < RULES.closePrivilege) throw new QAError("closing needs 3000 reputation");
    if (duplicateOf && (duplicateOf === q || duplicateOf.status === "DUPLICATE")) throw new QAError("point duplicates at a canonical question");
    if (q.status !== "OPEN") throw new QAError(`question is already ${q.status}`);
    q.status = duplicateOf ? "DUPLICATE" : "CLOSED";
    q.closeReason = reason;
    q.duplicateOf = duplicateOf;
  }

  reopen(by: User, q: Question): void {
    if (by.reputation < RULES.closePrivilege) throw new QAError("reopening needs 3000 reputation");
    if (q.status === "OPEN") throw new QAError("question is already open");
    q.status = "OPEN"; q.closeReason = ""; q.duplicateOf = null;
  }

  /** Questions carrying every tag, intersecting from the rarest tag. */
  search(tags: string[], sort: "votes" | "newest" = "votes", limit = 10): Question[] {
    const sets = tags.map((t) => this.byTag.get(t.toLowerCase()) ?? new Set<Question>()).sort((a, b) => a.size - b.size);
    if (!sets.length) return [];
    const found = [...sets[0]].filter((q) => sets.every((s) => s.has(q)));
    const order = sort === "votes" ? (a: Question, b: Question) => b.score - a.score || b.id - a.id
                                   : (a: Question, b: Question) => b.id - a.id;
    return found.sort(order).slice(0, limit);
  }
}

if (process.argv[1]?.endsWith("qa.ts")) {
  const so = new QAService();
  new ReputationService(so.bus);
  const [ann, bo, cy] = ["ann", "bo", "cy"].map((u) => so.register(u));
  const mod = so.register("mod", 5001);

  const q = so.ask(ann, "Why is my HashMap slow?", "...", ["java", "Performance"]);
  const a1 = so.answer(bo, q, "Bad hashCode."), a2 = so.answer(cy, q, "Resize churn.");

  so.vote(cy, a1, 1);
  so.vote(cy, a1, 1);                                          // same vote again: no change, no event
  assert.deepEqual([a1.score, bo.reputation], [1, 11]);
  so.vote(cy, a1, -1);                                         // flip: undo +10, apply -2, voter pays 1
  assert.deepEqual([a1.score, bo.reputation, cy.reputation], [-1, -1, 0]);
  so.vote(cy, a1, 0);                                          // retract: everything back
  assert.deepEqual([a1.score, bo.reputation, cy.reputation], [0, 1, 1]);

  so.accept(ann, a1, q);
  assert.deepEqual([bo.reputation, ann.reputation], [16, 3]);
  so.accept(ann, a2, q);                                       // switch: bo loses 15, cy gains 15
  assert.deepEqual([bo.reputation, cy.reputation, ann.reputation], [1, 16, 3]);

  const q2 = so.ask(bo, "HashMap slow lookups", "...", ["java"]);
  so.close(mod, q2, "duplicate", q);
  assert.throws(() => so.answer(cy, q2, "late"), QAError);
  so.vote(bo, q, 1);
  assert.deepEqual(so.search(["java"]), [q, q2]);
  assert.deepEqual(so.search(["java", "performance"]), [q]);
  assert.deepEqual(so.search(["rust"]), []);
  console.log("qa.ts: all assertions passed");
}

Notes on the code:

  • setVote returns the old value. The caller needs it to build the event, and reading it inside the same lock as the write is what makes the event truthful.
  • Reputation can go negative here. Stack Overflow floors displayed reputation at 1. Do the flooring on display, not in the counter. If you clamp the counter, a downvote that hits the floor and is then retracted would add 2 that were never taken, and reversal stops being exact.
  • Search intersects from the smallest tag set. For {java, jvm}, it starts from the few hundred jvm questions rather than the millions of java ones. Sorting happens after filtering, and limit caps the result.

7. Concurrency

Shared stateContended byProtection
A post's vote map and scoreeveryone voting on that postthe post's own lock, held only for read-old, write-new, adjust-score
A user's reputationevery event touching that useran atomic counter (AtomicInteger, or a small lock in Python)
A question's status, answers, accepted answeranswering, closing, acceptingthe question's lock
Tag indexasking and searchingconcurrent map of concurrent sets in Java, the service lock in Python

The lost update

sequenceDiagram
    participant A as Voter A
    participant P as Post, score 41
    participant B as Voter B
    A->>P: read score 41
    B->>P: read score 41
    A->>P: write 42
    B->>P: write 42
    Note over A,B: two upvotes, one counted

score += 1 is a read, an add and a write. Two threads can interleave between them. Worse, the vote map and the score must change together: if a thread records Bo's vote in the map but another thread reads the score before the add, the two disagree. Holding the post's lock around all three steps (read the old vote, write the new one, adjust the score) makes them one atomic action per post. Votes on different posts never wait for each other.

Why events go out after the lock

QAService.vote calls setVote (locks and unlocks the post), then publishes. If it published while holding the post lock, the reputation handler would take the user's lock while still holding the post's. Another code path that locked a user and then a post (say, a moderator tool that deletes a user's posts) would then risk deadlock. Never calling out to unknown code while holding a lock removes that whole class of bug.

That leaves one question: two events for the same voter can now be delivered in a different order from the one in which they were applied. Voter Cy changes 0 → +1 on thread 1 and +1 → −1 on thread 2. If thread 2's event is handled first, the author briefly gets "−10 −2" before "+10". Because each event applies effects(new) − effects(old), the sum over both events is effects(−1) − effects(0) whatever the order. The deltas commute, so the final reputation is right. The Java race test below hammers this with eight threads randomly flipping one user's vote while 500 others upvote, and checks the result 50 times.

Why not one global lock?

It would be correct, and for a toy it's fine. But a viral answer receives hundreds of votes a minute while millions of other posts are being voted on, and a global lock serialises the entire site behind the busiest post. Per-post locks keep contention exactly where the data is shared.

In a database

The same design maps onto tables: a votes table with primary key (post_id, voter_id) gives "one vote per user" for free. An upsert returns the old value (INSERT … ON CONFLICT … RETURNING, or read-then-write inside a transaction with the row locked). The score is updated in the same transaction with UPDATE posts SET score = score + :delta, which is atomic. Reputation changes are written as rows in a ledger and summed, or applied as atomic increments. Publish the event through an outbox table so it's sent only if the transaction commits.

TypeScript. Node runs one thread, and every method here is synchronous, so no interleaving is possible and no locks are needed. The moment vote awaits a database call between reading the old value and writing the new one, the lost update returns, and you need the database-side atomicity above.

8. The interviewer adds…

Bounties

A bounty puts 50 to 500 of the offerer's reputation on a question for seven days. The reputation is taken up front (escrow) and is never refunded. The offerer awards it to an answer. If they don't, half goes to the top answer if it has a score of at least 2. This mirrors Stack Overflow's rule in simplified form.

stateDiagram-v2
    [*] --> OFFERED : offer, reputation held
    OFFERED --> AWARDED : offerer awards an answer
    OFFERED --> EXPIRED : seven days pass
    EXPIRED --> [*] : half to top answer if score is 2 or more
    AWARDED --> [*]

It's a new service next to QAService, and nothing in the core changes.

import threading
import time

from qa import Answer, QAError, QAService, Question, ReputationService, Status, User

DAY = 86_400


class BountyService:
    """Offer reputation on a question, held in escrow until awarded or expired."""

    def __init__(self, so: QAService, clock=time.time) -> None:
        self.so, self.clock = so, clock
        self.open: dict[int, tuple[User, int, float]] = {}    # question id -> (offerer, amount, expires)
        self._lock = threading.Lock()

    def offer(self, by: User, q: Question, amount: int, days: int = 7) -> None:
        if not 50 <= amount <= 500 or q.status is not Status.OPEN:
            raise QAError("bounty must be 50-500 on an open question")
        with self._lock:                                      # check and deduct as one step
            if q.id in self.open:
                raise QAError("one bounty at a time")
            if by.reputation < amount:
                raise QAError("not enough reputation")
            by.adjust(-amount)                                # paid up front, never refunded
            self.open[q.id] = (by, amount, self.clock() + days * DAY)

    def award(self, by: User, answer: Answer) -> None:
        with self._lock:
            offerer, amount, expires = self.open.get(answer.question.id, (None, 0, 0))
            if offerer is not by or self.clock() > expires or answer.author is by:
                raise QAError("no awardable bounty")
            del self.open[answer.question.id]
        answer.author.adjust(amount)

    def expire_due(self) -> None:
        """Unawarded bounty: half goes to the top answer if it scored at least 2."""
        with self._lock:
            due = [(qid, b) for qid, b in self.open.items() if self.clock() > b[2]]
            for qid, _ in due:
                del self.open[qid]
        for qid, (_, amount, _) in due:
            best = max(self.so.posts[qid].answers, key=lambda a: a.score, default=None)
            if best and best.score >= 2:
                best.author.adjust(amount // 2)


now = [0.0]
so = QAService()
ReputationService(so.bus)
ann, bo, cy, dee = (so.register(u, 200) for u in ["ann", "bo", "cy", "dee"])
bounties = BountyService(so, clock=lambda: now[0])

q = so.ask(ann, "Title", "...", {"python"})
a = so.answer(bo, q, "answer")
bounties.offer(ann, q, 100)
assert ann.reputation == 100
bounties.award(ann, a)
assert bo.reputation == 300 and q.id not in bounties.open

q2 = so.ask(cy, "Another", "...", {"python"})
a2 = so.answer(bo, q2, "answer")
so.vote(ann, a2, 1)
so.vote(dee, a2, 1)                                   # bo +20, score 2
bounties.offer(cy, q2, 50)
now[0] = 8 * DAY
bounties.expire_due()
assert bo.reputation == 300 + 20 + 25 and cy.reputation == 150
print("ext_bounty: ok")

The interesting line is the check-and-deduct in offer. "Has at least 100 reputation" and "subtract 100" must happen together, or two bounties offered at once could spend the same reputation twice. The bounty lock covers bounty-to-bounty races. Votes can still lower the offerer's reputation in between, which is acceptable here. For strict guarantees, give User a try_spend(amount) that checks and subtracts under the user's own lock.

Badges

"Nice Answer" at a score of 10, "Good Answer" at 25, each awarded once per post even if the score dips and recovers. It's a second observer on the same bus.

import assert from "node:assert/strict";
import { Answer, EventBus, QAService, ReputationService, type User } from "./qa.ts";

/** A second observer on the same bus. Nothing in QAService changes. */
export class BadgeService {
  readonly awarded = new Map<string, string[]>();              // user id -> badges
  private readonly seen = new Set<string>();                   // "postId:badge", each badge once per post
  constructor(bus: EventBus, private readonly thresholds = new Map([[10, "Nice Answer"], [25, "Good Answer"]])) {
    bus.subscribe("VoteChanged", (e) => {
      if (!(e.post instanceof Answer)) return;
      for (const [score, badge] of this.thresholds) {
        const key = `${e.post.id}:${badge}`;
        if (e.post.score >= score && !this.seen.has(key)) {
          this.seen.add(key);
          this.give(e.post.author, badge);
        }
      }
    });
  }
  private give(user: User, badge: string): void { this.awarded.set(user.id, [...(this.awarded.get(user.id) ?? []), badge]); }
}

const so = new QAService();
new ReputationService(so.bus);
const badges = new BadgeService(so.bus);
const [asker, author] = [so.register("asker"), so.register("author")];
const a = so.answer(author, so.ask(asker, "t", "b", ["ts"]), "answer");
const voters = Array.from({ length: 11 }, (_, i) => so.register(`v${i}`));
voters.slice(0, 10).forEach((v) => so.vote(v, a, 1));
so.vote(voters[0], a, 0);                                     // drops to 9
so.vote(voters[10], a, 1);                                    // back to 10: no second badge
assert.deepEqual(badges.awarded.get("author"), ["Nice Answer"]);
assert.equal(author.reputation, 1 + 10 * 10);
console.log("ext-badges: ok");

This is the payoff of the Observer design. Adding a feature that reacts to votes took zero edits to the voting code. The same shape gives you "notify the author when their question gets an answer" (subscribe to an AnswerPosted event), and you'd hand the delivery to something like the notification service.

Daily reputation cap

Stack Overflow caps reputation from votes at 200 per day. Put the cap in ReputationService, keyed by (user, day), and apply it only to vote gains, not accepts or bounties. The subtle part is reversal: if an upvote was capped (earned 0), retracting it must also take back 0. That means remembering what each vote actually earned, and the pure effects(new) − effects(old) no longer holds. Saying this out loud shows you understand why the simple version works.

9. Testing

Test the rules with plain single-threaded tests, and the concurrency with a stress test that checks an invariant rather than an exact interleaving. Designing for testability covers injecting clocks and fakes, which the bounty extension does for expiry.

import random
import threading

from qa import QAError, QAService, ReputationService, Status


def setup():
    so = QAService()
    ReputationService(so.bus)
    return so


def raises(fn, *args) -> bool:
    try:
        fn(*args)
    except QAError:
        return True
    return False


def test_votes_are_one_per_user_and_reject_self_votes():
    so = setup()
    asker, voter = so.register("asker"), so.register("voter")
    q = so.ask(asker, "t", "b", {"go"})
    for _ in range(3):
        so.vote(voter, q, 1)
    assert q.score == 1 and asker.reputation == 11
    assert raises(so.vote, asker, q, 1) and raises(so.vote, voter, q, 2)


def test_question_downvotes_are_free_for_the_voter():
    so = setup()
    asker, voter = so.register("asker"), so.register("voter")
    so.vote(voter, so.ask(asker, "t", "b", {"go"}), -1)
    assert asker.reputation == -1 and voter.reputation == 1


def test_lifecycle_and_privileges():
    so = setup()
    asker, newbie, mod = so.register("asker"), so.register("newbie"), so.register("mod", 3000)
    q, canon = so.ask(asker, "t", "b", {"go"}), so.ask(asker, "canon", "b", {"go"})
    assert raises(so.close, newbie, q, "off-topic")
    so.close(mod, q, "duplicate", canon)
    assert q.status is Status.DUPLICATE and raises(so.close, mod, q, "again")
    assert raises(so.close, mod, canon, "dup of a dup", q)
    so.reopen(mod, q)
    assert q.status is Status.OPEN and q.duplicate_of is None
    so.answer(newbie, q, "now allowed")
    assert raises(so.ask, asker, "t", "b", set()) and raises(so.ask, asker, "t", "b", set("abcdef"))


def test_concurrent_upvotes_from_many_users_are_all_counted():
    so = setup()
    author = so.register("author")
    q = so.ask(author, "t", "b", {"go"})
    voters = [so.register(f"v{i}") for i in range(200)]
    threads = [threading.Thread(target=so.vote, args=(v, q, 1)) for v in voters]
    [t.start() for t in threads]
    [t.join() for t in threads]
    assert q.score == 200 and author.reputation == 1 + 200 * 10


def test_one_user_hammering_vote_ends_consistent_with_their_final_vote():
    for _ in range(20):
        so = setup()
        asker, answerer, voter = so.register("asker"), so.register("answerer"), so.register("voter")
        a = so.answer(answerer, so.ask(asker, "t", "b", {"go"}), "x")
        barrier = threading.Barrier(8)

        def spam() -> None:
            barrier.wait()
            for _ in range(200):
                so.vote(voter, a, random.choice([-1, 0, 1]))

        threads = [threading.Thread(target=spam) for _ in range(8)]
        [t.start() for t in threads]
        [t.join() for t in threads]
        final = a.score                                   # one voter, so score == their vote
        assert final in (-1, 0, 1)
        expected = {1: (11, 1), 0: (1, 1), -1: (-1, 0)}[final]
        assert (answerer.reputation, voter.reputation) == expected


def test_search_requires_every_tag_and_sorts():
    so = setup()
    u, v = so.register("u"), so.register("v")
    q1 = so.ask(u, "a", "b", {"java", "jvm"})
    q2 = so.ask(u, "c", "d", {"java"})
    so.vote(v, q1, 1)
    assert so.search({"java"}) == [q1, q2] and so.search({"java"}, sort="newest") == [q2, q1]
    assert so.search({"JVM", "java"}) == [q1] and so.search(set()) == []


if __name__ == "__main__":
    for name, fn in list(globals().items()):
        if name.startswith("test_"):
            fn()
            print("ok", name)

The Java stress test runs with real parallelism (no GIL). 500 voters upvote one answer while eight threads flip a single spammer's vote at random. Whatever the interleaving, the score must be 500 + final spam vote, and both users' reputation must equal what that final state implies.

import java.util.*;
import java.util.concurrent.*;

public class VoteRaceTest {
    public static void main(String[] args) throws Exception {
        for (int round = 0; round < 50; round++) {
            QAService so = new QAService(new EventBus());
            new ReputationService(so.bus);
            User asker = so.register("asker", 1), answerer = so.register("answerer", 1), spammer = so.register("spammer", 1);
            Answer a = so.answer(answerer, so.ask(asker, "t", "b", Set.of("java")), "x");
            List<User> voters = new ArrayList<>();
            for (int i = 0; i < 500; i++) voters.add(so.register("v" + i, 1));
            CountDownLatch go = new CountDownLatch(1);
            try (ExecutorService pool = Executors.newFixedThreadPool(16)) {
                for (User v : voters) pool.submit(() -> { go.await(); so.vote(v, a, 1); return null; });
                for (int t = 0; t < 8; t++) pool.submit(() -> {
                    go.await();
                    for (int i = 0; i < 500; i++) so.vote(spammer, a, ThreadLocalRandom.current().nextInt(-1, 2));
                    return null;
                });
                go.countDown();
            }
            int spam = a.score() - 500;                       // the spammer's final vote
            int expectedAnswerer = 1 + 500 * 10 + (spam == 1 ? 10 : spam == -1 ? -2 : 0);
            int expectedSpammer = 1 + (spam == -1 ? -1 : 0);
            assert answerer.reputation() == expectedAnswerer && spammer.reputation() == expectedSpammer
                    : round + ": " + a.score() + " " + answerer.reputation() + " " + spammer.reputation();
        }
        System.out.println("VoteRaceTest: ok");
    }
}

The key idea in both race tests: you can't assert on a particular interleaving, so assert on an invariant that must hold for all of them. Here the invariant is "reputation equals the reputation implied by the final votes".

10. Common mistakes

  1. Toggle semantics for votes. toggleUpvote() makes a retried request undo itself. Use "set my vote to X".
  2. Storing votes as a counter only. Without the per-user map you can't enforce one vote per user or reverse a vote.
  3. Reputation handlers per transition. Six hand-written cases, one wrong sign. Use effects(new) − effects(old).
  4. Clamping the reputation counter at 1. Reversal stops being exact. Clamp on display.
  5. Updating score and vote map under different locks (or the score with an atomic and the map without). They drift apart.
  6. A global lock on the whole service. Correct but serialises the site behind its busiest post.
  7. Publishing events while holding a lock. It invites deadlocks and lets a slow subscriber stall voting.
  8. Letting anyone accept, or accepting an answer from another question. Both are one-line checks people forget.
  9. Duplicate chains. Closing A as a duplicate of B, which is a duplicate of C, sends readers on a hunt. Point at the canonical question.
  10. Searching by scanning all questions. Keep an inverted index from tag to questions, and intersect from the rarest tag.

11. Interview follow-ups

How do privileges work in general? A table from privilege to minimum reputation (upvote 15, comment 50, downvote 125, close 3,000 on Stack Overflow). Check it at the facade before the action. Make it a Specification per privilege if moderators and staff need overrides.

How would you detect serial voting (one user upvoting everything another user posts)? Another observer on VoteChanged. It counts votes per (voter, author) pair per day and flags pairs above a threshold. A nightly job reverses the flagged votes by publishing VoteChanged(+1 → 0) events. Reputation comes back automatically, because reversal is just another event.

The vote count on the page is slightly stale. Is that OK? Yes, for display. The page can read a cached score. The invariants that matter (one vote per user, exact reputation) are enforced on write. This is the read/write split that projections formalise.

How would you rank answers? Accepted answer first, then by score, with ties broken by age. Stack Overflow has since stopped pinning the accepted answer to the top by default, which is a good example of a ranking rule that changes. Make it a strategy passed to the query, not a field on Question.

How do you handle deleting a post? Soft-delete with a flag, so votes and history stay intact. Reputation from a deleted post's votes is reversed by emitting the inverse events, using the same machinery as vote retraction.

Could you event-source the whole thing? Yes, and it fits well. Votes, accepts and closes are already events with old and new values. Store them as the source of truth, and the score, reputation and tag index become projections you can rebuild. See event sourcing. The cost is that every read model now has a rebuild path to test.

How would tag search scale? The inverted index moves to a search engine. Each question becomes a document with tags, score and timestamps. Sorted tag queries are then a filter plus sort on indexed fields. Keep the in-memory index for the interview, and mention the move.

What if two moderators close and reopen at the same moment? The question lock serialises them. Each operation checks the current state inside the lock and throws if the transition is illegal (closing an already-closed question). The loser gets a clear error instead of silently overwriting.