← build log
feedpattern 05Feed architecture

Fan-out-on-write: paying for ranking before anyone reads

The following feed has no ranking problem. The only real question is where to spend the work.

The problem

The following feed shows posts from people you follow, in reverse-chronological order — no ranking model, no relevance scoring, just recency. The question is where the cost of assembling that list lives: computed fresh on every read, or paid once when a post is written. Naively, it’s a query — fetch posts where the author is in the user’s follow set, order by time, limit twenty — and that query gets slower in direct proportion to how many people a user follows and how many posts those authors have written.

Approaches considered

Query at read time. SELECT * FROM posts WHERE author_id IN (...) ORDER BY created_at DESC LIMIT 20. Correct, and trivially cheap when a user follows a handful of accounts. It stops being cheap once follow counts get into the hundreds — every page load re-scans and re-sorts across every followed author’s posts.

Cache the query result. Wrap the same query in a Redis cache with a short TTL. Reduces repeated-read cost but does nothing for the first read after a cache miss, and invalidation on every new post from any followed author is its own coordination problem.

Fan-out-on-write. When a post is created, push it directly into every follower’s precomputed timeline. Reads become a lookup against that timeline, not a query against the source table.

Trade-offs

Fan-out-on-write turns one write (a post) into N writes (one per follower), all triggered by a single event. For most authors that’s a small, bounded number. For an author with a very large following, it isn’t — which is its own problem, covered next.

The decision

fanout-service consumes post.created and pushes the post ID into every follower’s Redis sorted set, scored by timestamp. feed-service reads that sorted set directly.

Why

The following feed is read far more often than it’s written to — every follower’s every page load, against one post per author per interval. Fan-out-on-write moves the cost to the side of that ratio that happens once, and leaves the frequent side — the read — as close to free as a Redis lookup gets. The following feed doesn’t need to be clever; it needs to be fast, and doing nothing at read time is the fastest a read can be.

Implementation

// fanout-service — one post.created event becomes one ZADD per
// follower, writing directly into their precomputed timeline.
func (f *Fanout) HandlePostCreated(ctx context.Context, evt PostCreatedEvent) error {
	followers, err := f.userClient.GetFollowers(ctx, evt.AuthorID)
	if err != nil {
		return err
	}

	pipe := f.redis.Pipeline()
	score := float64(evt.CreatedAt.Unix())
	for _, followerID := range followers {
		key := fmt.Sprintf("timeline:%s", followerID)
		pipe.ZAdd(ctx, key, redis.Z{Score: score, Member: evt.PostID})
	}
	_, err = pipe.Exec(ctx)
	return err
}

// feed-service — the read path does exactly one thing: look up
// the precomputed timeline, newest first.
func (s *FeedService) GetFollowingFeed(ctx context.Context, userID string) ([]string, error) {
	key := fmt.Sprintf("timeline:%s", userID)
	return s.redis.ZRevRange(ctx, key, 0, 19).Result()
}