Design a Real-Time Click Counter and a Cross-Device File Sync Service
System DesignModel answerLast updated
Design two systems: a high-throughput ad click aggregator with idempotent deduplication, and a Dropbox-style file sync service with delta uploads and conflict resolution.
Overview
You are asked to design two independent but related distributed systems. Spend roughly equal time on each. For both, walk through API design, data modeling, architecture, and key trade-offs.
Part 1: Real-Time Click Counter
Build a backend system that records ad clicks and serves per-ad click counts aggregated by minute, at high throughput.
Each click event carries four fields: a unique click identifier, the ad identifier, the user identifier, and an event timestamp.
Requirements
- Aggregate counts must be available within roughly one minute of the click occurring.
- The system must deduplicate retries: if a client sends the same click twice due to a network retry, it must be counted only once.
- Events may arrive slightly out of order (up to a few minutes late) due to network jitter. Late events should still be counted correctly.
- The aggregates must be accurate enough for billing purposes.
Scale target: sustain at least 100,000 clicks per second, with the ability to absorb short peaks around 3× that.
Part 2: Cross-Device File Sync Service
Build a service that lets users store files in the cloud and keep them in sync across all their devices, similar to Dropbox.
Requirements
- Support uploading new files, downloading files, and propagating edits made on one device to all others.
- When two devices edit the same file at the same time, the system must detect the conflict and offer a resolution strategy rather than silently overwriting data.
- Keep a version history so users can restore a previous state.
- For large files, avoid re-uploading the entire file when only a small portion changes (delta sync).
Scale target: 10 million active users, approximately 3 devices each, average storage around 5 GB per user.
What Your Answer Should Cover
- API design — the key endpoints for both systems, including request and response shapes.
- Data model — schema choices suited to high-frequency writes (clicks) versus durable, versioned storage (files).
- Architecture — the core components, how they communicate, and which storage technologies you would use and why.
- Trade-offs — for the click aggregator, discuss consistency versus availability; for the sync service, discuss latency versus bandwidth efficiency and your conflict resolution strategy.
You are not expected to produce a fully production-ready spec. Focus on the most interesting design decisions and be explicit about where you are making trade-offs.
Hints
Hint 1
For the click aggregator, think about where deduplication should live (stream processor state vs. an external store like Redis) and what the cost of each approach is in memory and latency. Also consider what happens to clicks that arrive after your dedup window closes — how does a batch reconciliation job save you?
Hint 2
For the file sync service, content-addressable block storage (keying blocks by their SHA-256 hash) is the key insight that unlocks deduplication, immutable storage, and cheap delta uploads all at once. Walk through the upload flow step by step: chunk → hash → check which blocks the server already has → upload only the diff → commit metadata.
Hint 3
On conflict resolution: the classic approach is optimistic concurrency — the commit carries the parent revision the client based its edit on, and the server rejects the commit with a 409 if someone else has already advanced that revision. The client then has enough information to merge or surface a conflict copy. Be ready to explain why last-write-wins is dangerous for billing or document edits.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
These two designs test opposite instincts. The click aggregator is a streaming throughput problem where correctness under retries and disorder is the hard part. The file sync service is a durable-storage problem where efficient deltas and conflict semantics dominate. A strong answer spends a few minutes on requirements and back-of-envelope numbers for each, then goes deep on the one or two genuinely hard pieces in each half.
Part 1: Real-Time Click Counter
Numbers First
- 100k clicks/s average, ~300k/s peak.
- At roughly 200 bytes per event: ~20 MB/s ingest, ~1.7 TB/day of raw data.
- For aggregates: if 1M ads are active, 1M × 1,440 minutes/day = ~1.4B rows/day at maximum density. In practice the matrix is sparse, so far fewer rows.
API
# Click recording (called when a user clicks an ad)
GET /click?ad_id=X&click_id=Y → 302 redirect to advertiser URL; click event emitted async
# Internal ingest (from click service to processing pipeline)
POST /v1/clicks
body: { click_id, ad_id, user_id, timestamp }
→ 202 Accepted
# Query aggregates
GET /v1/ads/{ad_id}/clicks?from=&to=&granularity=minute
→ [{ window_start, count }]
Generate click_id server-side when the ad is rendered and sign it so clients cannot forge or replay it. The same signed ID must survive retries.
Data Model
- Raw event (Kafka + object storage):
click_id, ad_id, user_id, event_ts, ingest_ts. - Aggregate row (OLAP store — ClickHouse, Apache Pinot, or Druid): primary key
(ad_id, window_start), columnscountandlast_updated. Writes are upserts keyed by the window, so replays are naturally idempotent. - Dedup state: a set of
click_idvalues with a TTL slightly longer than the maximum tolerated lateness.
Architecture
- Click service — stateless, behind a load balancer. Validates the event, writes to Kafka, returns immediately.
- Kafka topic — partitioned by
ad_idso each ad's events land on one consumer and can be aggregated without cross-partition coordination. Use replication factor 3 andacks=all. Hot ads skew partitions; handle them by salting the key (ad_id#0..N) and merging shards downstream. - Stream processor (Flink) — three stages:
- Key by
click_id, drop duplicates using keyed state with a 10-minute TTL. (60M IDs × ~40 bytes ≈ 2.4 GB distributed across workers — cheap.) - Re-key by
ad_id, aggregate in event-time 1-minute tumbling windows. - Advance windows with watermarks (max observed event time minus 30 s), allow lateness up to 2 minutes; events later than that go to a side output.
- Key by
- OLAP sink — upserts from Flink. Each arriving late-but-within-window event simply revises the stored count.
- Nightly reconciliation job — re-reads the raw S3 archive and recomputes exact counts. The batch result is the source of truth for billing. The streaming path gives fast approximate visibility; the batch path gives correctness.
Key Trade-offs
Idempotency options:
- Flink keyed state (preferred): no extra network hop, state is checkpointed, TTL prevents unbounded growth.
- Redis
SET NX EX: simpler to operate, but adds latency and a dependency. Use it if Flink is not already in the stack. - Bloom filter as a pre-filter: saves memory, but false positives silently drop real clicks. Only acceptable as a first layer in front of an exact store.
Consistency vs. availability:
- Ingest is AP — accept the click even during partial failures. Kafka durability ensures eventual counting.
- Real-time dashboards tolerate eventual consistency of seconds to minutes.
- Billing reads the reconciled batch output, not the streaming view. This lambda-style split — fast approximate + slow exact — is the right answer for accuracy-critical revenue data.
Part 2: Cross-Device File Sync Service
Numbers First
- 10M users × 3 devices = 30M connected clients.
- 10M × 5 GB = ~50 PB raw storage; content-addressed block dedup meaningfully reduces this.
- The workload is read-heavy for metadata. Most edits touch a small portion of a large file, which is the motivation for chunking and delta sync.
API
# Block layer
POST /v1/blocks/check { hashes[] } → { missing[] }
PUT /v1/blocks/{sha256} → 201
GET /v1/blocks/{sha256} → signed URL (CDN or S3 direct)
# Metadata / commit layer
POST /v1/files/commit { namespace_id, path, parent_rev, block_hashes[], size, mtime }
→ 200 { rev }
| 409 { conflict, current_rev }
| 412 { missing_blocks }
# Change feed (for sync)
GET /v1/changes?namespace_id=&cursor=&limit= → { entries[], cursor, has_more }
GET /v1/changes/longpoll?cursor= → { changed: bool }
# Versioning
GET /v1/files/{file_id}/revisions
POST /v1/files/{file_id}/restore { rev }
Data Model
Metadata DB (sharded relational — Spanner or sharded MySQL, sharded by namespace_id):
files(file_id, namespace_id, path, latest_rev, is_deleted)
revisions(file_id, rev, parent_rev, block_list[], size, author_device, created_at)
journal(namespace_id, seq, file_id, rev, op) -- append-only change log
The journal table is the backbone of sync. Clients store a cursor into it; polling /changes returns everything since their cursor.
Block store: S3-compatible object storage keyed by SHA-256 (content-addressed). Blocks are immutable — this gives dedup across files and users for free and makes the block store trivially cacheable at a CDN. GC runs as a periodic mark-and-sweep or via reference counting.
Architecture
- Client — local file watcher splits files into ~4 MB chunks, hashes each, maintains a local SQLite DB of last-synced state and server cursor.
- Block service — issues signed upload/download URLs so bulk bytes bypass app servers and go directly to object storage or CDN.
- Metadata service — handles commits and journal writes with strong consistency per namespace (serializable transactions).
- Notification service — holds long-poll or WebSocket connections; pushes a wake-up when the namespace journal advances. Clients then pull
/changesthemselves.
Upload flow:
- Client chunks the file and hashes each chunk locally.
- Calls
/blocks/checkwith all hashes — server returns only the ones it does not have. - Uploads only the missing blocks (the delta).
- Calls
/files/commitwithparent_rev= the revision the edit is based on. - If the server returns 409, someone else advanced the revision first — the client fetches the current version, merges or creates a conflict copy, and retries.
Conflict Resolution
Use optimistic concurrency. The parent_rev in the commit is the client's assertion about the base state. If latest_rev != parent_rev, the server rejects with 409. The client then:
- For text files: attempt a three-way merge using the common ancestor revision.
- On failure (or for binary files): keep both versions as distinct files (e.g.,
report (John's conflicted copy).docx).
Last-write-wins is tempting but dangerous — it silently discards work. Conflict copies are annoying but safe.
Key Trade-offs
- Delta sync vs. simplicity: chunking adds client complexity but cuts bandwidth dramatically for large files with small edits. Worth it at this scale.
- Block size: smaller chunks mean finer deltas but more metadata overhead and more round trips. ~4 MB is a common sweet spot.
- Latency vs. consistency: the commit path is strongly consistent (prevents silent data loss). The change feed can be eventually consistent — a client that polls slightly stale data will catch up on the next poll without harm.
- Storage cost vs. version retention: keeping every block version forever is expensive. A practical policy is full history for 30–180 days and only the latest version after that, with user-configurable retention for paid tiers.
Common Mistakes to Avoid
- Using a single large file blob instead of content-addressed blocks — you lose dedup, delta sync, and CDN caching all at once.
- Deduplicating only on the client — a malicious or buggy client can replay clicks or corrupt file state. Server-side validation is non-negotiable.
- Skipping the reconciliation batch job for the click aggregator — streaming windows are fast but not exact; billing systems need the batch truth.