Design a Live Polling and Voting App
Enforce one vote per user without locking one counter row on viral spikes, using sharded or buffered counts and SSE live tallies.
In this lesson (4 bite-sized sections)
Two separate jobs: dedup and counting
A live poll or upvote widget feels simple enough for a weekend project until 500,000 viewers vote inside ten seconds during a livestream. The classic intern mistake is collapsing two different workloads into one SQL statement: verifying that a user has not voted yet and incrementing the option's total in the same transaction.
Separating vote deduplication (high cardinality, one row per user) from tally aggregation (low cardinality, four rows per poll) removes the hotspot cleanly.
One vote per user at write time
Record each cast ballot in a ledger table votes(poll_id, user_id, option_id, created_at) with a composite unique constraint on (poll_id, user_id) (sharded by poll_id or (poll_id, user_id) at extreme scale). Because each voter writes a distinct key, inserts spread across index pages instead of hammering one shared row.
If a user double-clicks Submit, the unique constraint rejects the duplicate with a clean conflict error, making the endpoint naturally idempotent. If the product allows changing a vote before the poll closes, run an INSERT ... ON CONFLICT (poll_id, user_id) DO UPDATE and emit both old_option and new_option so downstream counters adjust by -1 and +1. For anonymous polls, layer signed browser tokens, IP rate limits, and bot challenges, and explicitly state to the interviewer that strict one-person-one-vote requires authenticated accounts.
Absorbing viral write spikes
Once the unique ballot is accepted, never increment a single shared SQL row synchronously. Pick between two proven counter strategies based on freshness and infrastructure:
| Strategy | Write Contention | Tally Freshness | Best Fit |
|---|---|---|---|
| Direct SQL UPDATE | Severe (1 hot row lock) | Immediate exact | Small internal polls (< 500 votes/sec) |
| Sharded Redis counters | Low (split K ways) | Sub-second on read sum | Viral polls with instant display |
| Kafka + 1s batch flush | Minimal (1 SQL update/sec) | 1 to 2 second lag | Huge spikes needing durable SQL rollups |
With sharded counters, split each option into K keys in Redis (poll:42:optB:0 through K-1). Each accepted vote runs atomic INCR on a random shard, multiplying write parallelism by K. A background aggregator sums the K shards every second into a single cached snapshot. With buffered stream aggregation, append each newly accepted vote event to Kafka (or Redis Streams); consumers fold increments in memory for 1-2 seconds and issue one batched UPDATE poll_options SET votes = votes + delta per option, turning 100K individual writes into a single row update per second.
Pushing live tallies without polling floods
When 500,000 viewers watch results update live, naive client polling every second creates 500K read QPS on top of the write spike. Because tally updates flow strictly one-way from server to viewer, Server-Sent Events (SSE) over HTTP/2 is lighter and simpler through proxies than full-duplex WebSockets.
Never broadcast on every individual vote. Instead, have the tally aggregator publish one debounced JSON snapshot per poll once per second onto Redis Pub/Sub. Edge fan-out servers hold open SSE connections and push that single 200-byte frame to all subscribed viewers, keeping origin load constant regardless of how fast votes arrive.
Sort each mechanism by whether it belongs on the vote write-dedup path or the live tally fan-out path.
Sort 5 more items to check
Sources: Google Cloud distributed counters · PostgreSQL unique constraints · Redis Pub/Sub overview
from collections import Counter
POLL_ID = "poll-42"
OPTIONS = ("A", "B", "C")
seen_ballots: set[tuple[str, str]] = set()
delta_buffer: Counter[str] = Counter()
sql_tallies: Counter[str] = Counter()
# Simulate 1,000 incoming vote requests (300 are duplicate retries)
incoming = [(POLL_ID, f"user-{i % 700}", OPTIONS[i % 3]) for i in range(1000)]
duplicates = 0
for poll_id, user_id, option in incoming:
key = (poll_id, user_id)
if key in seen_ballots:
duplicates += 1
continue
seen_ballots.add(key)
delta_buffer[option] += 1
# Flush 1 batched counter update per option instead of 1,000 SQL row locks
sql_updates = 0
for option, delta in sorted(delta_buffer.items()):
sql_tallies[option] += delta
sql_updates += 1
print(f"Incoming: {len(incoming)} | Unique: {len(seen_ballots)} | Duplicates dropped: {duplicates}")
print(f"SQL row updates: {sql_updates} (vs {len(incoming)} naive locks) | Tallies: {dict(sql_tallies)}")Apply
Your turn
The task this lesson builds to.
Architect a real-time polling and voting service for a broadcast with 2M concurrent viewers, enforcing one vote per user while pushing live results within 2 seconds.
Think about
- How do you enforce one vote per user without locking one shared counter row?
- How do sharded counters or stream-buffered batches survive 100K votes per second?
- Why is 1-second debounced SSE better than polling or broadcasting every individual vote?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Specify the architecture changes needed when voters can switch their choice before the poll closes and final results must be cryptographically auditable for a shareholder vote.
Think about
- How do you prevent double-counting when a user changes their vote from option A to option B?
- How do you preserve an immutable audit trail while letting users revise their active selection?
- How do you reconcile the live approximate tally with the final certified result?
Draft your design answer here Save your draft, compare against the model answer, and track progress.