Skip to content
Shubham JangleResources
Networking

Explore topics

How Torrents Work: The BitTorrent Protocol

How do torrents work?

  • How can you download a 100 GB game or a Linux ISO from thousands of strangers, with no single server sending you the file?
  • The answer is BitTorrent, a peer-to-peer (P2P) file-sharing protocol. Everyone who is downloading a file also uploads the parts they already have to others.

Client-server vs peer-to-peer

  • Client-server: one server (or a server cluster or CDN) sends the full file to every user. More users means more load and more bandwidth cost for the server owner.
  • Peer-to-peer: every downloader, called a peer, is both a client and a server. Each new peer adds upload capacity, so a popular file often downloads faster, not slower.
Client-server downloadBitTorrent (P2P)
Who sends the dataOne server or CDNMany peers at once
Effect of more usersMore load on the serverMore upload capacity in the swarm
Bandwidth costPaid by the server ownerShared by the peers
Single point of failureThe serverNo single source, but needs enough peers
AvailabilityAs long as the server is upAs long as every piece exists somewhere in the swarm
Integrity checkUsually trust the server (sometimes a checksum)Every piece is checked against a hash

The .torrent file

  • Everything starts with a small .torrent file (a "metainfo" file). It does not contain the content, only metadata about it:
    • File names and sizes (one file, or a folder of files).
    • Tracker address(es) under the announce key, for example udp://tracker.example.org:1337/announce.
    • Piece length and a hash for every piece.
  • The content is treated as one long stream of bytes and split into fixed-size pieces, typically 256 KiB to a few MiB each (always a power of two). A 100 GB game with 4 MiB pieces has about 25,000 pieces.
  • In the original protocol (v1), each piece hash is a SHA-1 hash (20 bytes). BitTorrent v2 (BEP 52) uses SHA-256 and a per-file Merkle tree.
  • The file is encoded with bencode, a simple format of strings, integers, lists, and dictionaries:
d
  8:announce   35:udp://tracker.example.org:1337/announce
  4:info d
    4:name         13:my-game-files
    12:piece length i4194304e        <- 4 MiB per piece
    6:pieces       <20-byte SHA-1 of piece 0><20-byte SHA-1 of piece 1>...
    5:files        l ... file paths and lengths ... e
  e
e

Info hash

  • The info hash is the hash of the info dictionary (SHA-1 in v1, SHA-256 in v2). It is the torrent's unique ID.
  • Because it covers the file list and every piece hash, changing even one byte of the content produces a different info hash, and therefore a different torrent.

Magnet links

  • Instead of a .torrent file, people often share a magnet link, which carries just the info hash (plus optional extras):
magnet:?xt=urn:btih:<40-hex-char info hash>&dn=my-game-files&tr=udp://tracker.example.org:1337/announce
  • xt is the exact topic (the info hash), dn the display name, and tr an optional tracker.
  • Your client first finds peers for that info hash, then downloads the metadata (the info dictionary) from those peers using the metadata extension (BEP 9). It verifies the metadata by hashing it and comparing the result with the info hash.

Finding peers

  • All peers sharing the same torrent form a swarm. Your client needs to discover at least some of them.

Trackers

  • A tracker is a server that keeps a list of peers in each swarm. Your client announces itself: "I'm interested in info hash X, here's my IP and port, and here's how much I have downloaded and uploaded."
  • The tracker replies with a list of other peers' IP addresses and ports, and how long to wait before announcing again.
  • Trackers speak HTTP(S) or a lightweight UDP protocol (BEP 15).
  • A tracker never stores or sends the file. It only introduces peers to one another.

DHT (Distributed Hash Table)

  • Some torrents have no tracker, or the tracker is down. Clients can then use the DHT, where the peers themselves act as a decentralized tracker.
  • BitTorrent's DHT (BEP 5) is based on Kademlia:
    • Every DHT node has a random 160-bit node ID, in the same ID space as info hashes.
    • The "distance" between IDs is their XOR. The nodes whose IDs are closest to an info hash store the list of peers for that torrent.
    • To find peers, your client asks the closest nodes it knows, which point it to even closer nodes, until it reaches nodes that have the peer list. Each step roughly halves the remaining distance, so lookups take about log(N) hops.
  • You still need a starting point: clients join the DHT through well-known bootstrap nodes or peers they already know.

Other peer sources

  • PEX (Peer Exchange, BEP 11): connected peers share lists of other peers they know.
  • Local Service Discovery: finds peers for the same torrent on your local network.

Downloading pieces

  • Once connected, peers tell each other which pieces they have, using a bitfield and then have messages as new pieces complete.
  • Your client requests different pieces from different peers in parallel. Each piece is fetched in smaller blocks, usually 16 KiB, so a single piece can even come from several peers.
  • Hash verification: when a piece is complete, the client hashes it and compares the result with the hash in the metadata.
    • If it matches, the piece is saved and announced to other peers.
    • If it doesn't, the piece is discarded and downloaded again. Clients can ban peers that repeatedly send bad data.
    • This makes it practically impossible for a peer to slip corrupted or fake data into your download.

Which piece to download next

  • Rarest first: clients prefer the pieces that the fewest connected peers have. This spreads rare pieces quickly and protects the swarm if a peer holding them leaves.
  • Random first piece: a brand-new peer has nothing to share, so it may grab a random, readily available piece first to start uploading as soon as possible.
  • Endgame mode: near the end, the client requests the last missing blocks from several peers at once, so one slow peer doesn't stall completion.

Uploading while downloading

  • As soon as you finish and verify a piece, you can upload it to others. You don't need the whole file to start sharing.
  • Choking (tit-for-tat): a client uploads to only a few peers at a time, preferring peers that upload to it the fastest. Uploading to others therefore tends to get you faster downloads.
  • Optimistic unchoking: every so often, the client uploads to a random peer anyway. This lets newcomers get their first pieces and helps discover faster peers.

Seeders, leechers, and the "stuck at 99%" problem

  • A seeder has the complete content and only uploads.
  • A leecher (or downloader) is still downloading. It uploads the pieces it has too. ("Leecher" is sometimes also used for someone who downloads without sharing back.)
  • When a leecher completes the download and keeps the client open, it becomes a seeder.
  • Availability is what matters, not the seeder count alone:
    • With no seeders, a swarm can still finish downloads if the leechers together have every piece.
    • If no connected peer has a particular piece, nobody can finish. Your download can sit at 99% indefinitely, until a peer with that piece (often an original seeder) comes back online.
  • Many clients show this as availability or "distributed copies". A value below 1.0 means some pieces are currently missing from the swarm.

Transport details

  • Peers traditionally connect over TCP. Most modern clients also support uTP (Micro Transport Protocol) over UDP, which uses LEDBAT congestion control to back off when other traffic needs the connection, so torrents don't slow down your browsing as much. See TCP vs UDP.
  • Behind a home router (NAT), other peers can't open connections to you unless the port is forwarded (manually or via UPnP/NAT-PMP). You can still connect out to others, but you will reach fewer peers.

Important qualifications

  • Hashes protect integrity, not safety. They prove you received exactly what the torrent describes. If the torrent itself was created from malware, you get the malware, perfectly verified. Trust depends on where the torrent or magnet link came from.
  • Your IP address is visible. Everyone in the swarm, including the tracker, can see the IP addresses of the peers. BitTorrent traffic is not anonymous.
  • The protocol is legal; what you share may not be. BitTorrent is widely used for legitimate distribution, such as Linux ISOs, game patches, and large datasets. Sharing copyrighted content without permission is illegal in many countries.
  • Private trackers usually disable DHT and PEX so peers can only be found through the tracker, and they enforce upload/download ratios.
  • A tracker or DHT outage doesn't stop an existing download, as long as you are already connected to peers or can find them another way.
  • Web seeds (BEP 19) let an ordinary HTTP server act as a seeder, combining a client-server fallback with P2P.

Summary

  • BitTorrent is a peer-to-peer protocol: every downloader also uploads.
  • The .torrent file or magnet link describes the content: file names, sizes, piece hashes, and the info hash that uniquely identifies the torrent.
  • Peers are found through trackers, the DHT, and peer exchange. None of these send the content itself.
  • Content is split into pieces, downloaded from many peers in parallel, verified by hash, fetched rarest first, and shared as soon as each one completes.
  • A download finishes only if every piece is available somewhere in the swarm. If a piece is missing and no seeder returns, you're stuck at 99%.

References