Before writing any code, we define what our poll widget looks like: a self-contained UI component that presents a question with multiple options, allows users to cast a vote, and displays aggregated results.
Front-End System Design for an Embeddable Voting Component
A deep dive into designing, building, and embedding a performant, accessible poll widget — from component hierarchy to real-time updates.
Before writing any code, we define what our poll widget looks like: a self-contained UI component that presents a question with multiple options, allows users to cast a vote, and displays aggregated results.
Let's talk about how we actually structure this thing. When I design a component, I like to think of it like a restaurant menu — you want just enough options to cover everything, but not so many that nobody can decide.
The poll widget follows a flat hierarchy because it does one thing: let people vote. A deeply nested component tree would be overkill here. Each piece has a single job, and they compose together cleanly.
interface PollWidgetProps {
pollId: string;
question: string;
options: PollOption[];
type: "single" | "multiple";
onVote?: (optionId: string) => void;
theme?: "light" | "dark";
readOnly?: boolean;
}renderEditItem and renderViewItem props. These let developers completely swap out the default UI without touching our internals. It's the same pattern React uses withrenderProps — and it makes the component infinitely extensible.The PollOption is where all the action happens. Each option needs to show a label, respond to clicks, and display a percentage bar when results come in. The bar animation uses transform: scaleX()instead of animating width — I'll explain why in the performance section, but the short version is that the GPU handles it, not the CPU.
Here's a rule I've learned the hard way: never store data you can calculate. If you store both the vote count and the percentage, they will get out of sync at some point. It's not a matter of if, but when.
So in our model, we only store the raw votes per option. The percentage? We calculate it on the fly:votes / totalVotes * 100. Simple, impossible to desync, and one less bug to hunt at 2 AM.
interface PollOptionData {
id: string;
label: string;
votes: number;
percentage: number;
}
interface PollData {
id: string;
question: string;
type: "single" | "multiple";
options: PollOptionData[];
totalVotes: number;
userVoteId: string | null;
}With the data model in place, the next step is defining the interfaces — how the client talks to the server, and how components talk to each other. In the RADIO framework, this is theI — and it's where most system design interviews really dig in.
The poll widget uses three HTTP endpoints and one SSE stream. Each has a clear contract — request shape, response shape, and error codes. I document these in an OpenAPI spec so the backend team can implement them independently.
GET /api/polls/{pollId}
→ Response: { id, question, options[], totalVotes }
GET /api/polls/{pollId}/results
→ Response: { options: [{ id, label, votes, percentage }] }
POST /api/polls/{pollId}/vote
→ Body: { optionId: string }
→ Response: { success: true, userVoteId: string }
→ Headers: Idempotency-Key (prevents duplicate votes)
SSE /api/polls/{pollId}/stream
→ Event: "results-update"
→ Data: { options: [{ id, votes, percentage }] }Idempotency-Key header on POST /vote is critical. Without it, a double-click or retry could submit two votes. The server stores the key for 24 hours and returns the cached response for duplicate requests.Within the client, components communicate through typed callbacks. The parentPollWidget passes handlers to children, creating a unidirectional data flow. Every callback is optional — the widget works out of the box without any configuration.
interface PollWidgetCallbacks {
onVote?: (optionId: string) => void;
onVoteConfirm?: (result: VoteResult) => void;
onError?: (error: PollError) => void;
onResultsChange?: (results: PollOptionData[]) => void;
}
interface VoteResult {
optionId: string;
newCount: number;
totalVotes: number;
}
interface PollError {
code: "DUPLICATE" | "NETWORK" | "RATE_LIMIT";
message: string;
}When embedded via iframe, the widget talks to the host page through postMessage. The host listens for "vote-cast" events and can request a resize by sending { type: "resize", height: 400 }. This two-way contract is documented in the widget's developer guide.
This is where things get interesting. Building the widget is the easy part — the real challenge is getting it to work on someone else's website without breaking their carefully crafted styles.
Imagine you're a blogger who wants to add a poll to your article. You paste our code snippet into your HTML, and suddenly all your buttons look wrong because our CSS is leaking everywhere. Not a great experience, right? That's why we need isolation — and we have two solid options.
Iframes are like a sandbox within a sandbox. Your widget lives in its own little world, completely isolated from the host page. Communication happens through postMessage, which is the browser's built-in way for iframes to talk to their parent. It's simple, proven, and works everywhere.
<iframe
src="https://polls.example.com/widget?id=123"
width="480" height="400"
style="border: none;"
title="Poll Widget"
sandbox="allow-scripts allow-same-origin"
/>Web Components are a browser-native way to create custom HTML elements. Combined with Shadow DOM, they give you CSS isolation without the overhead of an iframe. The widget becomes part of the host page's DOM, but its styles are scoped — like a force field around your component.
<script src="https://polls.example.com/widget.js" async></script>
<poll-widget poll-id="123" theme="dark"></poll-widget>When a user clicks "Vote", here's what happens behind the scenes — and I mean immediately behind the scenes, before the server even responds.
Here's a little secret: the vote count in the UI goes up before the server confirms it. This is called an optimistic update, and it's what makes modern apps feel instant. If the server fails, we roll back the count and show an error. But 99% of the time, the vote goes through, and the user never sees a loading spinner.
async function castVote(pollId: string, optionId: string) {
// Optimistic: update local state immediately
localState.options[optionId].votes += 1;
render();
try {
await fetch(`/api/polls/${pollId}/vote`, {
method: "POST",
body: JSON.stringify({ optionId }),
});
} catch {
// Rollback on failure
localState.options[optionId].votes -= 1;
render();
showError("Vote failed");
}
}This comes up in every system design interview, so pay attention. For a poll widget, data only flows one way: from the server to the client (vote counts update). We don't need real-time chat or collaborative editing. So Server-Sent Events (SSE) are perfect — they're simpler, auto-reconnect, and work over regular HTTP. WebSockets would be like using a fire hose to water a houseplant.
Our entire widget is ~4KB gzipped. That's smaller than most JPEG images on the web. How? No framework. No runtime. Just vanilla JavaScript that does exactly what it needs to do.
Vanilla JS isn't always the answer — I wouldn't build a complex SPA without React or Solid. But for a widget that does one thing, it's perfect. Less code means fewer bugs, faster downloads, and better performance.
Here's something most developers don't know: animating width triggers a layout recalculation on every frame. That's expensive. But animating transform: scaleX()? The GPU handles it in a separate compositor layer, completely off the main thread. Same visual result, way better performance.
.bar-fill {
height: 100%;
background: linear-gradient(90deg, #6366f1, #8b5cf6);
border-radius: 3px;
transform-origin: left;
transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
will-change: transform;
}transform and opacity. Everything else (width, height, top, left) triggers layout. Layout triggers paint. Paint triggers the CPU. The CPU is slow. The GPU is fast. Pick the fast path.The widget script never changes between deploys (we version it), so we tell the browser:Cache-Control: public, max-age=31536000, immutable. That's one year. After the first load, the widget launches instantly — no network request needed. The poll data itself uses a shorter cache with stale-while-revalidate, so the user sees yesterday's results immediately while we fetch fresh data in the background.
An embeddable widget is inherently a security boundary — it runs on someone else's website and handles user data. Getting security right is not optional.
The iframe uses sandbox="allow-scripts" — deliberately missingallow-same-origin. If the host page and the widget shared an origin, the widget could read cookies, localStorage, or even modify the host page's DOM. The sandbox attribute prevents all of this.
<iframe
src="https://polls.example.com/widget?id=123"
sandbox="allow-scripts"
csp="default-src 'none'; script-src 'self'"
referrerpolicy="strict-origin-when-cross-origin"
loading="lazy"
/>
window.addEventListener("message", (event) => {
if (event.origin !== "https://polls.example.com") return;
switch (event.data.type) {
case "vote-cast": handleVote(event.data); break;
case "resize": resizeIframe(event.data.height); break;
}
});Every message event listener checks event.originbefore processing data. Without this check, any website could send forged vote messages into our iframe. The origin check narrows the trusted surface to exactly one domain.
Duplicate voting is prevented at three layers: the Idempotency-Key header (server-side dedup), the session cookie (prevents cross-tab re-votes), and an IP-based rate limiter (30 votes per IP per 24 hours). Each layer is a defense in depth — if one fails, the others still hold.
Testing is where design meets reality. The poll widget has three layers of tests, each catching a different class of bugs before they reach production.
The core voting logic is a pure function: it takes current state and an action, returns new state. Pure functions are the easiest thing to test — no mocks, no async, no DOM. I test every state transition (idle → selecting → voted → error) and edge cases like voting with zero options or a maxed-out poll count.
Integration tests verify the full pipeline: user clicks "Vote" → optimistic update fires → POST request is sent → response updates the store → UI re-renders. I use MSW (Mock Service Worker) to intercept network requests and test both the happy path and error scenarios.
describe("PollWidget - vote flow", () => {
it("updates bar width optimistically on vote", () => {
render(<PollWidget {...mockProps} />);
const option = screen.getByLabelText("Option A");
fireEvent.click(option);
expect(screen.getByText("1 vote")).toBeVisible();
});
it("rolls back on network failure", async () => {
server.use(http.post("/api/polls/*/vote", () =>
HttpResponse.json({ error: "Server error" }, { status: 500 })
));
render(<PollWidget {...mockProps} />);
fireEvent.click(screen.getByLabelText("Option A"));
await waitFor(() => expect(
screen.getByText("Vote failed — please retry")
).toBeVisible());
});
it("prevents double-vote via idempotency key", async () => {
const { rerender } = render(<PollWidget readOnly={false} />);
fireEvent.click(screen.getByLabelText("Option A"));
rerender(<PollWidget readOnly={true} />);
expect(screen.queryByRole("radio")).not.toBeInTheDocument();
});
});I run axe-core audits in CI for every commit. The test renders the widget, callsaxe.run(), and fails if any violation is found. I also verify that all radio buttons are reachable via Tab and that the vote button has a descriptivearia-label. Keyboard navigation tests simulate arrow keys and Enter/Space to confirm the full flow works without a mouse.
A poll widget that isn't accessible is a poll widget that excludes people. And that's not okay. Here's what we do about it.
role="radiogroup" on the option list androle="radio" on each option. Screen readers immediately understand this is a voting interface.aria-labelledby. When results update, an aria-live region announces the change.Alright, enough theory. Here's the widget running live in your browser. Go ahead — pick an option, cast your vote, and watch those bars animate. Everything we talked about is running right here.
Keyboard shortcut: press 1 through 5 to select an option, then Enter to vote. Try it without touching your mouse.
If you take away nothing else from this article, remember these six things:
Non-functional requirements determine your architecture. Define them first.
Shadow DOM or iframe — pick one before writing a single line of CSS.
For one-direction data flow, SSE is simpler, cheaper, and easier to scale.
Update before the server responds. Rollback on error. Makes apps feel instant.
The GPU handles these. Width, height, top, left trigger CPU layout.
A 4KB widget loads faster than a 50KB one. Choose the right tool.