DEV Community

Cover image for Frontend System Design: Facebook News Feed
ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Frontend System Design: Facebook News Feed

๐Ÿง  System Design: Facebook News Feed (Frontend)


1. ๐ŸŽฏ General Requirements

  • Display feed/stories from people the user follows.
  • User can create posts (text, image, video).
  • Users can Like, Share, and Comment.
  • Should support Infinite Scrolling:

    • Fetch older feeds as you scroll down.
    • Show new feeds in real-time (without refresh).
  • Real time updates when:

    • New post is created.
    • Someone likes/comments on an existing post.

2. ๐Ÿงฉ Component Architecture

Weโ€™ll design a modular, maintainable component system.

Top Level Layout

  • FeedPage

    • Manages initial data load, scrolling, and SSE subscription.
    • Renders a list of StoryCard components.

Story Component StoryCard

Responsibilities:

  • Show user avatar, name, timestamp.
  • Render post content (text/media).
  • Include controls:

    • โค๏ธ Like
    • ๐Ÿ’ฌ Comment
    • ๐Ÿ” Share

Sub-components:

  • StoryHeader โ€“ avatar, name, timestamp
  • StoryMedia โ€“ renders image/video
  • StoryActions โ€“ like/share/comment buttons
  • CommentList โ€“ render list of comments
  • CreateComment โ€“ textbox + post button

Comment Component CommentList

  • Displays all comments (virtualized for performance).
  • Each comment has:

    • Avatar
    • Username
    • Comment text

Create Comment Component CreateComment

  • Textarea + Post button.
  • Emits comment creation event to parent (StoryCard).

๐Ÿง  Component Hierarchy

FeedPage
 โ”œโ”€โ”€ StoryCard
 โ”‚    โ”œโ”€โ”€ StoryHeader
 โ”‚    โ”œโ”€โ”€ StoryMedia
 โ”‚    โ”œโ”€โ”€ StoryActions
 โ”‚    โ”œโ”€โ”€ CommentList
 โ”‚    โ””โ”€โ”€ CreateComment
 โ””โ”€โ”€ InfiniteScrollLoader (sentinel element)
Enter fullscreen mode Exit fullscreen mode

3. ๐Ÿงฑ Data Entities

type Media = {
  id: string;
  type: 'image' | 'video';
  url: string;
  thumbnail?: string;
};

type Comment = {
  id: string;
  user: { id: string; name: string; avatarUrl: string };
  text: string;
  createdAt: string;
};

type Story = {
  id: string;
  author: { id: string; name: string; avatarUrl: string };
  content: string;
  media?: Media[];
  likes: number;
  shares: number;
  comments: Comment[];
  createdAt: string;
};
Enter fullscreen mode Exit fullscreen mode

4. ๐Ÿ”Œ Data APIs

API Method Description
/api/feed?cursor=<id> GET Fetch paginated stories (for infinite scroll)
/api/story POST Create a new story
/api/story/:id/like POST Like/unlike story
/api/story/:id/comment POST Add comment
/api/story/:id/comments GET Fetch comments
/api/feeds/stream GET (SSE) Receive new stories in real-time

5. ๐Ÿ—‚๏ธ Data Store (Frontend State Management)

Use React Query, Zustand, or Redux Toolkit for reactive state.

State Structure:

{
  feed: {
    stories: Story[];
    cursor: string; // pagination cursor for older feeds
    loading: boolean;
  },
  newStoriesBuffer: Story[]; // for stories from SSE
  comments: { [storyId: string]: Comment[] },
  user: { id: string; name: string }
}
Enter fullscreen mode Exit fullscreen mode

Behaviors:

  • Optimistic Updates: Apply changes (likes/comments) instantly, rollback on failure.
  • Normalized Storage: Map comments and stories by IDs.
  • Buffer for SSE stories: Temporarily store new stories and show a โ€œNew Posts Availableโ€ banner.

6. ๐Ÿ”„ Infinite Scrolling (Old Feeds)

Use IntersectionObserver for older feed pagination.

Frontend Flow:

const sentinel = document.querySelector('#load-more');

const observer = new IntersectionObserver(async entries => {
  if (entries[0].isIntersecting) {
    await fetchOlderFeeds(); // REST API call
  }
});

observer.observe(sentinel);
Enter fullscreen mode Exit fullscreen mode

API Example:

GET /api/feed?before=<oldest_story_id>&limit=10
Enter fullscreen mode Exit fullscreen mode

Backend returns:

[
  { "id": 201, "author": "Zeeshan", "content": "Older post...", "createdAt": "..." }
]
Enter fullscreen mode Exit fullscreen mode

7. โšก Real Time New Feeds via SSE

To get new stories without sockets, use Server-Sent Events (SSE).

Frontend:

// Connect to SSE endpoint
const eventSource = new EventSource('/api/feeds/stream');

eventSource.onmessage = (event) => {
  const newStory = JSON.parse(event.data);
  addToNewStoryBuffer(newStory); // Show "New posts available" banner
};
Enter fullscreen mode Exit fullscreen mode

When user clicks โ€œShow new postsโ€ โ†’ prepend buffer to feed.

Backend SSE Endpoint:

app.get('/api/feeds/stream', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.flushHeaders();

  const sendStory = (story) => {
    res.write(`data: ${JSON.stringify(story)}\n\n`);
  };

  feedEmitter.on('newStory', sendStory);

  req.on('close', () => feedEmitter.off('newStory', sendStory));
});
Enter fullscreen mode Exit fullscreen mode

Example Event Pushed:

data: {"id":302,"author":"Ali","content":"New post here!"}
Enter fullscreen mode Exit fullscreen mode

8. ๐Ÿงญ Complete Feed Flow

Direction Mechanism Trigger Endpoint Action
Initial Load REST On mount /api/feed?limit=10 Show first 10 stories
Infinite Scroll (Old Feeds) REST Scroll bottom /api/feed?before=<id> Append older stories
New Feed Updates SSE Server push /api/feeds/stream Prepend new stories / show banner

9. ๐Ÿš€ Optimization Strategies

A. Network Performance

  • Gzip/Brotli compression.
  • WebP/AVIF images.
  • Serve assets via CDN.
  • Enable HTTP/2.
  • Lazy load heavy media via IntersectionObserver.
  • Bundle splitting: vendor vs. app bundles.

B. Rendering Performance

  • Use SSR or hydration.
  • Virtualized list rendering (React Window / VirtualScroller).
  • Use defer/async for scripts.
  • Memoize components and results.

C. JS Performance

  • Debounce scroll handlers.
  • Code-splitting by route.
  • Offload heavy tasks to Web Workers.

10. ๐Ÿงฉ Accessibility (A11y)

  • Semantic HTML: <article>, <header>, <section>, <button>.
  • ARIA roles for live feed updates: aria-live="polite".
  • Keyboard navigation.
  • Alt text for media.
  • High contrast colors.

11. ๐Ÿงฎ Example Flow: Combined Infinite Scroll + SSE

Scenario:

  1. User opens app โ†’ GET /api/feed?limit=10
  2. Scrolls to bottom โ†’ GET /api/feed?before=201&limit=10
  3. Another user posts โ†’ Server sends SSE โ†’ data: {"id":305,"author":"Sara","content":"New story!"}
  4. Frontend receives event โ†’ Shows โ€œNew posts availableโ€ banner.
  5. User clicks โ†’ New story appears at top of feed.

12. ๐Ÿงพ Endpoint Summary

Endpoint Method Description
/api/feed?limit=10 GET Initial feed load
/api/feed?before=<id> GET Fetch older feeds (scroll)
/api/feeds/stream GET (SSE) Stream new feeds in real-time
/api/story POST Create new story
/api/story/:id/like POST Like story
/api/story/:id/comment POST Add comment

โœ… Final Summary

Feature Mechanism Endpoint Direction
Old Feeds (Scroll) REST API /api/feed?before=<id> โฌ‡๏ธ Downward
New Feeds (Live) SSE /api/feeds/stream โฌ†๏ธ Upward
Feed Rendering React Components โ€” Client-side
State Sync Store (Redux/Zustand) โ€” Bidirectional

More Details:

Get all articles related to system design
Hastag: SystemDesignWithZeeshanAli

systemdesignwithzeeshanali

Git: https://github.com/ZeeshanAli-0704/front-end-system-design

Top comments (0)