How to Build a User Follow System with NENE2
This guide walks through building a Twitter/Instagram-style social follow system — users follow each other, view follower/following lists, and check mutual follow status.
Field Trial: FT134
NENE2 version: ^1.5
Covered topics: follow/unfollow, idempotent writes, graph queries, soft-constraint enforcement
What we're building
A REST API that lets users:
- Follow and unfollow other users (idempotent follow, 204 unfollow)
- Query follower/following lists (ordered by most-recent-first)
- Check follower/following counts in one stat call
- Check if a specific user is following another
Database schema
sql
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE follows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
follower_id INTEGER NOT NULL,
followee_id INTEGER NOT NULL,
created_at TEXT NOT NULL,
UNIQUE (follower_id, followee_id),
CHECK (follower_id != followee_id),
FOREIGN KEY (follower_id) REFERENCES users(id),
FOREIGN KEY (followee_id) REFERENCES users(id)
);Two constraints do the heavy lifting at the DB layer:
UNIQUE (follower_id, followee_id)— prevents duplicate follow rowsCHECK (follower_id != followee_id)— prevents self-follow at the DB level (application also validates this)
API endpoints
| Method | Path | Description |
|---|---|---|
POST | /users | Create a user |
POST | /users/{followerId}/follow | Follow a user (idempotent) |
DELETE | /users/{followerId}/follow/{followeeId} | Unfollow a user |
GET | /users/{userId}/stats | Get follower/following counts |
GET | /users/{userId}/followers | List followers |
GET | /users/{userId}/following | List users this user follows |
GET | /users/{followerId}/is-following/{followeeId} | Check follow relationship |
Repository
php
final class FollowRepository
{
public function __construct(
private readonly DatabaseQueryExecutorInterface $executor,
) {}
public function follow(int $followerId, int $followeeId, string $now): bool
{
if ($this->isFollowing($followerId, $followeeId)) {
return false; // already following — return false so handler sends 200
}
$this->executor->execute(
'INSERT INTO follows (follower_id, followee_id, created_at) VALUES (?, ?, ?)',
[$followerId, $followeeId, $now],
);
return true; // new follow — handler sends 201
}
public function unfollow(int $followerId, int $followeeId): bool
{
$count = $this->executor->execute(
'DELETE FROM follows WHERE follower_id = ? AND followee_id = ?',
[$followerId, $followeeId],
);
return $count > 0;
}
public function isFollowing(int $followerId, int $followeeId): bool
{
return $this->executor->fetchOne(
'SELECT id FROM follows WHERE follower_id = ? AND followee_id = ?',
[$followerId, $followeeId],
) !== null;
}
/** @return array<int, array{id: int, name: string}> */
public function listFollowers(int $userId): array
{
$rows = $this->executor->fetchAll(
'SELECT u.id, u.name FROM users u
INNER JOIN follows f ON f.follower_id = u.id
WHERE f.followee_id = ?
ORDER BY f.id DESC',
[$userId],
);
return array_map(fn(mixed $row) => $this->hydrateUser((array) $row), $rows);
}
/** @return array<int, array{id: int, name: string}> */
public function listFollowing(int $userId): array
{
$rows = $this->executor->fetchAll(
'SELECT u.id, u.name FROM users u
INNER JOIN follows f ON f.followee_id = u.id
WHERE f.follower_id = ?
ORDER BY f.id DESC',
[$userId],
);
return array_map(fn(mixed $row) => $this->hydrateUser((array) $row), $rows);
}
}The follow() method returns bool to signal new-vs-existing so the handler can emit the correct HTTP status without an extra query.
Follow handler — idempotent POST
The tricky part is returning 201 Created for a new follow and 200 OK for a repeat follow, while rejecting self-follow with 422.
php
private function followUser(ServerRequestInterface $request): ResponseInterface
{
$params = (array) $request->getAttribute(Router::PARAMETERS_ATTRIBUTE);
$followerId = isset($params['followerId']) && is_numeric($params['followerId'])
? (int) $params['followerId'] : 0;
if ($followerId <= 0 || !$this->repo->findUserById($followerId)) {
return $this->responseFactory->create(['error' => 'follower not found'], 404);
}
$body = JsonRequestBodyParser::parse($request);
$followeeId = isset($body['followee_id']) && is_int($body['followee_id'])
? $body['followee_id'] : 0;
if ($followeeId <= 0 || !$this->repo->findUserById($followeeId)) {
return $this->responseFactory->create(['error' => 'followee not found'], 404);
}
if ($followerId === $followeeId) {
return $this->responseFactory->create(['error' => 'cannot follow yourself'], 422);
}
$wasNew = $this->repo->follow($followerId, $followeeId, date('Y-m-d H:i:s'));
$status = $wasNew ? 201 : 200;
return $this->responseFactory->create([
'follower_id' => $followerId,
'followee_id' => $followeeId,
'following' => true,
], $status);
}Why validate before the self-follow check? The 404 checks come first so that POST /users/9999/follow with followee_id: 9999 returns 404 (user doesn't exist) rather than 422 (self-follow). Existence errors take priority.
Unfollow handler — 204 or 404
php
private function unfollowUser(ServerRequestInterface $request): ResponseInterface
{
$params = (array) $request->getAttribute(Router::PARAMETERS_ATTRIBUTE);
$followerId = isset($params['followerId']) && is_numeric($params['followerId'])
? (int) $params['followerId'] : 0;
$followeeId = isset($params['followeeId']) && is_numeric($params['followeeId'])
? (int) $params['followeeId'] : 0;
if ($followerId <= 0 || !$this->repo->findUserById($followerId)) {
return $this->responseFactory->create(['error' => 'follower not found'], 404);
}
$removed = $this->repo->unfollow($followerId, $followeeId);
if (!$removed) {
return $this->responseFactory->create(['error' => 'not following'], 404);
}
return $this->responseFactory->createEmpty(204);
}Note: createEmpty(204) — JsonResponseFactory has a dedicated method for body-less responses.
Stats endpoint
php
private function stats(ServerRequestInterface $request): ResponseInterface
{
$params = (array) $request->getAttribute(Router::PARAMETERS_ATTRIBUTE);
$userId = isset($params['userId']) && is_numeric($params['userId'])
? (int) $params['userId'] : 0;
if ($userId <= 0 || !$this->repo->findUserById($userId)) {
return $this->responseFactory->create(['error' => 'user not found'], 404);
}
return $this->responseFactory->create([
'user_id' => $userId,
'followers_count' => $this->repo->followerCount($userId),
'following_count' => $this->repo->followingCount($userId),
]);
}AppFactory
php
final class AppFactory
{
public static function createSqliteApp(string $dbPath): RequestHandlerInterface
{
$dbConfig = new DatabaseConfig(
url: null,
environment: 'test',
adapter: 'sqlite',
host: '',
port: 1,
name: $dbPath,
user: '',
password: '',
charset: '',
);
$factory = new PdoConnectionFactory($dbConfig);
$executor = new PdoDatabaseQueryExecutor($factory);
$psr17 = new Psr17Factory();
$json = new JsonResponseFactory($psr17, $psr17);
$repo = new FollowRepository($executor);
$registrar = new RouteRegistrar($repo, $json);
return new RuntimeApplicationFactory(
$psr17,
$psr17,
routeRegistrars: [static fn(Router $r) => $registrar->register($r)],
)->create();
}
}Testing strategy
Each test runs against a fresh in-memory SQLite file, created in setUp() and deleted in tearDown().
Key cases:
php
// Idempotent follow → 200
public function testFollowIdempotentReturns200(): void
{
$alice = $this->createUser('Alice');
$bob = $this->createUser('Bob');
$this->request('POST', "/users/{$alice}/follow", ['followee_id' => $bob]);
$res = $this->request('POST', "/users/{$alice}/follow", ['followee_id' => $bob]);
$this->assertSame(200, $res->getStatusCode());
$this->assertTrue($this->json($res)['following']);
}
// Self-follow → 422
public function testFollowSelfReturns422(): void
{
$alice = $this->createUser('Alice');
$res = $this->request('POST', "/users/{$alice}/follow", ['followee_id' => $alice]);
$this->assertSame(422, $res->getStatusCode());
}
// Unfollow then re-follow → 201 again
public function testUnfollowThenRefollow(): void
{
$alice = $this->createUser('Alice');
$bob = $this->createUser('Bob');
$this->request('POST', "/users/{$alice}/follow", ['followee_id' => $bob]);
$this->request('DELETE', "/users/{$alice}/follow/{$bob}");
$res = $this->request('POST', "/users/{$alice}/follow", ['followee_id' => $bob]);
$this->assertSame(201, $res->getStatusCode());
}
// Mutual follow
public function testMutualFollow(): void
{
$alice = $this->createUser('Alice');
$bob = $this->createUser('Bob');
$this->request('POST', "/users/{$alice}/follow", ['followee_id' => $bob]);
$this->request('POST', "/users/{$bob}/follow", ['followee_id' => $alice]);
$this->assertTrue($this->json($this->request('GET', "/users/{$alice}/is-following/{$bob}"))['following']);
$this->assertTrue($this->json($this->request('GET', "/users/{$bob}/is-following/{$alice}"))['following']);
}Order-by convention
Both listFollowers and listFollowing use ORDER BY f.id DESC — the most recently followed user appears first. This mirrors Twitter/Instagram's "followers" tab behaviour.
Common pitfalls
| Pitfall | Fix |
|---|---|
| Returning 422 for unknown user in self-follow check | Validate user existence before the self-follow check |
followee_id read from path instead of body | followee_id is in the request body; followeeId is the path param for DELETE |
Using createJson() | The method is create(array $data, int $status = 200) |
Using createEmpty() for a 200 with body | Only use createEmpty() for 204 No Content |
Missing JsonRequestBodyParser::parse() call | Must call this manually in every handler that reads a JSON body |