Nov 23, 20266 min read

Build an Activity Feed: Fan-Out on Write vs Fan-Out on Read

How follow-based feeds are stored, when to copy activities into each follower's feed and when to pull them at read time, the hybrid for accounts with huge followings, and cursor pagination, with a TypeScript example on Encore.

Illustration for Build an Activity Feed: Fan-Out on Write vs Fan-Out on Read

An activity feed, the "what happened in the accounts you follow" list, looks like one simple query. With a few thousand users that holds. With a few million, every page load merges activities from hundreds of followed accounts, and the endpoint everyone opens first becomes the slowest one.

This guide compares fanning out on write and on read, explains the hybrid most large feeds use and builds it on Postgres in TypeScript.

How does fan-out on read work?

Nothing extra happens at post time. When a user opens their feed, the backend finds the accounts they follow, reads each account's recent activities and merges them by time. It is simple, uses no extra storage and is always consistent with the latest follows and unfollows. The cost lands on every read, grows with the number of followed accounts and is hard to page through efficiently, since every page repeats the merge.

How does fan-out on write work?

When someone posts, the backend inserts a row into the feed_items table for each follower, holding the follower's ID, the activity ID and the timestamp. Reading a feed becomes WHERE user_id = $1 ORDER BY created_at DESC LIMIT 30 on one index, which stays fast no matter how many accounts the reader follows. The cost moves to writes: a post from an account with 50,000 followers is 50,000 inserts, which must happen in the background rather than in the request that created the post.

What is the hybrid approach?

Use fan-out on write for ordinary accounts and fan-out on read for the few with very large followings, then merge the two at read time. Twitter described this split in Timelines at Scale, and it keeps both costs bounded: no single post triggers millions of writes, and readers only pull activities live from the handful of large accounts they follow. A follower-count threshold such as 10,000 decides which path an account uses.

How should a feed be paginated?

Use keyset pagination on (created_at, activity_id), not OFFSET. New activities arrive at the top while a user scrolls, so offsets shift and show duplicates or skip items, and deep offsets get slow. A row comparison such as (created_at, activity_id) < ($2, $3) continues exactly where the previous page ended and uses the same index as the first page.

What about unfollows, deletes and privacy?

Deleting an activity removes its feed items through an ON DELETE CASCADE foreign key. An unfollow should remove the unfollowed account's items from that user's feed, which is one DELETE joining feed_items to activities. Visibility rules, such as private posts or blocked users, should be applied at read time as well as at fan-out, since settings change after an item was copied.

Activity feed with Encore

Encore

Encore is a backend framework with built-in infrastructure, and the feed's tables and its fan-out queue are declared in the TypeScript service below. Accounts, follows, activities and feed items live in an Encore Postgres database, and each new activity is published to a Pub/Sub topic whose subscriber does the fan-out with a single INSERT ... SELECT. Deployed, Encore runs the database and the queue in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

-- feed/migrations/1_create_feed.up.sql CREATE TABLE accounts ( id TEXT PRIMARY KEY, follower_count INT NOT NULL DEFAULT 0 ); CREATE TABLE follows ( follower_id TEXT NOT NULL REFERENCES accounts (id), followee_id TEXT NOT NULL REFERENCES accounts (id), PRIMARY KEY (follower_id, followee_id) ); CREATE INDEX follows_followee ON follows (followee_id); CREATE TABLE activities ( id BIGSERIAL PRIMARY KEY, actor_id TEXT NOT NULL REFERENCES accounts (id), verb TEXT NOT NULL, object_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX activities_actor_time ON activities (actor_id, created_at DESC); CREATE TABLE feed_items ( user_id TEXT NOT NULL, activity_id BIGINT NOT NULL REFERENCES activities (id) ON DELETE CASCADE, created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (user_id, activity_id) ); CREATE INDEX feed_items_user_time ON feed_items (user_id, created_at DESC, activity_id DESC);
// feed/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("feed");
// feed/feed.ts import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Topic, Subscription } from "encore.dev/pubsub"; const db = new SQLDatabase("feed", { migrations: "./migrations" }); // Accounts at or above this many followers are pulled at read time. const HIGH_FANOUT = 10_000; interface ActivityCreated { activityId: number; actorId: string; createdAt: string; } const activityCreated = new Topic<ActivityCreated>("activity-created", { deliveryGuarantee: "at-least-once", }); export const record = api( { expose: false }, async (p: { actorId: string; verb: string; objectId: string }): Promise<{ id: number }> => { // The row commits only after the publish, so a failed publish stores nothing and the caller retries. await using tx = await db.begin(); const row = await tx.queryRow<{ id: number; created_at: Date }>` INSERT INTO activities (actor_id, verb, object_id) VALUES (${p.actorId}, ${p.verb}, ${p.objectId}) RETURNING id, created_at`; await activityCreated.publish({ activityId: row!.id, actorId: p.actorId, createdAt: row!.created_at.toISOString(), }); await tx.commit(); return { id: row!.id }; }, ); export const _fanOut = new Subscription(activityCreated, "fan-out-to-followers", { handler: async (e) => { const actor = await db.queryRow<{ follower_count: number }>` SELECT follower_count FROM accounts WHERE id = ${e.actorId}`; if (!actor || actor.follower_count >= HIGH_FANOUT) return; // read path covers these // ON CONFLICT makes a redelivered event a no-op. await db.exec` INSERT INTO feed_items (user_id, activity_id, created_at) SELECT follower_id, ${e.activityId}, ${e.createdAt}::timestamptz FROM follows WHERE followee_id = ${e.actorId} ON CONFLICT DO NOTHING`; }, maxConcurrency: 10, }); interface FeedParams { userId: string; beforeTime?: string; beforeId?: number; } interface FeedItem { id: number; actorId: string; verb: string; objectId: string; createdAt: Date; } export const feed = api( { expose: false }, async (p: FeedParams): Promise<{ items: FeedItem[] }> => { const beforeTime = p.beforeTime ?? "infinity"; const beforeId = p.beforeId ?? Number.MAX_SAFE_INTEGER; const items = await db.queryAll<FeedItem>` SELECT a.id, a.actor_id AS "actorId", a.verb, a.object_id AS "objectId", a.created_at AS "createdAt" FROM ( SELECT activity_id AS id FROM feed_items WHERE user_id = ${p.userId} AND (created_at, activity_id) < (${beforeTime}::timestamptz, ${beforeId}::bigint) UNION SELECT a2.id FROM activities a2 JOIN follows f ON f.followee_id = a2.actor_id JOIN accounts c ON c.id = a2.actor_id WHERE f.follower_id = ${p.userId} AND c.follower_count >= ${HIGH_FANOUT} AND a2.created_at > now() - interval '7 days' AND (a2.created_at, a2.id) < (${beforeTime}::timestamptz, ${beforeId}::bigint) ) ids JOIN activities a ON a.id = ids.id ORDER BY a.created_at DESC, a.id DESC LIMIT 30`; return { items }; }, );

The request that records an activity does one insert and one publish, and the fan-out happens in the subscriber with a single statement per activity, so a post from an account with 5,000 followers never blocks the user who posted it. The feed endpoint is internal and called from your authenticated API layer with the signed-in user's ID, and the next page passes the createdAt and id of the last item as beforeTime and beforeId.

encore run starts Postgres and Pub/Sub locally, so you can seed a few accounts, follow them, record activities and read the merged feed, with the fan-out visible as its own span in the local trace. A coding agent changing the threshold or adding a visibility rule edits the subscriber and the read query in the same file and can check both paths against the local database before the change goes anywhere.

Best fit: Apps with follows, workspaces or marketplaces that want a fast home feed backed by their own Postgres database and a background fan-out queue.

Frequently asked questions

What is fan-out on write?

When someone posts, the backend copies a reference to the new activity into the feed of every follower. Reading a feed is then a single indexed query on one user's rows, at the cost of many writes per post.

What is fan-out on read?

The feed is assembled when it is requested, by querying recent activities from every account the reader follows and merging them. Posting is one write, and reading gets slower as the number of followed accounts grows.

Which fan-out approach should I use for a feed?

Most feeds use fan-out on write, because feeds are read far more often than people post. Accounts with very large followings are the exception and are usually pulled at read time, which is the hybrid approach Twitter described for its home timelines.

How do I build an activity feed with Encore?

Store accounts, follows, activities and feed items in an Encore Postgres database, publish an event to a Pub/Sub topic when an activity is created, and fan it out to followers in a subscriber. encore run starts Postgres and Pub/Sub locally so posting and reading can be tested together.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders