Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 23 min read

News Feed System Design With Photo Sharing and Carousel - Deep Dive. (Part 1)

Designing a news feed is a classic front-end system design question. Many guides focus on single pieces of the system or give high-level overviews without diving into the mechanics of any of them. This makes sense for a

Designing a news feed is a classic front-end system design question. Many guides focus on single pieces of the system or give high-level overviews without diving into the mechanics of any of them.

This makes sense for a 45-minute interview where you can't explain everything, so guides stick to a broad overview and assume you will not have time to dive deeply into most subsystems.

My goal for this article series is to build a fleshed-out system diagram that includes all (or almost all) elements in a news feed so we avoid any "black boxes" in our design.

Requirements

Functional Requirements

  • Users can browse an infinite feed of posts.
    • Users can scroll continuously to load older posts and refresh stale sessions without losing their current reading position or duplicating already-loaded posts.
    • A failed pagination request displays an inline retry option at the bottom of the feed while keeping all already-loaded posts interactive and visible.
  • Users can follow and unfollow people (unfollowing or unfriending immediately removes that person's private posts from the active feed and client cache).
  • Users can block other users.
  • Users can mute other users.
  • Users can react to posts.
  • Users can create new posts.
    • Posts can contain multiple pictures.
    • Posts can contain an optional title, description, hashtags, and mentions.
    • Post editing and creation use a WYSIWYG (What You See Is What You Get) editor.
  • Users can edit pictures in a live WYSIWYG preview before posting:
    • Filters.
    • Cropping.
    • Adding text and stickers.
  • Posts with multiple pictures render as an interactive carousel:
    • Mobile users swipe horizontally to move between pictures.
    • Desktop users click Prev/Next arrows (or press Left/Right arrow keys) to move between pictures.
    • The carousel displays a slide counter (e.g., 2 / 5) and stops at the first and last slide without looping.
  • Posts and photos can be "private" or "public." Private photos are shown only to the author's friends; public photos are shown to everyone.
  • Users can edit posts, and an "edited" badge will be shown on the post.
  • Users can share or "repost" posts.
  • Users can comment on posts.
    • Comments support mentions and hashtags in a WYSIWYG editor.
  • Users can click a post to open its post-detail view.
  • When the app wakes from sleep, or the user returns to a backgrounded tab, the feed shows a "New posts available" banner instead of prepending posts and shifting what the user is reading.
  • Users can sort the feed by "hot/ranked" order or chronological order.
  • Ads appear roughly every 5 posts.
  • Users can keep the feed open in two browser tabs at the same time without state conflicts or stale reactions.

Non-functional Requirements

  • Crawlability: Public post permalinks and public profiles must be crawlable by search engines.
  • Cold Load Speed: The initial feed must render in under 2.5s at p75 (75th percentile) on a mid-range 4G mobile device.
  • Concurrent Editing & Uploading: Users can upload edited photos in the background while continuing to edit other slides or draft their caption.
  • Warm Navigation Speed: Returning to the feed from a single-post view must render in under 100 ms from client cache without losing scroll position.
  • Zero Cumulative Layout Shift (CLS < 0.1): Reserved aspect-ratio boxes prevent the feed from jumping as images load or as users switch carousel slides.
  • Bounded Client Memory & DOM Size: Active DOM nodes stay under 1,500 via list virtualization, and total tab RAM stays under 200 MB on mobile by decoding only the active and adjacent carousel slides (current - 1, current, current + 1) and capping the in-memory store window.
  • Privacy & Cache Isolation: Private media uses short-lived signed URLs or cookie-gated edge checks, and account-scoped client caches (IndexedDB, Service Worker, memory store) purge immediately on logout or account switch.
  • Main-Thread Responsiveness (INP < 200 ms): Client-side image edits, feed scrolling, and reactions respond in under 200 ms (Interaction to Next Paint).
  • Resilient Reads/Writes & Bandwidth Adaptation: Mutating requests use idempotency keys, pagination retries recover from expired feed generations or transient network errors without discarding already-loaded posts, and images serve responsive AVIF/WebP variants matched to viewport and network speed.
  • Instant Adjacent Slide Transitions (< 100 ms): Intent-based prefetching loads current + 1 and current - 1 slides ahead of navigation so adjacent carousel transitions render in under 100 ms.
  • EXIF Metadata Stripping: The client strips camera EXIF metadata (GPS coordinates, device serials) before upload, and the server re-encodes and verifies every binary before publishing.
  • Accessibility (a11y) & Internationalization (i18n): The feed, composer, and carousel support keyboard navigation, screen-reader semantics, prefers-reduced-motion, 44 x 44 px mobile tap targets, and RTL layout mirroring.
  • Safe Rich-Text Rendering: Post and comment bodies store normalized plaintext plus entity ranges rather than raw HTML, neutralizing XSS vectors at render time.

Architecture choices

Before diving into each feature, we need to lock down our architectural choices.

Database - SQL vs NoSQL

To choose the best database for our system, we should first look at the shape of the data each requirement needs.

Infinite Scroll (Functional)

Let's start with the app's core functionality: infinite scroll. The cornerstone of the infinite scroll is the Post, so let's figure out what information a post needs.

Post

  • An ID so we can find it quickly and link it wherever it needs to go.
  • An author ID so we know who made it.
  • A body, a title, and community tags.
  • Media IDs.
  • Engagement metrics.
  • Creation timestamp.
  • Public/Private indicator.
  • Edited indicator.
  • Viewer-specific flags (viewerReaction and viewerHasShared) β€” note that these do not live in the posts table; instead, the server builds them on the fly for the authenticated viewer by joining against post_reactions and post_shares at read time.
type Post = {
  id: string;
  authorId: string;
  body: PostBody;
  title?: string;
  communityTags: string[];
  mediaIds: string[];
  engagementMetrics: EngagementMetrics;
  createdAt: string;
  isPublic: boolean;
  isEdited: boolean;
  viewerReaction: ReactionType | null;
  viewerHasShared: boolean;
};

type ReactionType = 'like' | 'love' | 'lol' | 'wow' | 'sad' | 'angry';

type EngagementMetrics = {
  reactions: Record<ReactionType, number>;
  totalReactions: number;
  commentCount: number;
  shareCount: number;
};

type Entity = {
  type: 'mention' | 'hashtag' | 'link';
  start: number;
  end: number;
  userId?: string;
  url?: string;
};

type PostBody = {
  text: string;
  // UTF-16 code-unit offsets into NFC-normalized text.
  entities: Array<Entity>;
};

type PostReaction = {
  postId: string;
  userId: string;
  reactionType: ReactionType;
  createdAt: string;
};

type PostShare = {
  postId: string;
  userId: string;
  createdAt: string;
};

type PostTag = {
  tagId: string;
  postId: string;
  postCreatedAt: string;
};

Given these schemas, what is the best database choice for posts?

Many system design guides default to NoSQL (such as DynamoDB or Cassandra) for posts because social feeds take heavy write volume and partition cleanly by postId. In a document or wide-column store, writing a new post spreads evenly across shards, and fetching a single post by id pulls the entire recordβ€”including body.entities and mediaIds off the disk in one lookup without joining tables. But NoSQL starts fighting us if we go deeper:

User reactions and shares:
NoSQL is a no-go here because, without relational joins, it forces us to add reacting userId arrays inside the Post document, which will blow past NoSQL per-item or per-document limits (400 KB per item in DynamoDB or 16MB per document in MongoDB) when posts go viral with thousands of reactions (And their respective user IDs).
We can use relational databases instead: Place a Primary key (userId, postId) on post reactions and post shares, so hydrating posts in a feed takes a single index-only scan (WHERE user_id = $viewerId AND post_id = ANY($postIds)).

Dual-sort feeds (hot/ranked vs. chronological) and PostTag filtering:
For NoSQL, we would need three separate tables to store all feed types (chronological, ranked, community tag feeds). And that would mean running writes on each table whenever a user edits a post. SQL (PostgreSQL) uses B-tree indexes (created_at DESC, id DESC) and (rank_score DESC, id DESC) on posts, plus PRIMARY KEY (tag_id, post_created_at, post_id) on post_tags for O(log N) scans.

Immediate privacy, block, and mute enforcement:
Private posts must disappear immediately when a viewer unfollows, blocks, or mutes someone. PostgreSQL can check is_public in the follows and blocks tables in one ACID read, so there's no lag in hiding private posts.

Idempotent retries:
A composite PRIMARY KEY (user_id, post_id) rejects or upserts duplicate reaction retries atomically at the storage engine without extra distributed locks.

SQL is the right choice for our app's infinite scroll feed.
SQL joins are great for our use case, and B-tree indexing lets us fetch data nearly as fast as NoSQL, even at massive scale.

There's one hardware bottleneck we need to address, though: PostgreSQL uses Multi-Version Concurrency Control (MVCC), so every reaction count update (UPDATE posts SET total_reactions = total_reactions + 1) writes a new row to the disk (and marks the old row dead for VACUUM), appends to the Write-Ahead Log (WAL), and holds an exclusive row-level lock until commit. In a viral post, concurrent updates queue behind that single row lock and spike p99 latency.

To solve this, we keep PostgreSQL as the durable source of truth while buffering engagementMetrics increments in Redis (HINCRBY post:counts:{postId} like 1 in RAM) and flushing batched deltas back to PostgreSQL every few seconds.

The Post type is only one piece of the puzzle. There are many more fields to consider, like the feed, the user, the media, and the ads. Let's move on to the feed itself. What fields should our Feed type have?

Feed

  • Post IDs.
  • ranking ID - This field exists because we want to be aware of re-rankings; when a ranking changes, the client sees an ID mismatch and does a clean refresh instead of duplicating posts.
  • cursors: olderCursor and newerCursor - We need these to figure out where the user is on the feed so we can load new posts without duplicate posts.
  • older/newer post indicators
    • hasOlder tells the IntersectionObserver whether older posts still exist past olderCursor; without this indicator, olderCursor === null can be ambiguous. We can't tell whether the feed hasn't loaded yet or if we have hit the oldest post in our DB/feed. We can display a "End of feed" status when hasOlder is false.
    • hasNewer tells the UI if fresh posts exist above newerCursor after a background check or tab refocus. We display a "New posts available" banner if hasNewer is true.
  • lastFetchedAt.
type Feed = {
  sort: FeedSort;
  id: string;
  generation: string;
  postIds: string[];
  olderCursor: string | null;
  newerCursor: string | null;
  hasOlder: boolean;
  hasNewer: boolean;
  lastFetchedAt: number | null;
}

type FeedSort = 'ranked' | 'chronological';

Considering these schemas, should we use SQL or NoSQL?
We should consider SQL's weaknesses for this schema. If we compute the feed directly from PostgreSQL on every scroll (pull at read time), the database has to join posts, follows, blocks, and mutes, filter out private posts, and sort the results.

This isn't scalable; it might work for a user who follows few people, but it will eat too much compute power once users expand their networks. Plus, generation, olderCursor, and newerCursor are transient state, so writing cursor or generation updates to PostgreSQL generates unnecessary Write-Ahead Log (WAL) traffic and MVCC row churn.

Now let's think about NoSQL:
A NoSQL store (e.g., Cassandra or DynamoDB) solves the disk-seek bottleneck by pre-grouping each user's timeline into a single contiguous partition on disk.

  • Partition Key: (user_id, sort) β€” for example, user_42:ranked or user_42:chronological.
  • Clustering / Sort Key: (rank_score DESC, post_id DESC) or (created_at DESC, post_id DESC).

Cassandra and DynamoDB store partitions inside immutable SSTables (Sorted String Tables) on disk. Because all of user_42's feed entries sit sorted together inside one partition, fetching 20 postIds past olderCursor is a single sequential slice on disk.

Or we could use MongoDB, which can store one Feed document per (user_id, sort) containing generation, olderCursor, newerCursor, and a postIds: [...] array, letting the server read the entire feed in a single primary-key lookup.

But NoSQL has a problem. We want to use a rank score for our feeds, and background rankers periodically recalculate rank_score and bump the feed's generation ID.

In an LSM-tree (Log-Structured Merge-tree) engine (Cassandra or DynamoDB), rows on disk are immutable. We can't update a clustering key (rank_score) in place. So on every update, the database must write a tombstone (a deletion marker) at the old position and insert a new entry at the new position.

So every batch re-rank injects hundreds of tombstones into active user partitions. And those tombstones stay on disk until background compaction merges the SSTables, so when a user scrolls through a heavily re-ranked feed, the p99 latency spikes because the storage engine has to read and skip past dead tombstones on disk before finding 20 live postIds.

In an architecture like MongoDB, it isn't that different - If you embed postIds inside a single Feed document, appending a new postId every time one of 1,000 followed authors publishes a post forces MongoDB's storage engine (WiredTiger) to rewrite the document and update its B-tree indexes repeatedly. Concurrent writes to the same user's feed document contend for document-level locks and generate heavy disk I/O to push an 16-byte ID.

So what can we do? In this case, we have two choices:

  1. Use NoSQL on disk knowing the limitations.
  2. Go for the "costlier" third option, REDIS.

WHY REDIS WINS.
Redis lives in RAM, making it much faster, though costlier; it's worth it for us since Feed is the first thing users see and a core functionality we can't afford to throttle.

Redis has the following advantages:

  • In-place score updates without tombstones: Running ZADD updates a post's position inside the in-memory skip list directly. No "tombstones" or "compaction" lag.

  • Sub-millisecond slices & hasNewer counts: ZREVRANGEBYSCORE slices postIds past olderCursor, and ZCOUNT checks hasNewer in microseconds in RAM without touching disk IOPS.

  • Automatic size caps: ZREMRANGEBYRANK trims each user's timeline to the newest 500–1,000 postIds (~64 KB per user), keeping RAM bounded. At the same time, PostgreSQL stays the durable fallback whenever an inactive user's Redis timeline expires.

I mentioned something in the last point: a PostgreSQL fallback; we must have a durable database as a fallback when using Redis, in this case:

  • Filters for post privacy before showing it to the viewer: If a Viewer blocks or unfollows an Author. The Author's postIds might still sit inside the Viewer's Redis ZSET until an async cleanup job scrubs them. Because the API still hydrates those 20 postIds from PostgreSQL (WHERE id = ANY($postIds)), PostgreSQL's ACID check against follows, blocks, and is_public acts as the final gatekeeper and drops unauthorized posts before building the JSON payload.

  • Cache eviction for inactive users: Redis keeps hot timelines in RAM with a TTL (e.g., 7–14 days). When an inactive user returns after a month and hits a cache miss, the server runs the fallback SQL query on PostgreSQL, repopulates their Redis ZSET, and serves the feed.

  • Celebrity fan-out spikes: When an author with 5 million followers publishes a post, pushing that postId into 5 million Redis ZSETs saturates network bandwidth and Redis's single-threaded event loop (We'll talk about how to fix this when we talk about Feed Generation - Fan-Out on Write vs. Fan-Out on Read).

Next, we need to think about the user field.

User

Let's ponder which fields belong in the user type

  • user ID
  • name
  • handle
  • profile picture URL
  • Relationship to viewer - This is assembled on the fly for the authenticated viewer.
    • Relationship to viewer will include:
    • friend
    • following
    • muted
    • blocked
type RelationshipToViewer = {
  isFriend?: boolean;
  isFollowing?: boolean;
  isMuted?: boolean;
  isBlocked?: boolean;
};

type User = {
  id: string;
  name: string;
  handle: string;
  profilePhotoUrl: string;
  relationshipToViewer: RelationshipToViewer; // Built at read time for the viewer
};

type FollowEdge = {
  followerId: string;
  followeeId: string;
  isFriend: boolean;
  createdAt: string;
};

type BlockEdge = {
  blockerId: string;
  blockedId: string;
  createdAt: string;
};

type MuteEdge = {
  muterId: string;
  mutedId: string;
  createdAt: string;
};

NoSQL might seem like a good fit for User profiles. Each User record is a small JSON object keyed by id, but our relationshipToViewer, block, and mute requirements make NoSQL have problems:

Why NoSQL struggles:

  • Document stores (MongoDB / DynamoDB) break on embedded edge lists: If you store followingIds, blockedIds, or friendIds as arrays inside the User document, an active user who follows or mutes thousands of accounts bloats the document, triggers write contention on every follow/unfollow, and forces the application server to download and scan entire arrays to check the 15 unique authors on a single feed page.
  • Wide-column stores (Cassandra / DynamoDB) force duplicate edge tables: Social edges need two query directions:
    • Forward check (Feed hydration): Given viewerId and the 15 authorIds on the current feed page, return isFollowing, isFriend, isMuted, and isBlocked.
    • Reverse check (Fan-out): Given authorId, fetch all followerIds when that author publishes a new post.

In a wide-column store without secondary indexes or joins, serving both directions forces us to maintain two separate tables (user_following partitioned by viewerId and user_followers partitioned by followeeId) and write retry/reconciliation jobs so a follow never succeeds in one table while failing in the other.

What about Graph Databases?
Graph databases (Neo4j / Amazon Neptune) add cross-database lag: Graph databases are excellent for 3-to-4-hop traversals that a news feed doesn't need on every scroll (e.g., "friends of friends of friends"). Our feed only checks 1-hop edges (viewer -> author), so putting social edges in a separate graph database splits the source of truth. When Viewer A blocks or unfriends Author B, you have to synchronize that change from Neo4j to PostgreSQL before isPublic: false posts stop leaking.

Why SQL (PostgreSQL) Wins for User and Social Edges

  • Atomic uniqueness on identity fields: PostgreSQL enforces unique constraints on handle and email addresses at the storage level. (Two concurrent sign-ups can never claim the same handle.)

  • Bidirectional B-tree indexes without duplicating rows: On follows, putting PRIMARY KEY (follower_id, followee_id) alongside a secondary index (followee_id, follower_id) lets one table serve both feed hydration and reverse follower lookups. When hydrating a 20-post feed page, PostgreSQL runs an index-only scan (WHERE follower_id = $1 AND followee_id = ANY($2)), checking its lightweight Visibility Map in RAM to return the edge flags straight from the B-tree leaf pages without even reading the main table heap.

  • Immediate ACID enforcement on blocks and unfollows: Because users, follows, blocks, mutes, and posts sit in the same PostgreSQL database, blocking or unfriending someone commits in a single ACID transaction. The next feed read sees the updated edge immediately. (Blocked users get blocked instantly)

3. Where Redis Assists (Caching Static Profile Fields)

There is one read-amplification hotspot on User: in a 20-post feed, millions of users fetch the same viral creators' static profile fields (name, handle, profilePhotoUrl) on every scroll. Even though WHERE id = ANY($1) is a fast primary-key lookup, hammering PostgreSQL for unchanged avatars and display names wastes database CPU.

The clean split is:

  • Redis (Profile Cache): Cache public profile fields (name, handle, profilePhotoUrl) in Redis (MGET user:profile:{id} with a TTL and explicit invalidation whenever a user updates their profile).
  • PostgreSQL (Store + Edges): Keep users, follows, blocks, and mutes in PostgreSQL so relationshipToViewer is always computed from fresh, transactional edge indexes.

We are almost done with our fields; let's now think about how media is stored.

Media

Posts reference mediaIds: string[], so the feed needs a Media structure for single images and multi-slide carousels:

  • Media ID
  • source
  • srcSetAvif and srcSetWebp - These are image formats to let the browser pick a variant depending on internet bandwidth and screen size (e.g., mobile 4G vs. desktop screens)
  • placeholder - A simple BlurHash or ThumbHash of about 25 bytes.
  • Alt text string.
  • width and height - To let the frontend pre-render sizes and prevent CLS - it also allows for faster rendering since the browser can ask for the optimal picture size up-front.
type MediaStatus = 'pending' | 'processing' | 'ready' | 'failed';

type MediaRecord = {
  id: string;
  ownerId: string;        // Verifies the uploader owns this mediaId before attaching to a post
  postId: string | null;  // Null while uploading in the composer before the user hits Publish
  storageKey: string;     // Internal S3/R2 object path (used to mint signed URLs at read time)
  width: number;
  height: number;
  placeholder: string;
  alt: string;
  isPublic: boolean;
  status: MediaStatus;
  createdAt: string;
};

Each image still needs a ~200-byte metadata row (id, ownerId, postId, width, height, placeholder, storageKey, isPublic, status).

NoSQL pros:
Hydrating media for a feed page is a straightforward key lookup (WHERE id = ANY($mediaIds)), and embedding width, height, and placeholder inside a NoSQL Post document avoids a separate lookup at read time.

NoSQL cons:

  • Atomic ownership checks during concurrent uploads (preventing IDOR): Our requirements let users upload photos in the background while drafting their caption. When the user clicks Publish (POST /posts with mediaIds: ['m1', 'm2']), the backend must verify in one atomic step that m1 and m2 belong to ownerId (stopping an attacker from attaching another user's private mediaId to a public post), that both have finished transcoding (status === 'ready'), and that neither is already attached to another postβ€”then set postId and isPublic inside the same ACID transaction that inserts the posts row.
  • Single-transaction privacy updates: When an author edits a post from public to private (or private to public), PostgreSQL updates posts.is_public and media.is_public together in one transaction. In a NoSQL store without multi-document transactions, a partial write leaves a private post serving public CDN URLs.
  • Fast orphan cleanup: Users frequently upload photos in the composer and close the tab without publishing. A partial B-tree index on media (created_at) WHERE post_id IS NULL lets a background worker find abandoned uploads older than 24 hours in milliseconds and delete their S3/R2 objects without scanning active media rows.

SQL pros
SQL allows us to keep width, height, and placeholder in PostgreSQL, letting GET /feed return aspect ratios and 25-byte placeholders in a single batched query (WHERE id = ANY($mediaIds)), keeping Cumulative Layout Shift (CLS < 0.1) near zero without touching object storage on feed reads.

So we should use SQL.

Media BLOBs

We need to store the actual media somewhere. The best practice for this is using blob storage; We have a few options that depend on the image's access patterns:

  1. CDNs - To keep popular images geographically close to where they are needed and quickly accessible.
  2. Blob storage (e.g. Amazon S3, Cloudflare R2) - To store the bulk of our images
  3. Cold storage (e.g., Amazon Glacier) - To store rarely accessed data and for archival purposes.

AdItem

Keep sponsored cards separate from user posts so ad campaign fields never pollute the posts table.

type AdItem = {
  id: string;
  campaignId: string;
  sponsorName: string;
  sponsorAvatarUrl: string;
  headline: string;
  body?: string;
  mediaId: string;
  ctaLabel: string;
  ctaUrl: string;
  impressionToken: string; // Signed payload sent back when the ad enters the viewport
};

// Backend database row powering ad selection and billing
type AdCampaign = {
  id: string;
  advertiserId: string;
  status: 'active' | 'paused' | 'exhausted';
  dailyBudgetCents: number;
  spentTodayCents: number;
  cpmCents: number; // Cost per 1,000 impressions
  targetTags: string[];
  createdAt: string;
};

SQL should own ad_campaigns, ad_items and billing ledgers

  • ACID budget caps: Advertisers pay per thousand impressions (cpmCents) or clicks. If two workers deduct spend from dailyBudgetCents at the same time in an eventually consistent NoSQL store, a campaign can overspend its daily cap before status flips to 'exhausted'. PostgreSQL updates spent_today_cents inside a single transaction (WHERE spent_today_cents + $cost <= daily_budget_cents) and flips status = 'exhausted' once the cap is hit.
  • Idempotent billing logs: Every billed view writes an append-only row to ad_billing_events with a UNIQUE constraint on impression_token_id and foreign keys to ad_campaigns and ad_items. If a mobile client retries a dropped POST /ads/impressions call, PostgreSQL rejects the duplicate token so the advertiser never pays twice for one view.

SQL cons on feed scroll

  • Per-viewer frequency capping (seen_ads): Users should not see the same ad every 5 posts as they scroll. Tracking seen campaigns in a PostgreSQL ad_impressions(user_id, campaign_id, seen_at) table and running WHERE c.id NOT IN (SELECT campaign_id FROM ad_impressions WHERE user_id = $viewerId AND seen_at > NOW() - INTERVAL '24 hours') on every page load forces PostgreSQL to scan and write ephemeral session rows at high QPS, bloating B-tree indexes with data that expires the next day.
  • MVCC lock contention on hot campaigns: Just like viral Post reactions, running UPDATE ad_campaigns SET spent_today_cents = spent_today_cents + $cost thousands of times per second queues concurrent writes behind a lock on that campaign row and spikes Write-Ahead Log (WAL) traffic.

Luckily, we have already decided that REDIS is the best choice for feeds:
How Redis Handles the Hot Path

  • Frequency capping in Redis (SET with TTL): When the feed assembler picks an ad for viewerId, it records SADD seen_ads:{userId} {campaignId} with a 24-hour EXPIRE. On the next scroll, the server reads SMEMBERS seen_ads:{userId} from RAM in microseconds and filters out already-seen campaigns before selecting the next AdItem.

  • Buffered impression counters: Incoming POST /ads/impressions calls verify the impressionToken signature, deduplicate the token in Redis (SETNX seen_token:{tokenId}), increment HINCRBY campaign:spend:{campaignId} impressions 1, and flush batched spend deltas to PostgreSQL every few seconds.

  • Interleaving at read time instead of fan-out on write: Unlike organic posts, ads never enter a user's pre-computed feed:{userId}:{sort} Redis ZSET. A campaign can pause or exhaust its budget at 2:04 PM; if its ID sat inside 5 million cached user timelines, you would have to scrub millions of ZSETs or leave empty slots in user feeds. Instead, the API slices 20 organic postIds from Redis, hydrates them from PostgreSQL, and inserts an eligible AdItem at every 5th slot right before returning the JSON payload.

Comments

Our final step when deciding NoSQL vs SQL is comments.
Post and comment are very similar schemas, so just like Post, a comment needs:

  • Post and parent links (postId and parentCommentId): Every comment belongs to a post. Keeping parentCommentId: string | null (null for top-level comments, or the top-level comment's ID for 1-level replies) supports threaded replies in the post-detail view without recursive tree queries.
  • Edited indicator (isEdited): Matches post editing so users see when a comment changed after posting.
  • Viewer-specific reaction flag (viewerHasLiked): Built on the fly at read time from a comment_reactions join tableβ€”never stored as a column on comments.
type Comment = {
  id: string;
  postId: string;
  parentCommentId: string | null; // null for top-level comments; parent ID for 1-level replies
  authorId: string;
  body: PostBody; // Reuses normalized plaintext + UTF-16 entity spans
  likeCount: number;
  replyCount: number;
  createdAt: string;
  isEdited: boolean;
  viewerHasLiked: boolean; // Built at read time from comment_reactions
};

type CommentReaction = {
  commentId: string;
  userId: string;
  createdAt: string;
};

Let's think about NoSQL vs SQL for comments,

NoSQL Pros

  • Contiguous partition reads in wide-column stores (Cassandra / DynamoDB): Comments are always read inside a single post's detail view. Using postId as the partition key and (created_at ASC, comment_id ASC) as the clustering key stores a post's comments together on disk, so loading the first 30 comments is a single sequential slice.
  • Embedding small threads in document stores (MongoDB): When a post only has five comments, embedding them inside the Post document fetches the post and its discussion in one lookup.

NoSQL Cons

  • Viral threads break document embedding: Embedding comments inside a Post document collapses the moment a viral post collects 50,000 commentsβ€”blowing past MongoDB's 16 MB document limit or DynamoDB's 400 KB item limit and forcing the storage engine to rewrite the entire Post document on every new reply.
  • Hot-partition bottlenecks: Partitioning strictly by postId routes every read and write for a viral post to a single storage shard, saturating that node's disk IOPS while other shards sit idle.
  • Block filtering and viewer hydration at read time: When a Viewer opens a post-detail view, comments from users the Viewer blocked must be excluded, and each comment needs viewerHasLiked hydrated from comment_reactions. Without joins, a NoSQL store has to fetch raw comments first, run separate queries against blocks and comment_reactions, and filter out blocked comments in application code (shrinking a 30-comment page down to 22 items).

Why SQL is better with a Redis Counter Buffer

  • Single-range B-tree scans for keyset pagination: Defining a composite B-tree index on (post_id, parent_comment_id, created_at ASC, id ASC) groups all top-level comments (parent_comment_id IS NULL) for a post into one contiguous leaf range ordered by creation time. Paginating with a keyset cursor (WHERE post_id = $1 AND parent_comment_id IS NULL AND (created_at, id) > ($cursorTime, $cursorId) LIMIT 30) walks 30 adjacent keys on the leaf page without slow OFFSET scans.
  • ACID block checks, cascades, and idempotency: PostgreSQL filters out blocked authors (NOT EXISTS against blocks), hydrates viewerHasLiked via an index-only scan on comment_reactions (user_id, comment_id), cascades deletions automatically when an author deletes a post (ON DELETE CASCADE), and rejects duplicate mobile retries via a UNIQUE (author_id, idempotency_key) constraint.
  • Offloading hot counters to Redis: Just like Post.engagementMetrics, updating posts.comment_count or comments.like_count directly in PostgreSQL during a viral spike creates MVCC dead tuples and row-lock contention. Buffering those increments in Redis (HINCRBY post:counts:{postId} comments 1) and flushing batched deltas to PostgreSQL every few seconds absorbs the write burst in RAM while keeping PostgreSQL as the durable source of truth.

Putting the Storage Layer Together

Matching each schema to its physical access pattern splits our storage across three engines rather than forcing one database to handle conflicting workloads:

  • PostgreSQL owns the durable relational tables (posts, post_reactions, post_shares, post_tags, users, follows, blocks, mutes, media, ad_campaigns, comments, and comment_reactions). ACID transactions, composite B-tree indexes, and unique constraints enforce immediate block and privacy checks, idempotent retries, and O(log N) keyset pagination.
  • Redis handles the in-memory hot paths: pre-computed user timelines (ZSET), buffered reaction, comment, and ad-impression counters (HINCRBY), cached public user profiles (MGET), and 24-hour seen-ad sets (SET).
  • Object Storage (S3 / Cloudflare R2) + CDN stores and serves immutable AVIF and WebP image files at the edge so multi-megabyte binaries never evict hot index pages from PostgreSQL RAM.

Now that we know where every schema lives, we have solved half of the backend puzzle. A user's timeline sits in a Redis ZSET, and organic posts live in PostgreSQLβ€”but we still need to decide how posts get into those timelines in the first place, especially when an account with 5 million followers publishes a post or when the server injects an AdItem every 5 posts without breaking cursors.

In Part 2, we will lock down the remaining architectural choices before writing any UI code:

  • Feed Generation (Fan-Out on Write vs. Fan-Out on Read): How we populate chronological and ranked timelines, handle celebrity fan-out spikes, and interleave ads every 5 posts.
  • REST vs. GraphQL: Standard cacheable endpoints (GET /feed, POST /posts) vs. typed queries with data-driven dependencies (@match/@module) for heterogeneous post formats.
  • SSR vs. CSR (and SPA vs. MPA): Rendering crawlable public post permalinks while keeping the personalized feed in an SPA for < 100 ms return navigation.
  • Real-Time Updates (Short Polling vs. Long Polling vs. SSE vs. WebSockets): Pushing "New posts available" banners and live reaction counts without shifting what the user is reading.
  • Media Upload & Variant Pipeline: Two-step presigned uploads, client-side EXIF stripping, and pre-computed vs. on-the-fly edge AVIF/WebP resizing.
πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.