SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Peer-to-Peer (P2P)

No central server: every machine is both a client and a server (BitTorrent, blockchains).

⏱ 13 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Peer-to-peer (P2P) is a design where the computers talk directly to each other and share the work. Every computer (a peer) is both a client and a server.

  • There is no single big server that everyone must go through. The crowd is the system.
  • When more people join, they also bring more capacity (upload speed, storage, CPU), so the system can get stronger as it grows.
  • With no central point, there is no single point of failure, but finding things and trusting strangers become harder.

02Concept: What is it?

In the client-server model, many clients ask one (or a few) servers. The server does the work and holds the data. If a million people download a big file, the server's network becomes the bottleneck, and the owner pays for all of that traffic.

In a peer-to-peer network, each participant can both ask and answer. A peer that has downloaded a piece of a file can give that piece to other peers. The file travels through the crowd, and the original owner uploads far less.

Two big questions must be solved in every P2P system. First, discovery: how does a peer find other peers or find who has the data it wants? Second, trust: how do we know a stranger sent the correct data? Systems answer these with trackers, distributed hash tables (DHT), gossip, and cryptographic hashes.

Client-server and peer-to-peer
Client-server
🖥️Serverdoes everything
💻Client
💻Client
💻Client
↕all traffic
Peer-to-peer
💻Peer A
↔
💻Peer B
💻Peer C
↔
💻Peer D
↕peers help each other
In P2P the arrows go in many directions. Every peer gives and takes.
🧠Everyone is both
A peer is a client when it asks for data and a server when it gives data. The more peers that give back, the healthier the network.

03Real-Life Example

🍵Copying a Book in a Study Group
A teacher has one rare book that 30 students need. If every student queues to copy it from the teacher, the teacher is busy for days. Instead, the teacher gives chapter 1 to one student, chapter 2 to another, and so on. Students then swap chapters with each other. Soon everyone has the whole book, and the teacher only handed out the book once. If the teacher goes home, the students can still finish, as long as someone holds each chapter. To make sure nobody copies a chapter wrongly, each chapter has a checksum written by the teacher.
Study group
Peer-to-peer file sharing
The teacher with the only book
The original seed
Each student
A peer
A chapter
A piece of the file
Swapping chapters
Peers exchange pieces
A student who leaves right after copying
A peer that does not seed (a leecher)
The checksum on each chapter
A hash used to verify each piece
Asking around who has chapter 5
Peer discovery (tracker or DHT)
Download time as the crowd grows
Client-server, 10 peoplefast
Client-server, 1000 peopleserver is the bottleneck
Peer-to-peer, 10 peoplefast
Peer-to-peer, 1000 peoplepeers add capacity
One server shares its speed among everyone. A swarm gets more total upload speed with every new peer.

04Why Do We Need It?

📈Scales with users
Each new peer brings upload speed and storage, so demand also adds supply.
💸Lower server cost
The owner does not pay for all the bandwidth. The crowd carries it.
🛡️No single point of failure
If some peers leave, the rest keep working. There is no one machine to take down.
🗽Hard to censor or shut down
No central owner means no single off switch.
📍Closer, faster paths
Peers in the same city or building can talk directly, without a trip to a far data centre.
🔐Privacy by design
Calls and messages can go directly between users, without a company in the middle.
P2P turns users from a cost into a resource: the more people use it, the more capacity it has.

05Where Do We Use It?

📦File sharing
BitTorrent shares big files by cutting them into pieces and trading pieces.
📹Calls and video
WebRTC connects browsers directly for video, voice and data (a server only helps them find each other).
🪙Blockchains
Bitcoin and Ethereum nodes gossip transactions and blocks to each other.
🧰Software updates
Some systems let computers on the same network share updates (Windows Delivery Optimization).
🗂️Distributed storage
IPFS and similar systems find files by their content hash and serve them from many peers.
🎮Games and chat
Some multiplayer games and chat apps connect players directly to reduce delay.

06Types / Parts / How It Works

Three kinds of P2P network

KindHow peers find each otherGood and bad
Centralized (hybrid)A central server keeps the list of who has what. Data moves peer to peer.Simple and fast to search. The index server is a single point of failure (the first Napster).
UnstructuredPeers connect randomly and ask neighbours, flooding the question across the network (early Gnutella).Very resilient. Searches are noisy and may miss rare items.
Structured (DHT)Peers and data get IDs, and a rule says which peer is responsible for which key (Chord, Kademlia).Exact lookups in about log N steps with no central server. More complex, and costly when peers join and leave often.
Three ways to find who has the data
Hybrid
📒Index server
💻Peer
💻Peer
Unstructured
💻Peer
↔
💻Peer
❓Ask neighboursflood the question
DHT
🔑key → responsible peer
🧭Route in log N hops
Central index Flooding Hash table
Discovery is the hardest part of P2P. The data transfer is easy once you know who to ask.

How BitTorrent shares one file

StepWhat happens
1. Make the torrentThe file is cut into pieces (for example 256 KB to 4 MB). A hash of each piece goes in a small .torrent file.
2. Find peersThe client asks a tracker or the DHT for a list of peers in the swarm.
3. Trade piecesPeers tell each other which pieces they have and request what they lack. Rare pieces are fetched first.
4. VerifyEvery piece is checked against its hash. A bad piece is thrown away and fetched again.
5. SeedPeers that finish keep sharing. The more seeds, the faster and safer the swarm.
VisualizerOne server for everyone vs a swarm of peersGrow the crowd and compare the two bars. Lower the share of peers who stay and watch P2P lose its help. Then switch the origin server off and see which approach survives.
🖥️Origin server100 MB/s
Green = peer that keeps sharing. Cyan = peer that downloads and leaves.
Client-server: time for everyone5 min
Peer-to-peer: time for everyone2 min
Download time as the crowd grows (blue = client-server, green = P2P). Taller is slower.
151020406080100
number of peers downloading
Client-server
5 min
3.3 MB/s each
Peer-to-peer
2 min
1 GB file
Server load
100%
client-server
Sharing peers
21
need 3+ if no server
With 30 downloaders, client-server takes 5 min because one server splits its speed 30 ways. In P2P each new peer also brings upload speed, so it takes 2 min. More users make P2P faster per user, not slower.

A simplified model with no random numbers. The file is 1000 MB, the server sends 100 MB/s in total, and a peer can download at most 20 MB/s. Real swarms (like BitTorrent) also lose speed to rare pieces, slow peers and peers leaving.

07How to Use It / Steps / Implementation

Designing a P2P system

  1. 1
    Decide what is shared
    Files, a ledger, a video call, storage space? This decides what peers must keep and send.
  2. 2
    Choose how peers find each other
    A central tracker is the easiest. A DHT or gossip removes the central part but is harder to build.
  3. 3
    Cut data into pieces
    Small pieces let many peers help at once, and let a peer resume after a break.
  4. 4
    Verify everything
    Give each piece a hash (or sign the data). Never trust a stranger's bytes without checking.
  5. 5
    Reward sharing
    Use rules such as tit-for-tat (BitTorrent) so peers that give get faster downloads. This fights free-riders.
  6. 6
    Handle NAT and firewalls
    Most home computers are behind a router. Use STUN, hole punching and, as a last resort, a relay server (TURN).
  7. 7
    Plan for churn
    Peers join and leave all the time. Keep copies on several peers and refresh them.
💡Hybrid is common
Many real products mix both: a server for login, search and relays, and peers for the heavy data. You get most of the savings and keep control of the user experience.
⚠️Your IP address is visible
In many P2P networks, other peers can see your address. Think about privacy, abuse and legal rules before you build or use one.

08Key Terms to Know

TermMeaning in easy words
PeerA participant that is both a client and a server
SwarmThe group of peers sharing the same file or data
SeedA peer that has the complete file and keeps sharing it
LeecherA peer that downloads but gives little back
TrackerA server that tells peers about other peers (does not hold the file)
DHTDistributed hash table: a shared lookup table spread over many peers (Kademlia, Chord)
Gossip protocolPeers pass news to a few random neighbours, and it spreads like a rumour
ChurnPeers joining and leaving all the time
NAT traversalTricks (STUN, hole punching, TURN) to connect peers behind routers
Free-riderA peer that uses the network and gives nothing back
Content addressingNaming data by the hash of its content, so any peer can serve it and anyone can verify it

09Pros, Cons and Trade-offs

✅ Pros
  • Capacity grows with the number of users
  • Cheaper for the owner (less bandwidth to pay for)
  • No single point of failure
  • Hard to shut down or censor
  • Can use nearby peers for lower delay
⚠️ Cons
  • Peers are unreliable: they leave, go offline or are slow
  • Discovery and NAT traversal are hard
  • Trust and security are hard (fake or bad peers)
  • Hard to update, delete or control data
  • Speed is uneven and less predictable
  • Peers see each other's IP addresses

Trade-offs

ChoiceWe gainWe lose
P2P instead of client-serverScale and low server costControl, predictability and simple security
Central trackerEasy and fast discoveryA single point of failure and a target
DHTNo central part at allComplex code and slower, less exact searches under churn
Small piecesMore peers can help, easy resumeMore hashes and more messages
Strict sharing rulesFair and fast for those who giveHarder for new or slow peers
Hybrid designServer control plus P2P savingsTwo systems to build and run

10Common Problems and Mistakes

Common mistakes

  1. Trusting peers. A peer can send corrupt or malicious data. Always verify with a hash or a signature.
  2. Forgetting NAT. Many users are behind routers, so direct connections often fail without STUN or a relay.
  3. No incentive to share. If everyone leaves after downloading, the swarm dies. Reward seeding.
  4. Relying on one tracker. If it goes down, nobody finds anyone. Add a DHT or several trackers.
  5. Assuming peers stay. Data held by one peer will disappear. Keep several copies.
  6. Ignoring attacks. Sybil attacks (one attacker pretends to be many peers) and eclipse attacks (surrounding a victim with bad peers) are real.
  7. Using P2P when a CDN is enough. For small files or few users, a normal server or CDN is simpler.

Things to watch

🎭Sybil attack
A fake crowd of peers controlled by one attacker. Costly identities (like proof-of-work) help.
🧱NAT and firewalls
Direct links fail for many users. Plan for relays.
🔄Churn
Peers coming and going can make a rare piece vanish from the swarm.
⚖️Legal and abuse
Open sharing can carry illegal content. Think about policy and moderation.

11Real-World Examples

🧲BitTorrent
Peers trade pieces of a file. Used for large legal downloads such as Linux images and game patches.
📞Skype (early days)
Used peer-to-peer links and supernodes for calls, before moving more to servers.
🪙Bitcoin and Ethereum
Thousands of nodes gossip transactions and blocks, and agree without a central bank.
🌐IPFS
Files are addressed by content hash and served by whichever peers hold them.
🎮Game launchers
Some games have used peer sharing for patches to save bandwidth.
📹WebRTC apps
Browser video calls send media peer to peer when the network allows.
📝Note
Products change how they work over time (Skype, for example, later moved to a server-based design). Treat them as examples of the idea.
Mini case: a video call with WebRTC
👩Browser A
↔signalling
🧭Signalling serverintroduces them
↔signalling
👨Browser B
👩Browser A
↔video and audio, direct
👨Browser B
The server only introduces the two browsers (signalling). The video itself goes directly, or through a relay if the direct path fails.

12Related Topics to Read Next

Client-Server→

The model that P2P is most often compared with.

WebRTC→

Browser-to-browser connections for calls and data.

Consistent Hashing→

The idea behind placing data on peers in a DHT.

Checksums→

How peers verify that a piece was not corrupted.

CDN→

The central way to serve popular files close to users.

Single Point of Failure (SPOF)→

P2P is one way to remove it.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: every node is both client and server. Peers share work and data directly.
  • ✔Gain: capacity grows with users, lower server cost, no single point of failure.
  • ✔Cost: discovery, trust, NAT, churn, uneven speed, harder control.
  • ✔Discovery: central tracker, flooding, or a DHT (log N lookups).
  • ✔Trust: hash every piece or sign the data. Never trust strangers.
  • ✔Fairness: reward seeding (tit-for-tat) to stop free-riders.
  • ✔Connect: STUN and hole punching first, TURN relay as the backup.
  • ✔One line: “Let the crowd serve the crowd, and verify what strangers send you.”
← Previous
Event-Driven Architecture
Next →
Hexagonal Architecture