Course outline

1.4

Client–Server vs Peer-to-Peer

Centralised vs decentralised: control, failure, scaling and security, with BitTorrent and WebRTC.

24 min Reading + animations

Tip: tap or hover any dotted-underlined term to see what it means.

By the end of this lesson you will be able to

  • Explain the core difference between the client–server and peer-to-peer (P2P) models, and why a peer is both a client and a server.
  • Compare them on control, node roles, single point of failure, scalability, security and traffic.
  • Explain how BitTorrent distributes a file: torrent files and magnet links, trackers and the DHT, pieces, seeders and leechers, rarest-first and tit-for-tat.
  • Describe how WebRTC sets up a direct call through NAT with signalling, STUN and TURN.
  • Recognise the hard problems of P2P (churn, free-riders, NAT, trust) and the hybrid designs real products use.
  • Decide which model fits a given system design problem, and justify it.

#Two ways to organise a networked system

Whenever computers work together, someone has to decide who holds the data and who does the work. There are two basic answers, and they come from two different philosophies:

  • Client–server (centralised): one side (the server) owns the data and provides the service; the other side (the client) asks for it.
  • Peer-to-peer, P2P (decentralised): there is no central owner. Every computer, called a peer or node, both asks for and provides the service.
Client–server (centralised)          Peer-to-peer (decentralised)

        [Central server]                 [Peer A] <-----> [Peer B]
        /       |      \                    ^   \       /   ^
       v        v       v                   |     \   /     |
  [Client] [Client] [Client]                v     /   \     v
                                         [Peer C] <-----> [Peer D]

Play the scenarios below. The same four computers behave very differently depending on the model, especially when something disappears.

Client–server vs peer-to-peer

The same four computers, organised two ways. Watch who talks to whom, and what happens when something disappears.

Scenario

Fixed roles: clients ask, the server answers.

Central serverowned by one company
A
B
C
D
Step 1 of 5
1

Centralised model. All the data (videos, posts, accounts) lives on the central server, run by one company. The four devices are clients.

#Client–server: the centralised model

In the client–server model, roles are fixed and separate:

  • The client only requests a service: your browser, the Facebook app, a game launcher.
  • The server only provides it: it stores the data, runs the logic and answers.
  • All the files and data live on central servers that one company or organisation runs.

Examples: Google Search, YouTube, Facebook, online banking, almost every traditional web service. Even a chat message from you to a friend travels through the server: the server stores it, checks it and delivers it.

Why most of the web is built this way:

  • Control: one owner decides the rules, ships updates instantly and can delete abusive content.
  • Consistency: there is one source of truth. Your bank balance is whatever the bank’s database says.
  • Security is easier to manage: you protect a known set of machines, check every request and keep logs.
  • Simple clients: a phone does not need to stay online, store anything or serve anyone.

The price is that the server side carries all the load and all the cost, and if it is not built with redundancy it is a single point of failure (SPOF).

#Peer-to-peer: the decentralised model

In a P2P network there is no central server. Every connected computer is a peer, and every peer acts as a client and a server at the same time.

When you download a file through BitTorrent, you receive pieces from other people (the client part), and at the same moment you upload the pieces you already have to someone else (the server part).

Well-known P2P systems:

SystemWhat is shared peer-to-peer
BitTorrentLarge files, split into pieces and traded between downloaders
Blockchain (Bitcoin, Ethereum)Transactions and blocks; every full node keeps its own copy of the ledger
IPFS (InterPlanetary File System)Files addressed by a hash of their content, not by a server location
WebRTCAudio, video and data sent directly between two browsers (video calls)

#Client–server vs P2P, side by side

CriterionClient–serverPeer-to-peer
ControlFully centralised: one server or company runs itDecentralised: no single owner or centre
Node roleClient and server roles are completely separateEvery node (peer) is both client and server
Single point of failureYes: if the central server goes down or its cable is cut, the whole system stops (unless it is built with redundancy)No: if some nodes go offline, the system keeps running
ScalabilityMore users means more load on the server; you must buy more serversMore users add more capacity, because newcomers also share (with limits, see below)
Security and confidentialityEasier to secure one central system wellHarder: malicious nodes, poisoned data and malware can spread
TrafficAll bandwidth converges on the central data centreTraffic is spread across many small peers
Finding dataEasy: ask the server, which can search its databaseHard: you must discover which peer has what
Availability of dataThe operator guarantees itOnly while some peer that has it is online
CostThe operator pays for servers and bandwidthUsers contribute their own bandwidth and storage

#Why P2P scales: the swarm

The strongest argument for P2P is distribution of popular content. Suppose 10,000 people want the same 1 GB file.

  • With one server, the server must upload 10,000 copies: 10,000 GB. The users’ upload capacity is wasted.
  • With P2P, the file is cut into pieces. The source sends each piece out roughly once, and the downloaders trade pieces among themselves. The total upload is shared by everyone.

Sending a 1 GB file to many people

Why P2P gets faster as more people join, while a single server gets slower.

Scenario

Upload cost grows with every user.

Original sourceserver / first seeder
Peer A
Peer B
Peer C
Peer D
Step 1 of 3
1

Four people want the same 1 GB file from one server.

That is why the notes say “more users make a P2P network faster”: every newcomer is also an uploader. Two honest limits:

  • Home upload is small. Many home connections upload much slower than they download, so the swarm’s total speed is limited by upload, not download.
  • Coordination costs grow too. Finding peers, keeping connections and handling churn add overhead, so P2P scales well but not infinitely.

#How BitTorrent works

BitTorrent (2001) is the classic P2P file-sharing protocol and the best example of the ideas above.

  1. 1. The torrent file or magnet link

    A small .torrent file describes the content: file names and sizes, the piece size (often 256 KB to a few MB), a hash of every piece, the tracker’s address, and the info hash, a fingerprint that identifies the torrent. A magnet link is even smaller: it carries only the info hash, and the client fetches the rest from peers.

  2. 2. Finding peers: tracker or DHT

    All peers sharing the same torrent form a swarm. To find them, the client either asks a tracker (a small web server that keeps a list of peers per info hash, but never stores the file), or the DHT (Distributed Hash Table), a lookup table spread over millions of peers, so no server is needed. Clients also swap peer lists with each other (peer exchange).

  3. 3. Trading pieces

    The client connects directly to many peers, learns which pieces each one has, and downloads different pieces from different peers in parallel. It asks for the rarest pieces first, so a piece that only one peer has gets copied before that peer leaves.

  4. 4. Verifying every piece

    Every received piece is hashed and compared with the hash in the metadata. A corrupt or fake piece is thrown away and the peer that sent it can be banned. This is what makes it safe to accept data from strangers.

  5. 5. Seeders, leechers and tit-for-tat

    A seeder has the complete file and only uploads. A leecher is still downloading (and uploads what it has). Each peer uploads to only a few peers at a time and prefers those who upload back to it fastest (tit-for-tat). Every so often it gives a random peer a chance (optimistic unchoking), so newcomers can start.

BitTorrent, step by step

From opening a torrent to becoming a seeder, and what happens when things go wrong.

Scenario

Your clientqBittorrent
Trackera small web server
DHT nodesother peers
Seederhas every piece
Leecherstill downloading
open .torrent
Step 1 of 10
1

A .torrent file is tiny. It holds the file names and sizes, the piece size, a hash of every piece, the tracker’s address, and the info hash: one fingerprint that identifies this torrent.

Self-checkQuestion

A BitTorrent tracker goes offline in the middle of your download. What happens?

#The hard parts of P2P

P2P removes the central server, and with it the things a central server used to guarantee. These are the problems every P2P design has to solve:

  • Churn: peers join and leave constantly. Data held only by peers that left is unavailable, and routing tables go stale. Designs keep several copies of everything and refresh their neighbour lists.
  • Free-riders: people who download but never upload. Incentives like tit-for-tat, or ratio rules on private trackers, push back.
  • Discovery: with no central index, finding “who has X” needs a DHT, flooding or a hybrid index.
  • NAT and firewalls: most home and mobile devices sit behind NAT and cannot accept incoming connections. P2P systems need NAT traversal (hole punching, UPnP port mapping) or relays.
  • Trust and security: any peer can lie. Systems use hashes to verify data, signatures to verify authors, and limits against a single attacker running thousands of fake peers (a Sybil attack). Your IP address is also visible to every peer you connect to.
  • Consistency: there is no single source of truth. Keeping everyone in agreement needs a consensus protocol, which is slow and complex (that is what blockchains spend their effort on).

#WebRTC: P2P inside your browser

WebRTC lets two browsers or apps exchange audio, video and data directly, which gives the lowest possible delay and costs the service nothing for bandwidth. Google Meet, WhatsApp calls and many video apps use it. The obstacle is NAT: neither side has a public address the other can connect to. WebRTC solves this with three helpers:

  1. Signalling server: the app’s own server (often a WebSocket) that passes the two sides’ offers and answers, describing media formats (SDP) and possible addresses (ICE candidates). WebRTC deliberately does not define it.
  2. STUN server: tells each device its public IP and port as seen from outside its NAT. Both sides then send packets to each other at the same time so each NAT lets the other in (hole punching). This is the framework called ICE.
  3. TURN server: when hole punching fails (strict NAT, carrier-grade NAT, firewalls that block UDP), the media is relayed through TURN. It still works and stays encrypted, but it is no longer peer-to-peer, and the operator pays for the bandwidth.

A WebRTC video call through NAT

P2P on the web needs three helper servers. None of them carries the call when things go well.

Scenario

The common case: STUN is enough.

Alicehome Wi-Fi, behind NAT
Signalling serverthe app’s WebSocket
STUN“what is my address?”
TURNrelay, last resort
Bobmobile data, behind NAT
what is my public address?
Step 1 of 8
1

Alice’s laptop only knows its private address (192.168.1.10). It asks a STUN server on the internet how it looks from outside.

#Blockchain and IPFS in brief

Blockchain networks such as Bitcoin and Ethereum are P2P networks of nodes that gossip transactions and blocks to their neighbours. Every full node verifies everything itself and keeps a full copy of the ledger. The hard part is agreeing on one order of transactions without a central bank; that is solved by a consensus rule (proof of work in Bitcoin, proof of stake in Ethereum). The cost is speed: Bitcoin handles only a handful of transactions per second, while a card network handles thousands.

IPFS stores files by content address: the file’s name is a hash of its contents, so you ask the network “who has this hash?” (through a DHT) instead of “give me the file on this server”. Any peer can serve it, and you can verify it. A file stays available only while at least one node keeps (“pins”) it, so many projects pay a pinning service, which is a server again.

#Hybrid models: what real products do

Pure P2P and pure client–server are the two ends of a spectrum. Most successful systems mix them: central parts for discovery, login and control; peers for the heavy data.

Pure vs hybrid P2P

Real P2P systems differ mainly in one question: how does a peer find the data?

Scenario

Search is central, transfer is P2P.

Central indexwho has what
A
B
Supernodea strong peer
Cbehind NAT
Dbehind NAT
who has song.mp3?
Step 1 of 3
1

Napster (1999) kept a central index of which user had which song. A asks the index.

  • Central index + P2P transfer: Napster (1999) had a central song index and direct transfers. Fast search, but when a court shut the index in 2001, the whole network died.
  • Tracker or signalling server: BitTorrent trackers and WebRTC signalling servers only introduce peers. If they fail, running transfers or calls continue but new ones cannot start.
  • Supernodes: early Skype promoted well-connected peers to supernodes that helped others find each other and relayed calls. Around 2012 Microsoft replaced them with its own servers, because phones make poor supernodes.
  • P2P to cut server costs: Spotify’s desktop app streamed music partly from other users from 2008 until 2014, when its own servers and CDNs became cheap enough. Windows Update’s Delivery Optimization still fetches update pieces from other computers, especially on the same LAN.
  • CDN vs P2P: a CDN puts the content on servers near users (a company-run, distributed client–server). It gives predictable speed, availability and control, at a cost. P2P gives near-free distribution but unpredictable availability. Some video platforms combine them: the CDN is the reliable base, and nearby viewers share pieces to reduce CDN traffic.

#Choosing a model in system design

Choose client–server when…Consider P2P (or a hybrid) when…
You need one source of truth (payments, bookings, accounts)The same large content goes to many users at once (updates, game patches, live video)
You must control access, moderate content or meet legal rulesLowest latency between two users matters (1:1 calls, multiplayer games on a LAN)
Clients are phones that sleep, have batteries and change networksUsers must keep working without a central operator, or censorship resistance is a goal
Data must always be available, even when no user is onlineBandwidth cost would dominate and users are willing to share

In an interview, the expected default for a product like a chat app, a shop or a social network is client–server with redundancy (load balancers, replicas, multiple regions, a CDN). Bring in P2P for a specific part, such as direct calls or content distribution, and name the trade-offs: NAT traversal and TURN cost, churn, trust, and the central pieces you still need.

#Try it yourself

# 1. Watch a real swarm: download a Linux image by torrent (legal and seeded by thousands).
#    In qBittorrent or Transmission, open the "Peers" tab: you will see many IPs,
#    and your own upload starts before your download finishes.
#    Ubuntu publishes torrents at https://ubuntu.com/download/alternative-downloads

# 2. Watch WebRTC: start a 1:1 Google Meet or any WebRTC call, then open
chrome://webrtc-internals
#    Look at the selected candidate pair: "host"/"srflx" means a direct path,
#    "relay" means the call goes through a TURN server.

A minimal WebRTC peer connection in the browser, showing where STUN and TURN servers are configured:

const pc = new RTCPeerConnection({
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },            // learn my public address
    { urls: 'turn:turn.example.com:3478',                 // relay if direct fails
      username: 'demo', credential: 'secret' },
  ],
});
pc.onicecandidate = (e) => e.candidate && signalling.send(e.candidate); // via your own server

#Summary

Key takeaways

  • Client–server is centralised: fixed roles, data on the operator’s servers, easy control and consistency, but the server carries all the load and is a single point of failure unless it is made redundant.
  • P2P is decentralised: every peer is both client and server, traffic is spread out, and capacity grows as peers join, as in a group study where everyone teaches.
  • BitTorrent splits files into hashed pieces, finds peers through a tracker or the DHT, downloads rarest first, and uses tit-for-tat against free-riders. Seeders have everything; leechers are still downloading.
  • P2P’s hard problems are churn, free-riders, discovery, NAT traversal, trust and consistency.
  • WebRTC uses a signalling server, STUN for hole punching and TURN as a relay when direct connection fails; group calls usually use an SFU server.
  • Most real systems are hybrids: central discovery and control, peer-to-peer data. In system design, default to client–server with redundancy and add P2P where distribution cost or latency demands it.