"Design Stack Overflow" sounds like a list of nouns. A weak answer draws a Question with a list of Answers, gives each an int votes, adds upvote() and downvote() methods, and stops. The page looks right, and none of the rules are there yet.
The interviewer is checking a few specific things. A person gets one vote on a post, and may change it or take it back. Each vote moves someone's reputation, and taking the vote back must move it back by exactly the same amount, even if the points table changed in between. Reputation earns privileges, such as downvoting. The asker can accept one answer and then change their mind. And thousands of people can vote on one popular answer at the same moment.
This article follows a 45 minute interview. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| What can people vote on? | Questions and answers. Not comments | Votes live on a shared Post base class |
| Can a person change or take back a vote? | Yes, at any time. One vote per person per post | A map from voter to vote on each post, and a retractVote |
| What does voting the same way twice do? | Nothing | A repeated vote is safe to retry |
| What is each action worth? | Upvote +10 to the author. Downvote −2 to the author, and −1 to the voter if it is on an answer. Accepted answer +15 | A ReputationPolicy interface |
| Do these numbers change? | Yes. Old votes keep the points they gave | Each vote stores the effect it had |
| Can you vote on your own post? | No | A check before anything else |
| What does reputation allow? | Upvoting at 15, downvoting at 125 | A Privileges object built from a table |
| Can reputation drop below 1? | Yes, in this version | The floor is a follow-up, kept out so undo stays exact |
| Who accepts an answer, and can it change? | Only the asker. They may switch or unaccept. Accepting your own answer earns nothing | The 15 points move with the acceptance |
| How do people find questions? | By tags (all of the ones given) and by whole words in the title, newest or most votes first | A TagIndex, a SearchQuery and a SortOrder |
| How many requests at once? | Many, from many threads | Locks on posts, and reputation that never loses an update |
The question that matters most is "do these numbers change?" If the points table never changes, a vote does not need to remember anything: taking it back can ask the table again. Once the table can change, a vote cast under the old table and taken back under the new one would return the wrong amount. So each vote must carry the points it gave. That one answer shapes the Vote record, the undo path and the acceptance code.
Requirements
Functional:
- A user asks a question with a title, a body and one to five tags. Any user can answer it.
- A user can upvote or downvote a question or an answer, change the vote, or take it back. A person has at most one vote on a post, and cannot vote on their own post.
- Each vote changes reputation by the table above. Taking a vote back, or changing it, reverses exactly what the vote gave, even if the table has changed since.
- Upvoting needs 15 reputation and downvoting needs 125. Taking a vote back needs nothing.
- Only the asker can accept an answer, and at most one at a time. Switching to another answer moves the 15 points. Unaccepting takes them back.
- Search finds questions that carry all the given tags and have all the given words as whole words in the title, sorted by newest or by score.
Out of scope: comments, editing, closing and deleting posts, badges, bounties, a daily cap on reputation, and notifications. We come back to these at the end, because each is a likely follow-up.
Everything lives in memory, as is normal for a low-level design interview.
What the code itself must handle:
- Many votes at once. One popular answer gets votes from many threads, and no vote or point may be lost.
- Rules that change. The points table sits behind an interface, and the privilege thresholds come from a table.
- Exact undo. Every change of reputation can be reversed to the point.
Finding the classes
Picking the nouns out of the requirements gives a first list. Users, questions and answers carry state that changes and that several threads touch, so they become classes. A vote, a tag and a search are values. The points table is a rule the business will change, so it becomes an interface.
Should reputation be a class of its own?
A Reputation class per user that keeps every event and adds them up
It is exact and keeps a full history. But every read of a user's reputation would add up their whole history, and the history repeats what the votes already hold.
A number on User, and each vote records the change it madeOur pick
Reading reputation is one read of an AtomicInteger. The history is not lost: each Vote holds the points it gave, so an undo knows exactly what to reverse. The cost is that rebuilding a user's total means taking their starting reputation and adding every stored vote and acceptance that names them. That includes the 1 point each of their answer downvotes cost them. It is a job for later, not a request.
Data or behaviour?
Some classes only carry values and never change: a vote, the points an action gave, a tag, a search and one search result. In Java these are records. A record's fields are fixed when it is created, and it gets equals, hashCode and toString for free. User, Question and Answer are ordinary classes, because their votes, scores and reputation change and their methods guard those changes.
The class diagram
The classes fall into three groups:
- Data: the records
Vote,ReputationEffect,ReputationChange,Tag,SearchQueryandQuestionSummary, and the enumsVoteType,PostKind,PrivilegeandSortOrder. - The core:
QaService,User,Post,QuestionandAnswer. They share theqapackage with theVoterecord, so the methods that change a post or a user can be package-private. - Rules and the index: the
ReputationPolicyinterface,PrivilegesandTagIndex.
Building it
Questions and answers
A question and an answer have a lot in common. Each has an author, a body, a time, a score and a set of votes. Only a question has a title, tags, a list of answers and an accepted answer. Only an answer knows its question.
/** What questions and answers share: an author, a body, and votes. Each post is its own lock. */public abstract class Post { private final long id; private final String authorId; private final String body; private final Instant createdAt; private final Map<String, Vote> votesByVoter = new HashMap<>(); private int score;Post is abstract and holds what both share: the votes, in a HashMap keyed by voter id, and the score. Question and Answer extend it. The rules for voting are written once, in Post, and both kinds get them.
Are questions and answers one class or two?
One Post class with a type field
There is one place for votes. But the title, the tags and the accepted answer are fields that are empty on every answer, and nothing stops a caller from accepting a question.
Two unrelated classes
Each class has only its own fields. But the voting code, the trickiest code in the design, is written twice and has to stay the same in both.
An abstract Post with Question and Answer extending itOur pick
Voting lives in one place, and each subclass adds only its own fields. Question.accept takes an Answer, so the compiler stops our own code from accepting a question, and QaService.accept refuses a question's id. The cost is one level of inheritance, which is safe here because both kinds are posts and vote the same way.
The points table
The business will change how much each action is worth. The rules also differ by what was voted on: a downvote on an answer costs the voter 1 point, and a downvote on a question costs nothing.
@Override public ReputationEffect forVote(PostKind kind, VoteType type, String authorId, String voterId) { if (type == VoteType.UP) { int reward = kind == PostKind.ANSWER ? points.answerUpvote() : points.questionUpvote(); return ReputationEffect.of(new ReputationChange(authorId, reward)); } if (kind == PostKind.QUESTION) { return ReputationEffect.of(new ReputationChange(authorId, points.downvote())); } return ReputationEffect.of( new ReputationChange(authorId, points.downvote()), new ReputationChange(voterId, points.answerDownvoteCost())); } @Override public ReputationEffect forAcceptance(String answererId, String askerId) { if (answererId.equals(askerId)) { // Accepting your own answer is allowed, but earns nothing. return ReputationEffect.NONE; } return ReputationEffect.of(new ReputationChange(answererId, points.accepted())); }The policy does not change anyone's reputation. It returns a ReputationEffect, a record that lists who gets how many points. An answer downvote is the one action with two changes, lines 41 to 43: −2 for the author and −1 for the voter. Accepting your own answer returns an empty effect.
public ReputationEffect reversed() { return new ReputationEffect(changes.stream().map(ReputationChange::negated).toList()); } public ReputationEffect plus(ReputationEffect other) { List<ReputationChange> both = new ArrayList<>(changes); both.addAll(other.changes); return new ReputationEffect(both); }reversed flips the sign of every change, and plus joins two effects. These two methods are all the undo logic needs. ReputationChange refuses any change of more than 1,000 points either way, so no policy, even one swapped in later, can build a change that cannot be reversed. StandardReputation.Points uses the same bound.
Casting, changing and taking back a vote
QaService.vote checks the request, asks the policy for the effect, and hands the post a Vote record that carries the effect with it:
public void vote(String voterId, long postId, VoteType type) { Objects.requireNonNull(type, "type"); User voter = user(voterId); Post post = post(postId); if (post.authorId().equals(voterId)) { throw new ActionNotAllowedException("you cannot vote on your own post"); } if (post.voteBy(voterId).orElse(null) == type) { // A retry of the same vote changes nothing, even if the voter has since lost the privilege. return; } privileges.require(type.requiredPrivilege(), voter.reputation()); ReputationEffect effect = checked(reputation.forVote(post.kind(), type, post.authorId(), voterId)); apply(post.vote(new Vote(voterId, type, effect))); } public void retractVote(String voterId, long postId) { user(voterId); apply(post(postId).retract(voterId)); }- No self-votes (line 75). This check comes first, so a user voting on their own post hears the real reason, not a reputation message.
- A retry changes nothing (lines 78 to 81). If the voter already has this vote, the call returns before the privilege check. A user at 125 who downvoted an answer is now at 124, and a retry of that downvote must not be refused.
- The privilege check (line 82). Each
VoteTypenames the privilege it needs. - The policy prices the effect (line 83) under whatever rules are in force. A policy can be swapped while the site runs, so the private
checkedmethod makes sure every user the effect names exists before anything is stored. - The post stores it (line 84), and returns the reputation to apply.
The post does the part that must happen in one step:
/** Stores the vote. Returns the reputation to apply: the new vote's, less the one it replaced. */ synchronized ReputationEffect vote(Vote vote) { Vote previous = votesByVoter.get(vote.voterId()); if (previous == null) { votesByVoter.put(vote.voterId(), vote); score += vote.type().weight(); return vote.effect(); } if (previous.type() == vote.type()) { return ReputationEffect.NONE; } ReputationEffect change = previous.effect().reversed().plus(vote.effect()); votesByVoter.put(vote.voterId(), vote); score += vote.type().weight() - previous.type().weight(); return change; } /** Removes the user's vote. Returns the reputation to apply: exactly what that vote gave, reversed. */ synchronized ReputationEffect retract(String voterId) { Vote previous = votesByVoter.get(voterId); if (previous == null) { return ReputationEffect.NONE; } ReputationEffect change = previous.effect().reversed(); votesByVoter.remove(voterId); score -= previous.type().weight(); return change; }If the voter has no vote yet, the post stores the new one and returns its effect. If the voter is changing a vote, the post works out the old effect reversed plus the new one (line 70), swaps the vote and moves the score. For Ben, changing a downvote on Chen's answer to an upvote returns Chen +2, Ben +1 and Chen +10. retract works out the reversal and removes the vote (lines 82 and 83). A retract with no vote returns nothing, so it is safe to retry.
What does voting the same way twice do?
Toggle: a second upvote takes the first one back
It matches the button on the page. But a double click, or a retry after a dropped connection, would undo the vote the person meant to cast.
Nothing, and taking a vote back is its own callOur pick
QaService returns early when the type is unchanged, before the privilege check, so a retry is harmless even from a voter who has since dropped below the threshold. Lines 67 to 69 of Post do the same for two identical votes that arrive together. The page can still toggle: it calls retractVote when the button is already lit. A repeat also keeps the stored effect, so it never reprices an old vote under new rules.
Taking a vote back after the rules change
Here is where the stored effect pays for itself. Chen upvotes Ben's answer while an answer upvote is worth 10. Later the business makes it 15. Then Chen takes the vote back.
When a vote is undone, how much reputation comes back?
Whatever today's rule says the vote is worth
There is nothing to store. But after any change to the table, every undo is wrong by the difference, and the error is permanent. Changing the table would quietly move everyone's reputation.
Recalculate the user's whole reputation from all their votes
It is always consistent with the current rule. But one undo would read every vote the user ever received, and every user's total would jump whenever the rule changed.
Exactly what the vote gave, stored in the Vote recordOur pick
The undo reverses the stored effect, so reputation always returns to where it was. The cost is a small list on every vote. If the business does want old votes repriced, that is a separate job that walks the stored votes, not a side effect of an undo.
Privileges
A user below 15 cannot upvote, and a user below 125 cannot downvote. The numbers are a table the business will tune, so Privileges is built from a map at startup and checks that every privilege has a minimum of at least 1:
public void require(Privilege privilege, int reputation) { int needed = minimumFor(privilege); if (reputation < needed) { throw new NotEnoughReputationException(privilege, needed, reputation); } }Line 31 refuses only a reputation below the minimum, so a user with exactly 125 may downvote. The refusal is a NotEnoughReputationException, which extends ActionNotAllowedException and carries the number needed and the number the user has. Its message, such as "downvote needs 125 reputation, you have 101", is meant for the person. Bad arguments, such as a blank title or an unknown post id, are a programmer's mistake and throw IllegalArgumentException or NoSuchElementException instead.
Taking a vote back needs no privilege. A user at 125 who downvotes an answer pays 1 point and drops to 124. They must still be able to change their mind.
Where do the reputation thresholds live?
In the Privilege enum, as UPVOTE(15) and DOWNVOTE(125)
The numbers sit next to the names. But changing one means a new release, and a test cannot build a site with other numbers.
A Privileges object built from a map and handed to QaServiceOur pick
The numbers come from configuration, and the constructor refuses a table that leaves a privilege out. Tests build a site with thresholds of their own. The check is one method, require, so every caller refuses in the same way.
Accepting an answer
Only the asker can accept, and the 15 points go to the answer's author. The asker may switch to another answer or unaccept. Question keeps the accepted answer and, beside it, the effect that accepting it had:
/** Marks the answer accepted. Returns the reputation to apply: the new effect, less the old one. */ synchronized ReputationEffect accept(Answer answer, ReputationEffect effect) { if (answer.questionId() != id()) { throw new IllegalArgumentException("answer " + answer.id() + " is not an answer to " + id()); } if (answer == accepted) { return ReputationEffect.NONE; } ReputationEffect change = acceptanceEffect.reversed().plus(effect); accepted = answer; acceptanceEffect = effect; return change; } /** Clears the accepted answer. Returns what accepting it gave, reversed. */ synchronized ReputationEffect unaccept() { ReputationEffect change = acceptanceEffect.reversed(); accepted = null; acceptanceEffect = ReputationEffect.NONE; return change; }This is the same idea as the vote. A switch returns the stored effect reversed plus the new effect (line 78), so Ben loses exactly the 15 he got and Chen gains 15. Both happen under the question's lock, so two accepts from the asker's phone and laptop cannot both keep their points. Accepting the answer that is already accepted returns nothing (lines 75 to 77). If the rule changed in between, re-accepting would otherwise reprice the old acceptance.
When the asker switches the accepted answer, what happens to the 15 points?
The first answerer keeps them
It is the simplest code. But an asker could accept five answers in turn and hand out 75 points, and a friend's answer could be accepted and unaccepted for free points.
Reverse the stored effect and apply the new one, under the question's lockOur pick
At any moment, exactly one answerer holds the acceptance points, and the amount is what they were given. The cost is one more field on Question, acceptanceEffect, beside accepted.
Many votes at once
When an answer goes viral, thousands of people vote on it within minutes, and many of those requests reach the same Post at the same time. Two things must stay exact: the post's votes and score, and every user's reputation.
The design has one lock per post. Post.vote and Post.retract are synchronized, so reading the old vote, working out the change, storing the new vote and moving the score happen as one step for that post. Different posts never wait for each other. Question.accept and unaccept lock the question in the same way.
Reputation is different. One user's reputation is changed by votes on all of their posts, and each of those runs under a different post's lock. So User keeps reputation in an AtomicInteger:
// No lock is held here. Each user's reputation is atomic, and additions can land in any order. private void apply(ReputationEffect effect) { for (ReputationChange change : effect.changes()) { user(change.userId()).addReputation(change.points()); } }apply runs after the post's lock is released. That is safe because additions can happen in any order and still give the same total. The post's lock guarantees that each stored vote is handed back for reversal at most once, so each effect is added once and taken away at most once. No lock is ever held while another is taken, so the design cannot deadlock.
There is a cost. Between Post.vote storing the vote and apply adding the points, another thread can see the new score before Ben's reputation has moved. That gap only affects what someone sees, never the totals. The privilege check also reads reputation a moment before the vote lands, so a user whose reputation drops at that instant can still cast that one vote. We accept both.
The project includes a check, demo/RaceCheck.java. Two thousand voters, each with 200 reputation, hit one answer from 16 threads that a latch releases together. Every voter upvotes. Half of them then switch to a downvote, and a quarter take their vote back. Meanwhile the asker accepts and unaccepts the answer 500 times, and ends with it accepted:
2000 voters on one answer, 16 threads, the asker accepting and unaccepting score: 500 (expected 500) Ana's reputation: 9016 (expected 9016) voters' reputation, sum: 399500 (expected 399500)
All three numbers match. We also ran it in a scratch copy with synchronized removed from vote and retract. In most runs the score fell below 500, and the reputation totals came out wrong, Ana's too high and the voters' too low. With AtomicInteger replaced by a plain read and write, the score stayed right but Ana's reputation came out short. The exact numbers change from run to run and from machine to machine.
Where do the locks go?
One lock around every vote on the site
It is correct and easy to explain. But every vote on every post waits for every other, and a viral answer slows down the whole site.
Lock the voter and the author together
Reputation changes under a lock too. But a vote needs two user locks, always taken in the same order to avoid deadlock, and a popular author's lock becomes the queue for all of their posts.
One lock per post, and reputation in an AtomicIntegerOur pick
Votes on different posts run in parallel, and each lock is held only to update one map entry and one score. Reputation needs no lock at all, because each change is a single atomic addition. The cost is the short gap described above, where a score can move a moment before the reputation does.
Tags and search
A tag is a short lowercase word such as java or c++. People type Java and java and mean the same tag, so Tag.of trims and lowercases what was typed before the record checks it:
public record Tag(String name) { private static final Pattern VALID = Pattern.compile("[a-z0-9][a-z0-9.#+-]{0,34}"); public Tag { Objects.requireNonNull(name, "name"); if (!VALID.matcher(name).matches()) { throw new IllegalArgumentException("not a valid tag: \"" + name + "\""); } } public static Tag of(String typed) { return new Tag(typed.strip().toLowerCase(Locale.ROOT)); }The pattern on line 12 allows lowercase letters, digits and .#+-, up to 35 characters, starting with a letter or a digit. A question carries one to five tags, and Tag.all drops a repeat, so Java, java counts as one.
To search by tag, QaService keeps a TagIndex: a map from each tag to the ids of the questions that carry it.
public List<QuestionSummary> search(SearchQuery query) { Collection<Long> ids = query.tags().isEmpty() ? posts.keySet() : tagIndex.questionsWithAll(query.tags()); List<QuestionSummary> found = new ArrayList<>(); for (long id : ids) { if (posts.get(id) instanceof Question question && query.matchesTitle(question.title())) { found.add(question.summary()); } } found.sort(query.order().comparator()); return List.copyOf(found.subList(0, Math.min(query.limit(), found.size()))); }With tags, the search starts from the index and keeps only the ids found under every tag (questionsWithAll keeps the ids in all the sets). With no tags, it scans every post and skips the answers. It then checks that every query word is a whole word of the title, so java does not find "JavaScript closures". Each match is copied into a QuestionSummary (line 111) before the list is sorted (line 114).
The copy matters. Scores change while a search runs. If the sort compared live scores, one question's score could change between two comparisons, and Java's sort can throw "Comparison method violates its general contract" when that happens. A summary holds the score at the moment it was copied, so the sort sees fixed values.
Search skips any id it cannot find in posts, so a question appears once both writes land, whichever runs first. Tags cannot be edited in this version, so a question's index entries never change.
How does search find questions by tag?
Scan every question and check its tags
It needs no extra structure. But every search reads every question on the site, most of which have nothing to do with the tag.
A full-text search engine beside the site
It ranks well and scales to millions of questions. But it is a separate system to keep in step with every new question, which is more than the interview asks for.
A tag index from each tag to its question ids, then filter and sort copiesOur pick
A search reads only the questions that carry the tags. The index uses a ConcurrentHashMap of concurrent sets, so ask and search can run at once without a lock. The cost is that a search by title words alone still scans every post.
The final design
QaService is the core. It owns the users and the posts, checks privileges through Privileges, finds tagged questions through TagIndex, and reaches the points table only through the ReputationPolicy interface. Each Post guards its own votes with its own lock, each Vote carries the reputation it gave, and each Question carries what its accepted answer gave.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should reputation be a class of its own? | A number on User, and each vote records the change it made | Reads are one atomic read, and undo still knows what to reverse |
| 2 | Are questions and answers one class or two? | An abstract Post with Question and Answer extending it | Voting is written once |
| 3 | What does voting the same way twice do? | Nothing, and taking a vote back is its own call | A retry is harmless |
| 4 | When a vote is undone, how much reputation comes back? | Exactly what the vote gave, stored in the Vote record | A rule change never breaks an undo |
| 5 | Where do the reputation thresholds live? | A Privileges object built from a map and handed to QaService | The numbers change without a release |
| 6 | When the asker switches the accepted answer, what happens to the 15 points? | Reverse the stored effect and apply the new one, under the question's lock | One answerer holds the points at a time |
| 7 | Where do the locks go? | One lock per post, and reputation in an AtomicInteger | Posts never wait for each other |
| 8 | How does search find questions by tag? | A tag index from each tag to its question ids, then filter and sort copies | It reads only matching questions, and sorts fixed scores |
Here is Chen's upvote on Ben's answer from the demo, end to end, and the undo that follows the rule change:
- Chen's browser calls
QaService.vote. The service finds that Chen did not write A2 and has no vote on it yet, andPrivileges.requirefinds he has the 15 an upvote needs. ReputationPolicy.forVotereturns an effect of Ben +10, andcheckedfinds that Ben exists. This is the only call to a rule, and no lock is held while it runs.Post.votetakes A2's lock, finds no earlier vote from Chen, stores theVotewith its effect, and moves the score from 0 to 1. If Chen had voted down before, it would also return that vote's effect reversed.- The lock is released, and
applycallsUser.addReputation, which moves Ben from 200 to 210 with oneaddAndGet. - The business swaps in a new policy with
changeReputationPolicy, and an answer upvote is now worth 15. - Chen calls
retractVote.Post.retracttakes A2's lock again, removes the vote and returns the stored effect reversed, soapplytakes exactly 10 from Ben. He ends at 200, where he started, even though the new rule says 15.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package qa; import java.time.Clock;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.NoSuchElementException;import java.util.Objects;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong; import exception.ActionNotAllowedException;import privilege.Privileges;import reputation.ReputationChange;import reputation.ReputationEffect;import reputation.ReputationPolicy;import search.QuestionSummary;import search.SearchQuery;import search.Tag;import search.TagIndex;import vote.VoteType; /** The site: users, posts, votes, accepted answers and search. Safe to call from many threads. */public final class QaService { private final Privileges privileges; private final Clock clock; private volatile ReputationPolicy reputation; private final Map<String, User> users = new ConcurrentHashMap<>(); private final Map<Long, Post> posts = new ConcurrentHashMap<>(); private final TagIndex tagIndex = new TagIndex(); private final AtomicLong postIds = new AtomicLong(); public QaService(ReputationPolicy reputation, Privileges privileges, Clock clock) { this.reputation = Objects.requireNonNull(reputation, "reputation"); this.privileges = Objects.requireNonNull(privileges, "privileges"); this.clock = Objects.requireNonNull(clock, "clock"); } public User registerUser(String userId, String name, int startingReputation) { User user = new User(userId, name, startingReputation); if (users.putIfAbsent(userId, user) != null) { throw new IllegalArgumentException("user " + userId + " already exists"); } return user; } /** New votes and acceptances use the new rules. Stored ones keep what they gave. */ public void changeReputationPolicy(ReputationPolicy policy) { reputation = Objects.requireNonNull(policy, "policy"); } public Question ask(String authorId, String title, String body, Set<Tag> tags) { user(authorId); Question question = new Question(postIds.incrementAndGet(), authorId, title, body, tags, clock.instant()); posts.put(question.id(), question); tagIndex.add(question.id(), question.tags()); return question; } public Answer answer(String authorId, long questionId, String body) { user(authorId); Question question = question(questionId); Answer answer = new Answer(postIds.incrementAndGet(), questionId, authorId, body, clock.instant()); posts.put(answer.id(), answer); question.addAnswer(answer); return answer; } public void vote(String voterId, long postId, VoteType type) { Objects.requireNonNull(type, "type"); User voter = user(voterId); Post post = post(postId); if (post.authorId().equals(voterId)) { throw new ActionNotAllowedException("you cannot vote on your own post"); } if (post.voteBy(voterId).orElse(null) == type) { // A retry of the same vote changes nothing, even if the voter has since lost the privilege. return; } privileges.require(type.requiredPrivilege(), voter.reputation()); ReputationEffect effect = checked(reputation.forVote(post.kind(), type, post.authorId(), voterId)); apply(post.vote(new Vote(voterId, type, effect))); } public void retractVote(String voterId, long postId) { user(voterId); apply(post(postId).retract(voterId)); } public void accept(String askerId, long answerId) { Answer answer = answer(answerId); Question question = question(answer.questionId()); requireAsker(askerId, question); ReputationEffect effect = checked(reputation.forAcceptance(answer.authorId(), askerId)); apply(question.accept(answer, effect)); } public void unaccept(String askerId, long questionId) { Question question = question(questionId); requireAsker(askerId, question); apply(question.unaccept()); } public List<QuestionSummary> search(SearchQuery query) { Collection<Long> ids = query.tags().isEmpty() ? posts.keySet() : tagIndex.questionsWithAll(query.tags()); List<QuestionSummary> found = new ArrayList<>(); for (long id : ids) { if (posts.get(id) instanceof Question question && query.matchesTitle(question.title())) { found.add(question.summary()); } } found.sort(query.order().comparator()); return List.copyOf(found.subList(0, Math.min(query.limit(), found.size()))); } public User user(String userId) { User user = users.get(Objects.requireNonNull(userId, "userId")); if (user == null) { throw new NoSuchElementException("no user " + userId); } return user; } public Post post(long postId) { Post post = posts.get(postId); if (post == null) { throw new NoSuchElementException("no post " + postId); } return post; } public Question question(long questionId) { if (post(questionId) instanceof Question question) { return question; } throw new NoSuchElementException("post " + questionId + " is not a question"); } public Answer answer(long answerId) { if (post(answerId) instanceof Answer answer) { return answer; } throw new NoSuchElementException("post " + answerId + " is not an answer"); } private void requireAsker(String userId, Question question) { user(userId); if (!question.authorId().equals(userId)) { throw new ActionNotAllowedException("only the person who asked can accept an answer"); } } // A policy can be swapped at run time, so what it returns is checked before anything is stored. private ReputationEffect checked(ReputationEffect effect) { Objects.requireNonNull(effect, "effect"); for (ReputationChange change : effect.changes()) { user(change.userId()); } return effect; } // No lock is held here. Each user's reputation is atomic, and additions can land in any order. private void apply(ReputationEffect effect) { for (ReputationChange change : effect.changes()) { user(change.userId()).addReputation(change.points()); } }}demo/Main.java runs one morning on the site. Asha asks a question about counters and threads, and Ben and Chen answer. People vote, some are refused, and Asha accepts one answer and then switches. Then the points table changes, and the demo ends with three searches:
Asha asks Q1 [java, concurrency]. Ben answers A2, Chen answers A3. Dev upvotes A2: refused, upvote needs 15 reputation, you have 1 Ben upvotes A2: refused, you cannot vote on your own post Chen upvotes A2: Ben 200 -> 210 Chen downvotes Q1: refused, downvote needs 125 reputation, you have 101 Ben downvotes A3: Ben 210 -> 209, Chen 101 -> 99 Ben downvotes A3 again: no change Ben changes to an upvote on A3: Ben 209 -> 210, Chen 99 -> 111 Ben and Chen upvote Q1: Asha 1 -> 21 Scores: Q1 2, A2 1, A3 1 Dev accepts A2: refused, only the person who asked can accept an answer Asha accepts A2: Ben 210 -> 225 Asha switches to A3: Ben 225 -> 210, Chen 111 -> 126 The rules change: an answer upvote now gives 15. Chen takes back his upvote on A2: Ben 210 -> 200 Chen upvotes A2 again: Ben 200 -> 215 Search [java] by votes: Q1 score 2 [java, concurrency] How do I stop two threads updating one counter? Q4 score 1 [java, hashmap] Why does a HashMap lose entries under concurrent puts? Search [java] newest first: Q4 score 1 [java, hashmap] Why does a HashMap lose entries under concurrent puts? Q1 score 2 [java, concurrency] How do I stop two threads updating one counter? Search "threads": Q1 score 2 [java, concurrency] How do I stop two threads updating one counter?
Notice three things in the output. Dev, with 1 reputation, was refused an upvote, and Chen, with 101, was refused a downvote, but Chen's own upvote went through. When Ben changed his downvote on A3 to an upvote, he got back the 1 point the downvote cost him and Chen got back 2, plus 10 for the upvote. And after the table changed, Chen's retract took 10 from Ben, the amount the vote gave, while his new upvote gave 15.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Add comments." | A Comment class held by each Post, with its own lock or a concurrent list. Comment upvotes give no reputation. | Vote, ReputationPolicy and acceptance. |
| "Delete a post." | A deleted flag on Post. Deleting reverses every stored vote effect, and the acceptance if it is an answer, then removes it from TagIndex, which gains a remove. | The stored effects, which make the reversal exact. |
| "Cap reputation from votes at 200 a day." | ReputationPolicy.forVote needs the author's points so far today, so its signature changes. User keeps a per-day count, and the stored effect records what the cap allowed. | Undo, which still reverses the stored effect. |
| "Reputation never goes below 1." | User.addReputation cannot simply clamp, because a clamped change would no longer undo exactly. User keeps the true sum and shows the larger of it and 1. | Vote, Post and the policy. |
| "Lock a vote in after 5 minutes." | Vote keeps the time it was cast, from the service's Clock. Post.vote and Post.retract take the current time too, and refuse a change or a retract after 5 minutes. | Reputation and acceptance. |
| "Let the asker edit tags." | Question.tags becomes changeable under the question's lock, and TagIndex gains remove. | Votes and reputation. |
| "Add bounties." | A Bounty record on Question. Starting one takes reputation from the asker, and awarding it is a new effect stored with the bounty. | Vote and the vote path. |
| "Tell Ben when his answer is upvoted." | A listener list on QaService, called after apply, outside every lock. This is where Observer fits. | The vote path itself. |
| "Recalculate everyone under the new table." | A job that walks every stored vote, prices it with the new policy, and replaces the stored effects. | The live vote path. |
In most rows the change lands on one class or adds a record, and Post.vote stays as it is. Two rows change a signature: the daily cap needs more input to the policy, and the 5 minute lock needs the time inside Post.vote and Post.retract.
What the interviewer looks for
Mid-level
A mid-level candidate shows questions and answers with a shared base, one vote per user per post, a refusal of self-votes, and reputation that moves with votes. They say that two votes at once could lose a count and that some locking is needed, even if the lock covers more than it has to.
Senior
A senior candidate shows everything above and gives the reasons. They store the effect with each vote, so undo and change are exact after the table changes. They move the acceptance points on a switch, check privileges at the boundary, lock per post, and keep reputation in an atomic counter.
Staff+
A staff candidate leads the conversation through the trade-offs without being asked. They point out the short gap between a score moving and the reputation following, the cost of rebuilding a total from stored votes, and why a daily cap or a floor of 1 breaks a naive undo. They say how search would move to a separate engine at scale.
Common mistakes
- Undoing a vote with today's rule. After any change to the points table, every undo is off by the difference, for good.
- Votes as a counter only. A plain
int votescannot tell who voted, so it cannot stop a second vote or let anyone take one back. - Making a repeated vote a toggle in the model. A retry after a dropped connection undoes the vote.
- Leaving the 15 points with the first answerer. An asker can hand out points by switching back and forth.
- A plain
intfor reputation, changed under the post's lock. Votes on two different posts by the same author still race. - Sorting search results on live scores. A score that changes mid-sort can make the sort throw.
- Checking only upvote reputation when a vote changes to a downvote. The new vote needs its own privilege.
Summary
- Ask first whether the points table can change. If it can, each vote must remember what it gave.
QuestionandAnswerextend an abstractPost, which holds the votes in a map keyed by voter.- Voting the same way twice changes nothing, and taking a vote back is a separate call.
- A changed or retracted vote reverses its stored effect, and a switched acceptance does the same with the 15 points.
- Privileges come from a table, and taking a vote back needs none.
- Lock each post for its votes, keep reputation in an
AtomicInteger, and apply it after the lock. - Search reads a tag index, then sorts copies of the results so live scores cannot break the sort.