← tonia.ai

Distributed systems · peer-to-peer

Peers without a center

In a peer-to-peer system every participant is both a client and a server. There is no machine in charge, so the peers themselves must find each other, decide who stores what, route requests, survive constant arrivals and departures, and keep cheaters and attackers from taking over.

Why peer-to-peer

A client-server system concentrates capacity, control, and failure in one place. A peer-to-peer (P2P) system spreads all three across the participants. Each new peer brings demand, but also bandwidth, storage, and CPU, so capacity can grow with popularity instead of collapsing under it.

Client-serverPeer-to-peer server one bottleneck, one point of failure, one owner every node serves; capacity grows with membership

The price is that every service a central server gives for free must be rebuilt in a decentralized way: membership (who is in the system), lookup (who has item X), placement (who should store X), and trust (which peers are honest). Peers are also unreliable and unequal. Measurements of early file-sharing networks found that peers differed by orders of magnitude in bandwidth and uptime, and that many contributed little or nothing.

PapersSaroiu, Gummadi & Gribble, "A Measurement Study of Peer-to-Peer File Sharing Systems," MMCN 2002 · Androutsellis-Theotokis & Spinellis, "A Survey of Peer-to-Peer Content Distribution Technologies," ACM Computing Surveys 36(4), 2004

Overlay networks

Peers connect to each other over ordinary internet paths, forming an overlay network: a logical graph whose links are application-level connections. Two overlay neighbors may be on different continents, while two machines in the same building may be many overlay hops apart.

overlayphysical network ABCDEF routers one overlay hop
An overlay hop from A to B crosses several physical links. Overlays that ignore physical location can send a lookup around the world several times; proximity-aware designs prefer neighbors with low round-trip time.

Overlays come in two broad kinds. Unstructured overlays let peers connect to whomever they like and search by exploring the graph. Structured overlays dictate exactly which peers each node links to, so that any item can be found in a bounded number of hops.

Unstructured search

The first P2P file-sharing systems tried three approaches in turn. A central index (Napster) kept the file transfers peer-to-peer but the directory on one server, which made it simple, fast, and easy to shut down. Flooding (early Gnutella) removed the server: a peer sends a query to its neighbors, who forward it to theirs, until a hop limit (TTL) runs out.

TTL = 2 boundary Q has the file,never asked hop 1: 4 peershop 2: 8 more plus duplicatesalong cross links
Message cost grows roughly as (degree)TTL, and a larger TTL only partly helps: rare items far from the searcher are still missed.

Flooding is robust and needs no maintenance, but it scales poorly and gives no guarantee of finding anything. Later designs improved it without adding structure:

  • Random walks: send a few walkers that each take one random step at a time, checking back periodically, instead of a flood. Message cost drops by orders of magnitude for popular items.
  • Replication by popularity: making more copies of popular items shortens searches. Replicating each item in proportion to the square root of its query rate minimizes the expected search cost.
  • Super-peers: a two-tier design where well-connected, long-lived peers index the content of the ordinary peers attached to them and flood only among themselves. KaZaA, later Gnutella versions, and early Skype used this.

PapersRipeanu, "Peer-to-Peer Architecture Case Study: Gnutella Network," P2P 2001 · Lv et al., "Search and Replication in Unstructured Peer-to-Peer Networks," ICS 2002 · Cohen & Shenker, "Replication Strategies in Unstructured Peer-to-Peer Networks," SIGCOMM 2002 · Yang & Garcia-Molina, "Designing a Super-Peer Network," ICDE 2003

Distributed hash tables

A distributed hash table (DHT) gives every peer the same simple interface, put(key, value) and get(key), while spreading the table across all participants. Every DHT rests on three ideas:

  • One identifier space. Hash each node's address or public key, and each item's name or content, into the same large space, typically 160 or 256 bits. Hashing spreads both uniformly.
  • A responsibility rule. Each key belongs to the node whose identifier is "closest" to it, by some distance the design defines. This is consistent hashing: when a node joins or leaves, only the keys adjacent to it move, roughly 1/N of the total.
  • Partial routing state. No node knows everyone. Each keeps O(log N) carefully chosen contacts, enough to make progress toward any key at every hop, so lookups finish in O(log N) hops.

Logarithmic scaling is what makes DHTs practical. With a million peers, log₂ N is about 20, so a lookup takes at most about 20 hops while each peer tracks only a few dozen others.

Many applications sit on that one primitive: file systems and archives (CFS, PAST), multicast (Scribe), content-addressed storage (IPFS), peer discovery for BitTorrent and blockchains, and the partitioning rings inside data stores such as Dynamo and Cassandra.

PaperKarger et al., "Consistent Hashing and Random Trees," STOC 1997

Chord: routing on a ring

Chord places nodes and keys on a circle of 2m identifiers. A key is stored on its successor, the first node clockwise from it. Following successor pointers alone would find any key, but in O(N) hops. So each node also keeps a finger table: finger i points to the successor of (own id + 2i−1), giving shortcuts a quarter, an eighth, a sixteenth of the way around, and so on.

Keys live on their successorFingers and a lookup for K54 N1 N8 N14 N21 N32 N38 N42 N48 N51 N56 K10→N14 K24→N32 K30→N32 K54→N56 identifiers 0–63clockwise ↻key → first node clockwise N1 N8 N14 N21 N32 N38 N42 N48 N51 N56 K54 lookup: N8 → N42 → N51 → N56dashed: N8's other fingers
With m = 6, N8's fingers point to successor(9), (10), (12), (16), (24), (40), which are N14, N14, N14, N21, N32, N42. Each hop at least halves the remaining distance to the key.

A lookup jumps to the finger that most closely precedes the key, then repeats from there. To join, a node finds its successor, takes over the keys between its predecessor and itself, and builds its fingers. A background stabilization protocol periodically repairs successor and predecessor pointers and refreshes fingers, so routing stays correct even when many nodes join at once. Fingers only affect speed; correctness depends only on successor pointers, which is why each node keeps a list of several successors.

PapersStoica et al., "Chord: A Scalable Peer-to-Peer Lookup Service for Internet Applications," SIGCOMM 2001 · extended version, IEEE/ACM ToN 11(1), 2003 · Dabek et al., "Wide-Area Cooperative Storage with CFS," SOSP 2001

Prefix routing

Pastry and Tapestry treat identifiers as strings of digits in base 2b, commonly hexadecimal. Each hop forwards to a node whose identifier shares one more leading digit with the key. A node's routing table has one row per prefix length and one column per digit value, so a lookup takes about log16 N hops: around five for a million nodes.

key: 3A7F 9C21 3F05 3A12 3A7B 0 digits shared1 digit2 digits3 digits; closest in its leaf set: owns key At each hop the routing table row for the current prefix length, column for the next key digit, gives the next node.

The routing table often has several candidates for an entry, and Pastry picks the one with the lowest network latency. This proximity neighbor selection makes early hops short and later hops, where candidates are scarce, the only long ones, so total lookup latency stays within a small factor of the direct path. Each node also keeps a leaf set of its numerically nearest neighbors, which finishes the final hop and provides natural replica locations.

PapersRowstron & Druschel, "Pastry: Scalable, Decentralized Object Location, and Routing for Large-Scale Peer-to-Peer Systems," Middleware 2001 · Zhao et al., "Tapestry: A Resilient Global-Scale Overlay for Service Deployment," IEEE JSAC 22(1), 2004

Kademlia and XOR distance

Kademlia defines the distance between two identifiers as their bitwise XOR, read as an integer. XOR is symmetric (d(a,b) = d(b,a)) and for any point and distance there is exactly one other point at that distance. Symmetry means the peers that contact a node are exactly the kind it wants in its own table, so ordinary traffic keeps routing tables fresh for free.

0000 6 0001 7 0010 4 0011 5 0100 2 0101 3 0110 0 0111 1 1000 14 1001 15 1010 12 1011 13 1100 10 1101 11 1110 8 1111 9 idd bucket 2d = 4–7 bucket 1d = 2–3 bucket 0d = 1 bucket 3d = 8–15 me Each bucket covers twice as many identifiers as the one below it but holds the same number of contacts (k, often 20). A node knows its own neighborhood in fine detail and distant regions only coarsely.

A node keeps a k-bucket for each distance range [2i, 2i+1). Buckets favor contacts that have been online longest, since long-lived peers tend to stay. Lookups are iterative and parallel: the searcher asks α (typically 3) of the closest contacts it knows for even closer ones, and repeats until no closer node appears. Parallel queries hide the delay of dead or slow peers. Kademlia's simplicity and resilience made it the most widely deployed DHT design.

PaperMaymounkov & Mazières, "Kademlia: A Peer-to-Peer Information System Based on the XOR Metric," IPTPS 2002
SpecsBitTorrent DHT protocol (BEP 5) · libp2p Kademlia DHT

Comparing geometries

Every structured overlay chooses a geometry, the shape of its identifier space and its distance function. The geometry decides how much freedom a node has in picking neighbors and next hops, which in turn decides how well it tolerates failures and how easily it can favor nearby peers.

DesignGeometryState per nodeLookup hopsWhere it lives on
ChordRing, clockwise distanceO(log N) fingers + successor listO(log N)Research systems; the ring idea in Dynamo and Cassandra
Pastry / TapestryPrefix tree of base-2b digitsO(2b log2b N) + leaf setO(log2b N)Multicast and storage layers (Scribe, PAST)
KademliaXOR metric (a binary tree)O(k log N) contactsO(log N), queried in parallelBitTorrent Mainline DHT, IPFS, Ethereum discovery
CANd-dimensional torusO(d) neighborsO(d N1/d)Influential design; constant state per node

Analysis across these designs found that geometries giving flexibility in both neighbor choice and route choice, such as rings and XOR, hold up better under failures and adapt to network proximity better than rigid ones.

PapersRatnasamy et al., "A Scalable Content-Addressable Network," SIGCOMM 2001 · Gummadi et al., "The Impact of DHT Routing Geometry on Resilience and Proximity," SIGCOMM 2003 · Lua et al., "A Survey and Comparison of Peer-to-Peer Overlay Network Schemes," IEEE Communications Surveys & Tutorials 7(2), 2005

Living with churn

Churn is the continual joining and leaving of peers. In open networks many sessions last minutes, so a large share of the membership turns over every hour. Data and routing state must survive this without any node announcing its departure.

Before: replicas on the next three successors ids → N32N38 (owner)N42N48N51 K35 After N38 fails N32goneN42 (new owner)N48N51 (new copy) re-replicate
Keeping r copies on consecutive successors means the next node already holds the data when the owner disappears; the system only has to restore the replica count.

Practical lessons from deployed DHTs:

  • Detect failure with timeouts tuned to measured round-trip times. A fixed timeout either waits too long on dead peers or declares slow ones dead.
  • Repair periodically rather than reactively. Reacting to every suspected failure at once can flood an already stressed network with repair traffic and make things worse.
  • Prefer long-lived peers. Session lengths are highly skewed; a peer that has been up for hours is likely to stay up, so routing tables that keep old contacts are more stable.
  • Budget repair bandwidth. Each departure forces its data to be copied elsewhere. Under high churn, replication traffic can exceed the bandwidth available for serving data, which limits how much a DHT can store reliably.
  • Balance load with virtual nodes. Random identifiers leave some nodes with several times their fair share of the ring. Running several virtual identifiers per physical node evens this out, and stronger machines can run more.

PapersRhea et al., "Handling Churn in a DHT," USENIX ATC 2004 · Stutzbach & Rejaie, "Understanding Churn in Peer-to-Peer Networks," IMC 2006 · Karger & Ruhl, "Simple Efficient Load Balancing Algorithms for Peer-to-Peer Systems," SPAA 2004

Incentives

A P2P system works only if peers contribute, but each individual peer does best by downloading without uploading, known as free-riding. BitTorrent's answer is to make contribution pay. A file is split into pieces, and peers sharing the same file form a swarm that trades pieces directly.

tracker or DHT "who else has this file?" seed peer A peer B peer C piece 3 piece 1 piece 2 piece 5 Filled squares are pieces a peer holds. Each peer requests the rarest pieces first, so every piece stays available.
  • Tit-for-tat choking: each peer uploads to the few peers that recently uploaded to it fastest, and "chokes" (refuses) the rest.
  • Optimistic unchoking: every so often it also uploads to one random peer, which lets newcomers with nothing to trade get started and discovers better partners.
  • Rarest first: peers fetch the pieces fewest others have, which spreads every piece quickly and protects the swarm if the original seed leaves.

Later studies showed that tit-for-tat is not airtight: a strategic client could download faster while uploading less by exploiting how generous ordinary peers are. Designing incentives that hold up against selfish but rational peers remains an active topic, and it reappears in blockchain systems that pay peers directly.

PapersCohen, "Incentives Build Robustness in BitTorrent," P2PEcon 2003 · Piatek et al., "Do Incentives Build Robustness in BitTorrent?" NSDI 2007
SpecThe BitTorrent protocol (BEP 3)

Getting through NATs

Most home and mobile devices sit behind network address translators and firewalls that block unsolicited incoming connections. Two such peers cannot simply connect to each other. The standard trick is hole punching with help from a reachable rendezvous server.

rendezvouspublic address NAT 1 NAT 2 A B 1. register1. register 2. swap public ip:port 3. both send at once outgoing packets open each NAT's mapping If the NATs are too strict (for example, symmetric NATs that pick a new port per destination), traffic falls back to a relay that forwards packets, which works but costs the relay's bandwidth.

The ICE framework standardizes this process: gather candidate addresses (local, public as seen by a STUN server, and relayed through TURN), test pairs of them, and use the best that works. WebRTC, VoIP, and libp2p all rely on it. Early Skype went further and promoted well-connected users into super-nodes that relayed and indexed for others, until it moved to server-based infrastructure.

PapersFord, Srisuresh & Kegel, "Peer-to-Peer Communication Across Network Address Translators," USENIX ATC 2005 · Baset & Schulzrinne, "An Analysis of the Skype Peer-to-Peer Internet Telephony Protocol," INFOCOM 2006
StandardsICE (RFC 8445) · STUN (RFC 5389) · libp2p hole punching

Attacks on open overlays

Anyone can join an open P2P network, and identities are cheap. That opens attacks that closed clusters never face.

victim S S S S S S S S attacker every neighbor is a Sybil honest peers, unreachable
Sybil attack
One adversary creates many identities. Without a trusted authority to certify identities, no fully decentralized system can prevent this, only make it costly.
Eclipse attack
The attacker fills a victim's routing table so all its traffic passes through attacker nodes, which can then hide, delay, or fake data.
Routing and storage attacks
Malicious nodes drop or misroute lookups, or claim responsibility for keys and return bad values.
Index poisoning
Fake entries point searchers to decoy or corrupted content.

Defenses raise the cost of identities and limit what any one identity can do:

  • Expensive or verified identifiers: derive node ids from public keys and require a proof of work, or tie them to IP addresses and limit nodes per subnet.
  • Constrained routing tables: make some entries deterministic, so an attacker can't choose freely who appears in them.
  • Redundant, disjoint lookups: query along several independent paths and compare answers.
  • Self-certifying data: address content by its hash, or sign it, so a forged value is detected on arrival no matter who served it.

PapersDouceur, "The Sybil Attack," IPTPS 2002 · Castro et al., "Secure Routing for Structured Peer-to-Peer Overlay Networks," OSDI 2002 · Singh et al., "Eclipse Attacks on Overlay Networks: Threats and Defenses," INFOCOM 2006 · Baumgart & Mies, "S/Kademlia: A Practicable Approach Towards Secure Key-Based Routing," ICPADS 2007 · Heilman et al., "Eclipse Attacks on Bitcoin's Peer-to-Peer Network," USENIX Security 2015

In practice

BitTorrent Mainline DHT

Kademliatrackerless discovery

Clients find other peers for a torrent by looking up the torrent's info-hash in a Kademlia DHT shared by millions of nodes, so a swarm keeps working even when no tracker exists. It is one of the largest DHTs ever deployed.

BEP 5: DHT protocol · WebTorrent (BitTorrent in the browser over WebRTC)

IPFS

content addressinglibp2p

IPFS names every block of data by the hash of its content, so any peer can serve it and the receiver can verify it. A Kademlia DHT maps content ids to the peers that provide them. Its evaluation paper measures the live network, nearly 200,000 peers in 152 countries, and the delays it achieves for publishing and retrieving content.

Trautwein et al., "Design and Evaluation of IPFS: A Storage Layer for the Decentralized Web," SIGCOMM 2022 · IPFS DHT docs

Blockchain networks

gossipunstructured overlay

Bitcoin and Ethereum spread transactions and blocks by gossip over unstructured overlays, and Ethereum uses a Kademlia-style protocol to discover peers. Because propagation speed affects fairness and forks, recent work redesigns these overlays: Kadcast broadcasts along Kademlia's structure, and Perigee lets each node learn better neighbors from observed delays.

Rohrer & Tschorsch, "Kadcast: A Structured Approach to Broadcast in Blockchain Networks," AFT 2019 · Mao et al., "Perigee: Efficient Peer-to-Peer Network Design for Blockchains," PODC 2020 · Ethereum networking layer

Local-first collaboration

peer syncCRDTs

Collaborative apps increasingly keep the primary copy of data on users' own devices and sync directly between peers when they can, merging concurrent edits with conflict-free replicated data types. Servers become optional helpers instead of the source of truth.

Kleppmann et al., "Local-First Software: You Own Your Data, in Spite of the Cloud," Onward! 2019

P2P ideas also live on inside data centers: Dynamo and Cassandra place data with a consistent-hashing ring and gossip membership, borrowing DHT techniques but running them among trusted machines where churn and Sybils are not concerns.

PaperDeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store," SOSP 2007

Tools and reading

Try it

  • PeerSimSimulate overlays with thousands of nodes and measure lookups under churn.
  • IPFS KuboRun a node, add a file, and watch which peers provide it.
  • libp2pThe modular P2P networking stack behind IPFS and Ethereum, with Kademlia, gossip, and hole punching built in.
  • TransmissionAn open-source BitTorrent client; watch the swarm, piece map, and DHT node count.
  • WiresharkCapture DHT and BitTorrent traffic; both have built-in dissectors.
  • MIT 6.5840 (formerly 6.824)Lectures and labs on the replication and fault-tolerance ideas DHTs build on.

Read it