DevPath · Learn to code ESPTEN

Project: social network

The plan: users, followers and the social graph

The heart of a social network

A social network seems complicated, but it boils down to three entities:

  1. Users: each person with their id and their name.
  2. Followers: who follows whom.
  3. Posts: what each user writes.

The interesting piece is the followers one. Notice: a user can follow many others, and at the same time be followed by many. That is an N:M (many-to-many) relationship. But there is a special detail: both sides of the relationship are the same type of entity (a user follows another user).

A table with itself: the graph

When an entity relates to itself with N:M cardinality, what you get is a directed graph: the nodes are the users and the edges are the "follows". Direction matters: Ana following Beto does not imply that Beto follows Ana.

We model that relationship with a bridge table with two columns, both pointing to users:

CREATE TABLE followers (
  follower_id INTEGER, -- who follows
  followed_id INTEGER  -- whom they follow
);

Each row is an edge of the graph. To find out whom Ana (id = 1) follows, you filter by follower_id = 1 and look at the followed_id.

What's coming

In the next exercises you will build, in order:

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
The feed and the N+1 problem →