Design a Decentralized Large-File Distribution Network
System DesignModel answerLast updated
Design a peer-to-peer file sharing system where downloaders pull chunks directly from other peers, covering content identity, discovery, integrity verification, NAT traversal, and swarm health.
Design a Decentralized Large-File Distribution Network
You are tasked with designing a file distribution system where downloaders retrieve files directly from other users who already have copies, rather than pulling everything from a central file server. The goal is to offload bandwidth from any central infrastructure onto the participants themselves.
Walk the interviewer through your design in three parts. Before diving in, state any assumptions you are making and identify questions you would want answered first.
Assumptions to Confirm
- Peers are regular consumer machines: they appear and disappear without warning, their upload speed is typically much lower than their download speed, and many are behind NAT or corporate firewalls.
- Central components are allowed for coordination and metadata, but raw file data must never pass through them.
- Files can reach several gigabytes, so transfers must support resuming after interruptions and downloading from multiple sources simultaneously.
- Any peer in the network — intentionally or due to bugs — might send corrupted bytes. The system must catch bad data before it becomes part of the final file.
- Content search, user authentication, and billing are out of scope unless the interviewer says otherwise.
Suggested Clarifying Questions
- What scale should the design target — number of concurrent peers, number of shared files, and how skewed the popularity distribution is?
- Is running a coordination service acceptable, or must the system function with zero infrastructure of our own?
- Are files immutable after publication, or can publishers push updates under the same identifier?
- Is every file public to anyone who has its identifier, or is access control needed?
- Which clients matter — desktop only, or also mobile devices with battery and data constraints?
Part 1 — Identifying Content and Finding Peers
Explain how a file gets a canonical identifier, what metadata a downloader needs before the first byte is transferred, and how a peer that wants a file locates others who hold all or part of it. Compare at least two peer discovery approaches and argue for which you would build first.
Your answer should address:
- A content-derived identifier and the minimum metadata required to start downloading
- The trade-offs between a centralized tracker and a fully decentralized lookup
- How peer lists stay accurate as nodes join, leave, and time out
Part 2 — Moving Bytes Efficiently and Correctly
Describe how a downloader actually assembles the file from many peers: how it divides the file into pieces, decides which piece to request and from which peer, verifies each piece without trusting the sender, and picks up where it left off after a crash or restart.
Your answer should address:
- Splitting the file into chunks and tying each chunk to a trusted hash
- Piece selection strategy, including how a brand-new peer with nothing gets started and how the final rare pieces are handled
- Resume behavior: what the client persists to disk and how it recovers after an unexpected shutdown
Part 3 — Keeping the Swarm Healthy at Scale
Explain how the system remains functional given real-world conditions: peers sitting behind NAT, participants who only download and never contribute upload bandwidth, a file that suddenly goes viral, and a file whose last complete holder is about to go offline. Close with what you would instrument and monitor.
Your answer should address:
- How peers behind NAT or firewalls establish connections, and what fallback exists when direct connection fails
- A mechanism that discourages free-riding and ensures upload bandwidth is fairly contributed
- How sudden popularity spikes are absorbed and how availability is maintained as peers churn
- What observability looks like for a system running on machines the operator does not control
Hints
Hint 1
Start with content identity: a hash of the file's bytes gives you an immutable, self-verifying identifier that does not depend on any server staying alive. Think about what metadata a downloader needs before it can ask anyone for a single byte — file size, chunk boundaries, and per-chunk hashes. That bundle of metadata is itself a small file that can be distributed through any channel.
Hint 2
For peer discovery, the core trade-off is operational simplicity (a tracker you run) versus resilience (a DHT that survives your tracker going down). A tracker is far easier to build and debug; a DHT is more robust but introduces its own consistency and routing complexity. Consider starting with a tracker and adding DHT as a fallback rather than treating them as mutually exclusive.
Hint 3
Piece selection is where naive implementations fail at the edges. A sequential downloader leaves rare final chunks concentrated on few peers; a rarity-first strategy spreads them out. Think also about the brand-new peer problem: it has nothing to offer in an upload-for-upload incentive scheme, so it needs a grace period. And think about what 'resuming' actually requires — what must be written to d…
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong answer keeps the data plane fully peer-to-peer and uses any central component only for lightweight coordination. Every design choice should be justified against the constraints: asymmetric bandwidth, untrusted peers, and continuous churn.
Part 1 — Content Identity and Peer Discovery
Content-derived identifier
Hash the complete file with SHA-256 (or a stronger digest if post-quantum concerns matter). That hash becomes the file's permanent identity. It is independent of any server, unforgeable, and doubles as the final integrity check. Distribute it out-of-band — a link, a QR code, anything the downloader trusts.
The metadata bundle (analogous to a .torrent file) contains: the content hash, total file size, chunk size (typically 256 KB–1 MB), and a SHA-256 hash for each chunk. This bundle is small enough to host anywhere and can itself be integrity-checked against a hash of the bundle. The downloader needs this before requesting a single byte.
Discovery: tracker vs. DHT
| Centralized tracker | Distributed Hash Table (DHT) | |
|---|---|---|
| Complexity | Low — one HTTP endpoint | High — routing protocol, bootstrap nodes |
| Resilience | Single point of failure | Survives any single node going down |
| Latency to find peers | Low | Higher; multi-hop lookups |
| Peer list freshness | Controlled by tracker TTL | Depends on DHT churn handling |
I would start with a tracker. Peers announce themselves with {content_hash, ip, port, bytes_held} on join and every 30 minutes. The tracker returns a random sample of 50–200 peers. The tracker only stores IP/port/hash tuples — no file bytes, no routing of user traffic. Estimated load: at 1 M active peers each pinging every 30 min, that is ~550 requests/sec, trivially handled by a small cluster.
Add DHT (Kademlia-style) as a second discovery source once the tracker is stable. Peers maintain routing tables among themselves; no single point of failure. Use the tracker for fresh swarms (faster bootstrap) and DHT as a fallback when the tracker is unreachable.
Peer lists go stale as nodes drop. The downloader should treat any peer list entry as soft-expired after twice the announce interval and evict peers that fail three consecutive connection attempts.
Part 2 — Chunked Transfer, Verification, and Resume
Chunking and hashing
Split the file into fixed-size chunks (512 KB is a reasonable default; last chunk is smaller). Each chunk has a SHA-256 hash stored in the metadata bundle. The downloader verifies every received chunk against its stored hash before writing it. A chunk that fails verification is discarded and re-requested from a different peer — the sender is not trusted.
Piece selection strategy
- Rarest-first: prioritize chunks held by the fewest peers in the swarm. This spreads rare data across more nodes quickly, preventing a situation where the last few chunks are held by one slow peer.
- Random early on: a new downloader with nothing to offer picks random pieces initially to avoid all new peers competing for the same rare chunk.
- Sequential endgame: once all chunks have been requested, send duplicate requests for the remaining unreceived chunks to all peers that have them, then cancel duplicates on first arrival. This eliminates the long tail that slows completion.
Brand-new peer (seeder bootstrap)
A peer with 0% of the file cannot contribute under a strict tit-for-tat scheme. Grant it an "optimistic unchoke" slot: a handful of established peers will upload to it unconditionally on a rotating basis. Once it holds verified chunks it can start reciprocating.
Resume behavior
Persist a bitfield to disk mapping which chunk indices have been verified. On restart, read the bitfield and skip already-verified chunks. Write each verified chunk to its correct offset in a pre-allocated file. This means a restart costs zero re-download of good data. Never update the bitfield until the chunk hash passes verification.
Part 3 — Swarm Health at Scale
NAT traversal
Most consumer peers are behind NAT. Approach in order of preference:
- UPnP / PMP: ask the router to open a port. Works on many home routers; silent failure on corporate networks.
- Hole-punching: two NATed peers each send a packet to the other simultaneously, coordinated by a rendezvous server. Succeeds for cone NATs (the majority).
- TURN relay: when hole-punching fails (symmetric NAT, strict firewall), route the connection through a relay server. This is the only option that works universally but burns relay bandwidth. Reserve it for peers that cannot connect any other way.
Free-rider incentives
Use a tit-for-tat upload policy: a peer preferentially unchokes the peers that have uploaded the most to it recently, measured over a rolling 20-second window. Keep a small number of "optimistic unchoke" slots (2–3) that rotate every 30 seconds to give new or unlucky peers a chance to demonstrate reciprocity. Peers that never contribute stay in low-priority slots and get slow downloads — a natural incentive to share.
Popularity spikes
When a file goes viral, the tracker returns more peers than usual. The chunking model helps naturally: each new downloader immediately becomes a partial seeder, multiplying available bandwidth. The tracker itself is not a bottleneck because it serves only peer lists, not data. If one tracker instance becomes a hot spot, add read replicas behind a load balancer — the data is ephemeral and cheap to replicate.
Availability under churn
A file disappears if no peer holds a complete copy. Mitigations:
- Track "swarm completeness" at the tracker (fraction of chunks covered by at least N peers). Alert when completeness falls below a threshold.
- Dedicated seed nodes operated by the publisher or by the platform ensure at least one complete copy persists.
- Encourage long-lived peers (those with high uptime) to prioritize rare chunks, similar to a DHT replication factor.
Observability
Because the operator does not control client machines, direct metrics are limited. Instrument:
- Tracker: announce rate, unique swarm sizes, peer churn rate per swarm
- Relay (TURN) servers: connection count and bandwidth consumed (high relay usage signals NAT problems)
- A small fleet of passive "canary" downloaders that periodically download a known file and report chunk-acquisition time, failure rate, and total download speed
- Completion rates reported voluntarily by clients on finish (sampled, opt-in)
The canary fleet is the most reliable signal: it measures actual user-observable performance from outside the infrastructure.
Common Mistakes
- Routing file bytes through the tracker or a relay by default — this defeats the purpose and creates a cost and scaling problem.
- Skipping per-chunk verification and only checking the full file hash at the end — a corrupted chunk requires re-downloading the entire file.
- Ignoring the endgame problem — downloads that stall at 98% because one slow peer holds the last two chunks are a real user-experience failure.
- Designing incentives only for large swarms — a file with three peers and no free-rider pressure still needs the tit-for-tat logic to function correctly when the swarm eventually grows.