Designing Access Control for Social Feed Visibility
System DesignModel answerLast updated
Design a system that enforces per-post audience rules across feed and permalink reads at high QPS while staying correct under friendship and privacy-setting changes.
You are building the visibility layer for a large social network. Every post an author creates has an audience setting that controls who can view it.
Audience types:
- Public: anyone can see the post.
- Friends: only the author's direct friends.
- Friends-of-friends (optional): direct friends plus anyone who shares a mutual friend with the author.
- Only me: the author only.
- Custom: an allow set (specific users, friend lists, or groups) combined with a deny set. The deny set always takes precedence.
Where enforcement applies:
- Main feed (infinite scroll with ranked candidates).
- Direct post permalink.
- Any surface where post content surfaces (profile, search, notifications).
Operational requirements:
- Privacy must be evaluated at read time against the current state of friendships, blocks, and audience settings.
- Reads dominate: expect hundreds of thousands of feed requests per second, each ranking 200–500 candidate posts, so the system performs over 100 million visibility checks per second. Each check must be extremely fast and batchable.
- Adding p99 latency for privacy filtering should stay under ~10 ms.
- Friendship creation/removal and audience changes happen constantly. The system must fail closed: if data is missing or stale, never show a post to an unauthorized viewer. Over-showing after a tightening change (e.g., unfriending or narrowing an audience) must be bounded to seconds. Brief under-showing after loosening is acceptable.
Out of scope: regulatory audit trails, legal compliance logging.
Discuss the data model, the read-time enforcement path, caching strategy, and how you handle updates to relationships and audience settings.
Hints
Hint 1
Cache the inputs to the decision (friendship edges, block edges, policy objects) rather than final per-viewer-per-post results, because edge caches have precise invalidation keys while result caches have N×M cardinality.
Hint 2
Batch the visibility check per feed request: load the viewer's friend set, block set, and list memberships once, then evaluate all candidates locally against that snapshot.
Hint 3
Return 404 (not 403) when a viewer lacks access, so you don't leak the existence of a hidden post.
Hint 4
Friends-of-friends is the expensive case: consider sorted ID arrays or compressed bitmaps with early-exit intersection, and optionally a Bloom filter for fast negative pre-screening (positives must be confirmed against real edges).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and scale
Before diving in, nail down the numbers that shape every decision.
- ~2B users, ~1B daily active. Average user has ~300 friends, capped at 5,000.
- Post writes: ~10K/s. Audience changes are far less frequent.
- Feed reads: ~500K–1M requests/s. Each request ranks 200–500 candidates, so the system performs 100M+ visibility checks/s. A single check must cost microseconds and must be batchable.
- Latency budget: privacy filtering adds <10 ms p99 to a feed request.
- Correctness: never show a post to an unauthorized viewer. Under-showing for a few seconds after loosening is fine; over-showing after tightening must be bounded to seconds.
2. API surface
POST /posts { content, audience } -> post_id
PUT /posts/{id}/audience { audience } -> policy_version
GET /posts/{id} (viewer from auth context) -> post | 404
GET /feed?cursor= (viewer from auth context) -> [post]
internal: canSee(viewer_id, [post_id...]) -> [bool] // batched
Return 404, not 403, when access is denied. A 403 leaks that the post exists.
3. Data model
Post(post_id, author_id, created_at, content_ref, policy_id, policy_version)
Policy(policy_id, owner_id, type ENUM{PUBLIC, FRIENDS, FOF, ONLY_ME, CUSTOM},
allow_users[], allow_lists[], allow_groups[],
deny_users[], deny_lists[], version)
FriendList(list_id, owner_id) members stored as graph edges: (list_id) -> user_id
Friendship edges: (u, FRIEND, v) bidirectional, stored in a graph store (TAO-like)
Block edges: (u, BLOCKS, v)
Key design choices:
- Simple audience types (Public, Friends, etc.) map to well-known shared policy IDs, so they cost zero extra storage per post.
- Custom policies are first-class objects that many posts can reference (e.g., "Close Friends minus coworkers"), avoiding per-post duplication.
- Friend lists are stored by reference. Adding someone to "Close Friends" means they can see older posts shared to that list. This matches user expectations and avoids rewriting post metadata.
4. Architecture
Client -> API/Feed service
|-- Candidate generation (fanout inbox + pull for public/FoF)
|-- Ranking
|-- Privacy Filter (batched canSee) -> Policy cache, Graph cache (friend/block/list edges)
Writes -> primary DB -> replication log -> cache invalidation (all regions)
The core principle is to separate content from authorization:
- Post content cache is keyed by
post_idand is viewer-independent. High hit rate, safe to share across requests. - Fanout inboxes are hints, not grants. Fanout pushes a post to friend feeds at write time, but every candidate is re-checked at serve time. If a user unfriends someone, no inbox scrubbing is needed.
- Privacy filter runs as a library or sidecar co-located with the feed service. It reads from in-memory caches of edges and policies.
5. The visibility check
canSee(v, post):
a = post.author
if v == a: return True
if blocked(a, v) or blocked(v, a): return False
p = policy(post.policy_id)
if v in deny(p): return False # expand via membership edges
switch p.type:
PUBLIC: return True
ONLY_ME: return False
FRIENDS: return isFriend(a, v)
FOF: return isFriend(a, v) or hasMutualFriend(a, v)
CUSTOM: return v in allow(p) # direct user or member of allowed list/group
return False # unknown/missing -> fail closed
Membership checks are edge lookups like (list_id, MEMBER, v), O(1) against the graph cache. You never expand lists into user sets per post.
6. Making 100M checks/s cheap
Batch per request. Load the viewer's context once (friend set as a hash set, block set, list memberships). Then evaluate every candidate locally against that snapshot. A request with 300 candidates often involves only ~50 distinct authors, so memoize isFriend and isFoF per author within the request.
Cache inputs, not results. Final (viewer, post) decision caches have N×M cardinality, low hit rates, and hard invalidation. Instead cache the inputs: friendship edges, block edges, and policy objects. These have precise invalidation keys (e.g., "invalidate edge (u, FRIEND, v)").
7. Friends-of-friends
FoF is the expensive case. hasMutualFriend(a, v) requires checking whether friends(a) ∩ friends(v) is non-empty.
- Store friend lists as sorted ID arrays or compressed bitmaps (e.g., Roaring bitmaps). Probe the smaller set against the viewer's hash set. With a 5,000-friend cap, this is a few microseconds and exits on the first hit.
- Optionally maintain a per-user Bloom filter of 2-hop reach. A Bloom filter gives a fast negative. Positives must be confirmed against real edges, because false positives would leak posts.
- Memoize the result per
(viewer, author)within a request, and use a short TTL of seconds if cached across requests.
FoF and Public posts typically enter candidate sets via pull rather than push, since they don't fit fanout well.
8. Updates and consistency
Unfriend or block. Write the edge deletion to the primary. The replication log invalidates graph cache entries in every region. Because the check runs at read time, all existing feed entries and permalinks are immediately re-evaluated. No rewriting needed.
Audience change. Update the policy and bump policy_version. Invalidate the post and policy cache entries.
Tightening is the dangerous direction. A lagging replica could keep serving the post for a short window. Two mitigations:
- Write a short-lived "recently tightened" marker. Reads that see it re-check against the primary or a fresher cache tier.
- Wait for cross-region invalidation acknowledgment before returning success to the author.
Loosening can be eventually consistent. Brief under-showing is harmless and self-corrects.
9. Common mistakes
- Caching final visibility decisions per
(viewer, post)— the cardinality explodes and invalidation is nearly impossible. - Treating fanout inboxes as authoritative — this breaks the moment a friendship changes, requiring expensive scrubbing.
- Returning 403 instead of 404 — leaks post existence to unauthorized viewers.
- Expanding friend lists into user sets at write time — wastes storage and prevents the "add to list = retroactive access" behavior users expect.
- Forgetting to fail closed — missing or stale data must default to denying access.