Design a Voting Widget – Frontend System Design

We’ll walk through the frontend system design for an embeddable poll widget. Our goal is a question with 2–8 options, one vote per user (or per browser if they are anonymous), results as percentages after voting, and optional live tallies as other people vote. This is a widget interview, not a social network. The hard parts are isolation from the host page, an idempotent vote, and optimistic UI that can roll back.
You’ll see the host snippet, the Shadow DOM versus framed-embed trade-off, the vote API, and how we keep a thousand embeds from polling every second. We’ll stay at widget scale: one poll per embed, a small tally payload, and a uniqueness constraint the client does not get to enforce alone.
Problem Statement
Design a poll widget that can be embedded on any website.
Requirements:
- A question with 2–8 options
- One vote per user (or per browser if they are anonymous)
- Results as percentages after voting
- Optional live updates as others vote
Describe the embed, the vote API, and optimistic UI.
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Logged-in only, or anonymous? | Both. Logged-in is authoritative; anonymous uses a browser token. |
| 2 | Multiple questions? | One poll per embed. |
| 3 | Can the host change votes after publish? | No. They can close the poll. |
Two more worth asking: can a voter change their option after voting (no — they can only see results), and do we need to hide results until the voter has voted (yes, unless the host sets a “show results” flag). Those two change the first paint.
Requirements
Functional Requirements
- Host drops a snippet; the widget mounts into that node and loads one poll
- 2–8 options as a radio group before vote; percentage bars after
- One vote per logged-in user, or per anonymous browser token
- Optimistic increment on click, rollback on 409 (already voted) or 423 (closed)
- Host can close the poll; they cannot edit options after publish
- Optional live tally while the tab is visible
Non-Functional Requirements
- Host CSS must not restyle the widget; widget CSS must not leak out
- Vote is idempotent. Double-click and retry do not double-count
- Do not poll the tally from every embed on a timer
- Pause live updates when the host tab is hidden
- Accessible before and after the vote; announce “Vote recorded”
Scalability Estimates
A popular embed is busy. It is still a widget. Design for one poll, not a feed.
| Metric | Estimate | Calculation | Notes |
|---|---|---|---|
| Host page views | 100,000 / day | Busy article or docs site | Each view mounts one widget and does one GET. |
| Votes / poll / day | 10,000 | 10% of views vote | One POST each. Idempotent on user or token. |
| Options | 2–8 | Product cap | Radio group. Bars after vote. |
| Tally payload | ~200 bytes | ids + counts + total | Never send the voter list to the embed. |
| Live viewers on one poll | 500 | Concurrent open pages | SSE or a small socket. Pause when hidden. |
| Naive 1s poll | 1,000 req/s | 1,000 open embeds × 1 Hz | This is why we do not poll. Use a push channel. |
Architecture
Two pieces:
- Host snippet:
<div data-poll="p_123"></div>+ a tiny loader script. - Widget: a React (or vanilla) app that mounts into that div, talks to your API, and never leaks CSS into the host. Shadow DOM or an iframe keeps styles isolated. An iframe is the safer embed; Shadow DOM is nicer to resize.
<PollWidget>
<Question />
<Options /> // radio group before vote
<Results /> // bars after vote
</PollWidget>
Say the trade-off out loud. A framed embed gives you a separate document: host CSS cannot reach you, you can set a strict CSP, and cookies for the anonymous token stay on your origin. The cost is height. The host needs a postMessage when the widget switches from options to results so the frame can grow. Shadow DOM shares the page, resizes for free, and is easier to theme, but a host * { font: inherit } can still leak through some inherited properties and you must be careful with the token cookie’s SameSite story.
Default we pick: Shadow DOM for first-party hosts (your own blog, your docs), framed embed for third-party publishers. Same React tree, different mount. The Network Manager does not change.
Component Structure and Responsibilities
- Loader: The snippet’s only job. Finds
[data-poll], fetches the widget bundle once (dedupe if the host has three polls), and mounts. It does not vote. - PollWidget: Root. Reads the poll id, asks the Network Manager for
GET /api/polls/:id, and switches between Options and Results frommyVoteandclosed. - Question: The poll title. It is the accessible name of the radio group.
- Options: Radio group before vote. One tab stop, arrows move, Space/Enter votes the focused option (or a separate Vote button if you want an explicit confirm — say which you picked).
- Results: A list of bars. Each bar has
aria-valuenow,aria-valuemin={0},aria-valuemax={100}. Percentages are derived, not stored. - LiveRegion: A visually hidden polite live region. On success it says “Vote recorded.” On rollback it says “Already voted” or “This poll is closed.”
- Network Manager: GET poll, POST vote with an Idempotency-Key, open the live channel, abort it when the tab hides or the node unmounts.
Network Layer and Data Management
The Network Manager is the only module that knows URLs. The widget is a view over a Poll object.
- First paint: GET the poll. The response includes
myVoteso a returning voter goes straight to Results. - Anonymous token: the GET Set-Cookies an httpOnly token if one is missing. Do not mint it in JavaScript.
- Vote: POST the option id plus an Idempotency-Key (uuid from memory, reused on retry). The server keys uniqueness on userId or the token, not on the key alone.
- Live: subscribe after first paint if the poll is open and the tab is visible. Apply
tallyevents to counts. Ignore events older than the last applied total if you can (a monotonicversionfield).
Vote Workflow
- Loader mounts the widget. GET returns the poll and, for anonymous users, sets the token cookie.
- If
myVoteis set orclosedis true, render Results. Otherwise render the radio group. - The user picks an option. The View Model snapshots the current counts, increments that option and
total, setsmyVote, and swaps to Results immediately. - Network Manager POSTs. On 2xx, keep the optimistic tally (or replace it with the server’s counts).
- On 409, restore the snapshot if needed and keep Results with the server’s
myVote. On 423, mark closed and restore if the increment was wrong. - If live is on, subsequent
tallyevents update bars. The user’s option stays highlighted. - If the host tab goes to
document.visibilityState === "hidden", close the live channel. Reopen on visible with a fresh GET so you do not replay a gap from a dropped socket.
API
export type Poll = {
id: string;
question: string;
options: { id: string; label: string; votes: number }[];
total: number;
closed: boolean;
myVote: string | null;
};
// GET /api/polls/:id
// POST /api/polls/:id/votes { optionId } // Idempotency-Key header
// WS /api/polls/:id/live { type: "tally", options, total }
Vote is optimistic: increment the bar immediately, roll back on 409 (already voted) or 423 (closed). The idempotency key plus a server-side unique (userId or anonymous token cookie) prevents double counts.
Anonymous token: httpOnly cookie set on first GET. Don’t use localStorage as the only guard — it’s trivial to clear.
Those two sentences are the interview. Everything else is how you consume them without flashing the wrong bar.
State and Data Flow
The widget has one document worth of state. Keep the optimistic snapshot next to it so rollback is a replace, not a guess.
- Mount → Network Manager GET → store
Poll. - User selects an option → View Model writes an optimistic
Polland keepsprev. - POST vote. Success replaces counts with the server’s if they came back; failure restores
prevand sets an error reason. - Live events patch
optionsandtotalonly. They do not clearmyVote. - Close event (or a 423) sets
closedand disables the radio group if we have not swapped yet.
Do not store percentages. Derive them at render time from votes / total. Store integers. You will need a rounding pass so the bars add to 100 — largest-remainder is enough; say it, do not invent a stats library.
Data Model
The GET shape is almost the whole model. Add a local layer for optimism and live.
type PollOption = {
id: string;
label: string;
votes: number;
};
type Poll = {
id: string;
question: string;
options: PollOption[];
total: number;
closed: boolean;
myVote: string | null;
showResultsBeforeVote: boolean;
version: number; // monotonic; live events carry this
};
type VoteRequest = {
optionId: string;
};
type TallyEvent = {
type: "tally";
version: number;
options: { id: string; votes: number }[];
total: number;
};
type WidgetState = {
poll: Poll | null;
snapshot: Poll | null; // taken just before an optimistic vote
phase: "loading" | "ready" | "voting" | "error";
live: "off" | "on" | "paused";
error: "already_voted" | "closed" | "network" | null;
};
version lets you drop a stale live event that arrived after a newer GET. snapshot is how rollback stays honest — you do not decrement a bar you incremented if a live event already moved the totals.
API Design
Three endpoints. That is the whole surface. If you add a “create poll” route in this interview you are designing the host admin, not the widget.
| Action | Method / Endpoint | Description |
|---|---|---|
| Load poll | GET /api/polls/:id | Returns Poll, including myVote. May Set-Cookie an anonymous token. |
| Cast vote | POST /api/polls/:id/votes | Body { optionId }. Headers: Idempotency-Key, credentials include. 200, 409, or 423. |
| Live tally | GET /api/polls/:id/live (SSE) | Events: tally with { version, options, total }. SSE preferred; WS is fine. |
| Close (host) | POST /api/polls/:id/close | Publisher only. Widget only reads closed. |
Example: Optimistic Vote on the Frontend
async function castVote(pollId: string, optionId: string, key: string): Promise<Poll> {
const res = await fetch(`/api/polls/${pollId}/votes`, {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify({ optionId }),
});
if (res.status === 409) throw Object.assign(new Error("already_voted"), { status: 409 });
if (res.status === 423) throw Object.assign(new Error("closed"), { status: 423 });
if (!res.ok) throw Object.assign(new Error("network"), { status: res.status });
return res.json();
}
function vote(optionId: string) {
const prev = snapshot(poll);
applyOptimistic(optionId);
announce("Vote recorded");
const key = idempotencyKey ?? (idempotencyKey = crypto.randomUUID());
castVote(poll.id, optionId, key).then((serverPoll) => {
replacePoll(serverPoll);
}).catch((err) => {
restore(prev);
if (err.status === 409) announce("Already voted");
if (err.status === 423) announce("This poll is closed");
if (err.status !== 409 && err.status !== 423) announce("Could not record vote");
});
}
Reuse the same Idempotency-Key on retry. A new key plus a flaky network is how you accidentally double-count if the server’s unique constraint is weaker than you hoped. The unique constraint is still userId or token; the key is for retries of the same click.
Live Results
SSE or a small WebSocket is enough. Don’t poll every second from a thousand embeds. If the host page is in the background, pause the socket.
SSE fits this payload: the server already has the tally, it can fan out a 200-byte event, and the widget only needs a one-way stream. EventSource retries on its own. When you pause, eventSource.close() and on resume do a GET (authoritative) before opening a new stream so a missed increment does not leave you one vote behind forever.
Apply events in order. If version is less than or equal to the last applied, drop it. If a GET comes back while a stream is open, the GET wins and you reset the last version. Optimistic local increments should be marked so a live event that does not yet include your vote does not shrink your bar — either ignore tallies until the POST returns, or send the voter’s option id on the event and skip decrementing that option.
Building the bars

Each bar is a percentage of the track width. Because the widget lives in its own iframe, a width change reflows only the widget document, never the host page, so a plain width transition is the simple and correct default.
function barStyle(count: number, total: number): React.CSSProperties {
const percent = total === 0 ? 0 : (count / total) * 100;
return { width: `${percent}%`, transition: "width 180ms ease-out" };
}
width: 40% adapts when the frame resizes and never distorts the label. The track has a reserved height, and the label and percentage sit on top of the bar as siblings. Reduced motion: set the width with no transition.
If they push on animation cost, transform: scaleX() is the compositor-only alternative. It only works when the label is outside the scaled node, because scaling the node that holds text squashes the text. For a handful of options in an isolated frame, the layout cost of width is negligible, so do not start there.
On vote, optimistically bump counts[optionId] and total, then let the POST confirm. The bar eases to the new percent. If the POST fails, restore the previous counts and announce “Vote failed, try again” in a live region. Do not disable the whole widget while the request is in flight — disable only the option that was clicked, or allow a change-vote if the product says so.
A canvas is unnecessary here. A handful of options is a DOM problem. If they ask you to chart a thousand options, that is a different widget (virtualize the list, do not animate 1,000 bars at 60fps).
Optimizations
The widget is small. The optimizations that matter are isolation cost, one bundle per host page, and not opening a live channel you will not look at.
Pause live updates when the tab is hidden
function usePollLive(pollId: string, enabled: boolean, onTally: (event: TallyEvent) => void) {
useEffect(() => {
if (!enabled) return;
let source: EventSource | null = null;
const open = () => {
source = new EventSource(`/api/polls/${pollId}/live`);
source.onmessage = (message) => {
const event = JSON.parse(message.data) as TallyEvent;
if (event.type === "tally") onTally(event);
};
};
const onVisibility = () => {
if (document.visibilityState === "hidden") {
source?.close();
source = null;
} else {
open();
}
};
if (document.visibilityState === "visible") open();
document.addEventListener("visibilitychange", onVisibility);
return () => {
document.removeEventListener("visibilitychange", onVisibility);
source?.close();
};
}, [pollId, enabled, onTally]);
}
On visible again, prefer a GET-then-subscribe if the poll is busy. The snippet above is the pause; the GET is the catch-up. Mention both.
Accessibility and Security
- Options are a
radiogroupbefore vote; after vote, results are a list witharia-valuenowon each bar - Announce “Vote recorded” via
aria-live - CORS allowlist for embed origins; CSP on the iframe
- Rate-limit votes per token
The radio group is named by the question. Each radio’s label is the option text, not “Option 2.” After the vote, do not leave a selected radio in the tree — swap to the results list so the next Tab lands on the first bar or a “View source” link, not a dead control.
Bars need a text equivalent. aria-valuenow={42} is not enough if the visible label is only a colored span. Include the option name and the percentage in the accessible name: “Cats, 42 percent.”
Security is the embed. CORS allowlist the publisher origins that may GET and POST. The framed embed gets a strict CSP: no unexpected frames, no inline eval. The anonymous token is httpOnly, Secure, SameSite=None if the widget is on a third-party host (and then you need the framed embed so the cookie is first-party to you). Do not put the token in localStorage as the only guard — the user can clear it and vote again, and any script on the host can read it if you are in Shadow DOM on their page.
Rate-limit by token and by IP. A 429 on the POST rolls back like a network error and tells the live region “Try again in a moment.” Closing the poll is a publisher action; the widget only reads closed.
Handling User Edge Cases
| Case | Strategy |
|---|---|
| ❌ Double-click Vote | Same Idempotency-Key. Button disabled while phase === "voting". Server unique on token still wins. |
| ❌ Cleared localStorage | Irrelevant if the guard is the httpOnly cookie. If they clear cookies, they can vote again — say that limit out loud. |
| 🔄 Reload after vote | GET returns myVote. First paint is Results. No flash of the radio group. |
| 🔁 Retry after a 500 | Reuse the key. If the first POST actually landed, the retry is a no-op and returns the existing vote. |
| 📶 Live gap after a background tab | Close the stream on hidden. GET on visible, then subscribe. Do not fast-forward from a stale event buffer. |
| ⏳ Poll closed mid-click | 423 restores the snapshot, sets closed, shows Results without the user’s increment if the server rejected it. |
| 🚫 Host CSS bleed | Shadow DOM + inherited-property reset, or a framed embed with a height message. |
Pro-Level Optimizations
| Area | Suggestion |
|---|---|
| Bundle | One loader per host page, even if three polls mount. Split the widget chunk; keep the snippet tiny. |
| Percent rounding | Largest remainder so bars sum to 100. Do the math on integers, not toFixed on each row independently. |
| Bar motion | Transition width only. Skip if prefers-reduced-motion. Do not animate on the first Results paint after a reload. |
| Live backpressure | Server batches tallies (every 250ms) per poll. Clients do not need every single vote as its own event. |
| Catch-up | Hidden → visible does GET + subscribe. A versioned event log is optional; do not design Kafka for a widget. |
| Resize | Framed embed posts { type: "resize", height } to the host. Shadow DOM does not need this. |
Interview details people skip
Our contract is single-choice, one vote, results after submit. GFE’s is multi-select with immediate vote / unvote and no Submit button. Ask that first. Radio group vs checkbox group is the whole a11y model. totalVotes is respondents. In multi-select, option counts can sum to more than that, so percentages can exceed 100%. Never divide by zero on an empty poll.
Iframe is the third-party default. Shadow DOM isolates CSS reasonably and resizes for free, but it still runs in the host’s JavaScript world — polyfills and monkeypatches land on your code. An iframe is a separate document: host CSS cannot reach you, host JS cannot reach you, and cookies for the anonymous token stay on your origin. Facebook / YouTube ship both a copy-paste <iframe src="https://poll.example/embed/{id}"> and a small SDK that injects one. Give publishers both. Same-origin API under that embed host so you do not invent CORS for the common path.
The embed has a title, no obsolete frameborder, and loading="lazy" when it is below the fold. A fixed height clips long labels and translations. If you grow it, the frame posts { type: "resize", height } and the host checks origin, source window, and shape before applying. Keep overflow scroll as the fallback.
Return tabulated counts, not the vote log. The GET payload is question, options, counts, userVotedForOption, totalVotes, and a lastUpdated version. Redis (or similar) holds the public tally. Overlay the viewer’s private selection at request time. Do not cache a rendered page that includes someone else’s checkmarks. Do not send a raw list of votes — it does not scale, it leaks timestamps, and two clients will tally it differently.
An anonymous cookie is UX, not integrity. Third-party frames get partitioned or blocked cookies, so restoring “you voted React” is best-effort. Do not reuse that id across publisher sites. Rate limits and auth are the stuffing defense.
Hide results until a vote succeeds. Offer “See responses” if they want a peek. On the first vote, flip the selected state immediately and keep bars hidden until 2xx — a failed first vote must not flash tallies and then rip them away. Later changes can move bars optimistically and reconcile. Tag each in-flight request per option with a sequence number and ignore a stale unvote that arrives after a newer vote. The Idempotency-Key dedupes retries of one mutation; sequence numbers order distinct mutations.
Bars are a percentage of widget width (100% of respondents), the Reddit / X model — not “winner is full width.” Inline width: 40% adapts to resize. scaleX(0.4) on a bar that contains its label squishes the text, which is why the label stays a sibling. Server-render the unvoted shell (question + options, no counts). Locale for widget chrome (“Vote recorded”) comes from a ?lang= on the iframe URL; do not translate the creator’s question.
Conclusion: How to Design a Voting Widget
A poll is a tiny CRUD widget with a hard uniqueness constraint. Isolate the embed, make the vote idempotent, and never trust the client for the tally.
We’ll have walked the pieces that score in this interview: a two-part embed (snippet plus widget), a deliberate Shadow DOM versus framed-embed choice, a Network Manager that GETs once and POSTs with an Idempotency-Key, and an optimistic increment that rolls back on 409 and 423. Live updates are a paused SSE stream, not a one-second poll from every copy of the snippet.
The uniqueness constraint is the product. Logged-in users are authoritative. Anonymous users get an httpOnly cookie on first GET — localStorage is not a vote guard. If you remember one line for the debrief, remember that: the client can look instant, but only the server decides whether the vote counts.
