Peer-to-peer file distribution
Cutting a large file into hashed pieces so each receiver also uploads what it holds. The source sends about one copy, time grows little with receiver count when receivers upload too, and each piece is checked on arrival.
What it is
Peer-to-peer file distribution turns receivers into senders: a host that has part of a file serves that part to other hosts while it keeps downloading the rest, so the original source isn't the one link all the bytes go through. BitTorrent is the design this page follows. A small metadata file describes the content: its length, a fixed piece size, and a SHA-1 hash for each piece, with the file split into equal pieces except possibly a shorter last one; 256 KiB is the most common piece size. A tracker helps hosts find each other, and the rest happens between peers over connections that carry data in both directions.
The lower bound, by counting bytes. Take a file of F bits, N receivers, a source with upload rate u_s, and receiver i with upload u_i and download d_i, and suppose each host's own link is the limit rather than the network between them. With client-server delivery the source pushes N copies, so the time is at least N·F/u_s, and no receiver finishes before F/d_min, where d_min is the slowest download link. With peers helping, three limits remain: the source still has to send each byte out at least once (F/u_s), the slowest receiver still needs F/d_min, and N·F bits in total have to be uploaded by someone, which can't go faster than the sum of all upload rates. The first two don't shrink as N grows; the third barely moves when each new receiver brings its own upload link.
Client-server: D_cs >= max( N*F / u_s , F / d_min )
Peer-to-peer: D_p2p >= max( F / u_s , F / d_min , N*F / (u_s + u_1 + ... + u_N) )
F = file size in bits N = number of receivers
u_s = source upload u_i, d_i = receiver i's upload and download
Example with made-up numbers: F = 10 GB = 80 Gb, N = 200,
source and each host 1 Gbps up and down.
Client-server: 200 * 80 Gb / 1 Gbps = 16,000 s, about 4.4 hours
Peer-to-peer: max( 80 s, 80 s, 16,000 / 201 s = 79.6 s ) = 80 s
The source's single copy (F / u_s) is the floor; more receivers don't stretch it.Finding peers. With a tracker, a host sends an HTTP GET carrying the info hash (the hash of the metadata's info section), its own peer id, its listening port, and how many bytes it has uploaded, downloaded and still needs; the tracker answers with a list of peers and an interval in seconds to wait before asking again. A host may ask earlier when an event happens or it needs more peers. In a trackerless setup, the DHT described in BEP 5 is a Kademlia network over UDP: node ids and info hashes share one 160-bit space, distance is XOR, and a host asks the nodes closest to the info hash for peers (get_peers), walking closer each round until no closer node turns up, then announces itself (announce_peer) to the closest nodes with a token they handed it, so a node can't register someone else's address.
Learning what peers hold. Peer connections are symmetrical and run over TCP or uTP. A bitfield, one bit per piece the sender holds, is sent as the first message if at all (a host with no pieces yet may skip it); after that, each time a peer completes a piece and its hash matches, it sends have with the piece index to all its peers. Each side of a connection tracks two bits: choked or not, and interested or not. Data moves when one side is interested and the other has unchoked it. Transfers are in blocks: a request names a piece index, an offset and a length, and current clients use 16 KiB blocks and drop connections that ask for more. A downloader keeps several requests queued per peer so the connection doesn't sit idle between blocks, and requests that can't be written out yet are held in memory so they can be discarded if that peer chokes it.
Choosing what to ask for. The original spec has downloaders fetch pieces in random order so that no host ends up holding a strict subset or superset of a neighbor's pieces. Clients such as libtorrent refine that into rarest first: pick the piece the fewest of your peers hold, random among pieces of equal rarity, so that copies of each piece spread evenly through the swarm; an even spread gives peers more to trade and makes the swarm more tolerant of peers leaving. Among pieces of equal rarity the picker prefers one that already has blocks requested, since a half-finished piece can't be uploaded until it completes. At the end, when all pieces are either done or already requested, a client enters end-game mode: each peer that will take more requests is asked for one block already on request elsewhere, so a slow peer can't stall the finish, and cancel goes to the others once a block lands.
Choosing whom to serve. In the choking algorithm BEP 3 describes as the deployed one (others are allowed if they interoperate with it), a host unchokes the four interested peers it downloads from fastest, recomputed once per ten seconds so the choice doesn't flap, and a seed with the full file ranks peers by its upload rate to them instead. One peer is also unchoked regardless of rate, rotated once per 30 seconds, and counts as one of the four while it is interested; a new connection is three times as likely as the rest to be picked for it, so a newcomer with nothing to trade can still get a first complete piece. Capping the number of simultaneous uploads also keeps TCP congestion control from behaving badly across many connections at once.
When a piece arrives corrupted. A piece is hashed when its last block lands; a host doesn't advertise it until the hash matches, and a piece that fails is downloaded again, which is why the tracker protocol has hosts report bytes still needed rather than computing it from bytes downloaded. BitTorrent v2 (BEP 52) hashes each file as a SHA2-256 Merkle tree built from 16 KiB blocks, requires the piece length to be a power of two of at least 16 KiB, and adds hash request and hashes messages so a peer can fetch the tree layers it needs, down to the leaf hashes; a client that fetches leaf hashes can check single blocks rather than whole pieces.
When to use it
Use a swarm when many hosts want the same large bytes at about the same time: a fleet pulling a new container image, a deploy pushing one artifact to thousands of servers, a model checkpoint going out to a training or serving cluster, an OS image to a lab. The gain comes from the total-upload term: each receiver adds its own upload link to the pool, so the time to reach all of them stays near the time to send one copy, where client-server time grows in step with N.
Inside a data center the same idea shows up as a distribution layer in front of a blob store. Uber's Kraken registry was built after a sharded Docker registry with caches couldn't keep up with image pulls across its clusters; it keeps blobs in a store such as S3 or HDFS and distributes them peer to peer. Uber reports a peak of 20,000 blobs of 100 MB to 1 GB delivered in under 30 seconds, clusters of at least 8,000 hosts, and downloads above half of a host's maximum download speed, with cluster size and image size having little effect on that speed.
Reach for it as well when the receivers come and go. A host that leaves mid-download can come back with the pieces it checked still on disk and report what it has rather than start over, and a seed that stays after finishing keeps serving. Rarest-first selection is what makes churn survivable: the piece held by the fewest hosts is copied first, so a departing host is less likely to take the last copy with it.
When not to
Skip it when the client-server term is already small: a few receivers, or a file small enough that N·F/u_s is seconds. A swarm adds a tracker or DHT, hash checks, connection setup and a warm-up period in which a new host holds nothing to trade, so under the choking rules above its first piece may have to wait for an optimistic unchoke, which favors new connections. For one user fetching one file, a CDN that caches it near them is the simpler answer; see CDNs and edge caching.
Skip it when the bottleneck isn't the source's upload: when F/d_min, the slowest receiver's download time, is larger than the source's share of the work, it sets the time for both designs and peers can't help. A link many receivers share caps the total in a similar way. The bound above assumes each host's own link is the limit and the network between hosts has room to spare; our advice is to check that against your own topology (a rack uplink shared by a whole rack of receivers, a cross-region link) before promising swarm speeds.
Skip it when there's no overlap in what hosts want. A swarm forms around one content hash; a thousand hosts each pulling a different artifact get nothing from each other. And treat confidentiality as a design question of its own: the handshake in the base protocol checks the info hash and the peer id, not who the peer is, so a private deployment needs its own admission control around the tracker and the peer connections.
Compared
| Approach | Time to reach N hosts | The right choice when | Weak spot |
|---|---|---|---|
One source, client-server | Grows with N: about N·F/u_s once N is large | N is small, the file is small, or receivers arrive at different times | The source's upload link saturates first |
CDN or cache tier | Bounded by the edge nodes' total upload and how many of them hold a copy | Many users, each fetching on their own schedule, from fixed locations | Each cache still pays a full miss; receivers don't help each other |
Relay tree (each host forwards to a few children) | Roughly the depth times one hop when each node relays whole files; chunked forwarding can overlap the hops | A fixed set of hosts with stable links, such as a chained copy inside a rack | Leaves don't upload, and a slow or dead interior node stalls its whole subtree |
Swarm with pieces (BitTorrent-style) | Near the larger of F/u_s and F/d_min when peers upload at about the source's rate; with weak uploaders the total-upload term takes over | Many hosts want the same large file at about the same time | Slow start for a host with nothing to trade; a tracker or DHT to run; hash checks per piece |
In a picture
Step 1 of 4
Start with the metadata
A new host first gets the small metadata file: piece size, piece hashes and where to find a tracker. It knows what the file should look like before it has a single byte of it.