You create Twitter's architecture by separating four concerns: ingestion of posts and interactions, storage of a huge social graph and timeline data, fan-out and ranking of feeds, and delivery of real-time updates to clients. The key condition is that no single design scales to Twitter's size — you start with a simple monolith, then split read and write paths, then shard and cache selectively as traffic grows. This guide walks through that progression in workable order, using stable engineering principles rather than current internal specifics.

Start With What the System Must Do, Not With the Tools

Twitter's public behavior hides a demanding workload. A user posts a short message; followers expect to see it soon; everyone expects a scrolling feed that feels chronological and personal; search and trends surface what's happening now; and counts of likes and reposts update quickly. Each of those expectations maps to a different architectural pressure.

Write traffic is modest compared with read traffic. A small percentage of users post at any moment, but every post is read many times, and each reader expects a fast load. Celebrity accounts break naive assumptions: a single post from an account with tens of millions of followers cannot be copied to every follower's inbox in real time without enormous write amplification. Meanwhile timelines must be assembled from multiple sources — followed accounts, recommendations, ads, and promoted content — and ranked.

Translate those behaviors into concrete requirements before drawing boxes. You need an identity and profile store, a write path that accepts posts and durable interactions, a social graph that answers "who follows whom" quickly in both directions, a timeline service that can serve a home feed in well under a second, a search index for recent content, and a fan-out mechanism that distributes posts. You also need counters, media handling, and notification delivery.

A useful starting version of the requirements is: a post must be readable by followers within a few seconds; a home feed request should return within a few hundred milliseconds; the graph must support both "who does this user follow" and "who follows this user" lookups; and the system must tolerate the failure of any single component without losing accepted posts. Notice these are design targets, not measured promises — you set them for your own build.

Draw the High-Level Layers First

Before any code, sketch layers. Twitter-style systems generally organize into these bands:

1: Client and edge layer — mobile and web apps, API gateways, authentication, rate limiting, CDNs for media, and connection handling for real-time streams. 2: Ingestion services — endpoints that accept posts, likes, reposts, follows, and deletions, validate them, and hand them to durable queues. 3: Core data services — the post store, the social graph store, the user/profile store, and the media store. 4: Derived services — timeline assembly, fan-out workers, ranking, search indexing, trend computation, and counters. 5: Delivery services — feed APIs, real-time push, notification dispatch, and caching layers close to the edge.

The important architectural decision at this stage is the direction of dependencies. Ingestion should write to durable storage and to queues; derived services should consume from those queues and build their own views. That way the write path stays simple and fast, and read-side complexity — fan-out, ranking, indexing — scales independently. If instead you compute everything synchronously on write, a single slow follower-count update can stall posting.

Sketch this as a diagram before writing code, and label each arrow with what data crosses it and how often. An arrow from ingestion to the graph service carrying "new follow event" is different from an arrow carrying "read follower list," and conflating them leads to the classic mistake of using one storage engine for both directions.

Build the Data Model Around the Social Graph and the Post Log

Two stores dominate the design. The post store is an append-mostly log of messages keyed by post ID, with author ID, timestamp, text, media references, and reply/thread links. Post IDs matter: using a sortable ID scheme (for example, a snowflake-style ID combining time, machine, and sequence) lets you order and paginate without a separate index on every query. Keep the canonical post row immutable except for deletion markers; edit history, if you support it, belongs in a separate versioned table.

The social graph is the harder store. It must answer two queries fast: the list of accounts a user follows (used to build their feed), and the list of followers of an account (used for fan-out and for follower counts). These are different access patterns. A common approach is two tables — a "following" edge table keyed by follower, and a "followers" edge table keyed by followee — each sharded so that one user's edges live together. For very large accounts, the follower list itself becomes a partitioning problem; you don't need every follower in one row group.

The counts deserve special treatment. Follower counts, like counts, and repost counts are read constantly and updated constantly. Compute them asynchronously from an event stream with aggregation, keep a cached value for reads, and reconcile periodically against the raw edge or interaction tables. Do not run a count query against a billion-row edge table on every profile view.

User profiles, media metadata, and interaction records (likes, reposts, replies, bookmarks) round out the core. Media should live in object storage with a CDN in front; the database should store only the reference and processing state.

Make Writes Cheap: Ingest, Validate, Persist, Publish

The write path is where you earn your read performance. A post request should do four things in order, and little else:

1: Authenticate and authorize at the edge, so downstream services trust a signed identity. 2: Validate the payload — length, media references, duplicate detection via an idempotency key supplied by the client. 3: Persist the post to the post store with a generated sortable ID and the author's timestamp. 4: Publish a post-created event to a durable queue or log, then respond with success.

Success means the post is durably stored and the event is durable — not that every follower has it. If you wait for fan-out before responding, posting latency becomes a function of follower count.

The same shape applies to likes, reposts, follows, and deletes: validate, persist the canonical fact, emit an event. Deletes are especially instructive — mark the post as deleted in the canonical store, emit a delete event, and let timeline caches, search indexes, and fan-out stores remove or filter it asynchronously. Hard-deleting everywhere synchronously is a recipe for inconsistency.

A success check here is simple: post once, then immediately query the post store by ID from a second process, and confirm the event appears in the queue. If either fails, the write path isn't ready for fan-out.

Choose a Fan-Out Strategy and Understand Its Costs

Fan-out is how a post reaches followers. There are two classic extremes, and real systems blend them.

Fan-out on write (push): when a post is created, a worker reads the author's follower list and inserts the post ID into each follower's timeline list in a timeline store. Reading a home feed becomes a single lookup of a precomputed list. Write cost scales with follower count, which is brutal for celebrities but excellent for ordinary users who read far more than they post.

Fan-out on read (pull): no per-follower insertion. When a user opens their feed, the timeline service reads the recent posts of everyone they follow, merges them by time or score, and returns the top slice. Write cost is trivial; read cost scales with the number of accounts followed, and a user following thousands of accounts pays heavily on every refresh unless cached.

The practical hybrid: fan-out on write for accounts below a follower threshold, fan-out on read for accounts above it. A feed request then merges the precomputed list with recent posts pulled from a small set of high-follower accounts the user follows. This is the standard fix for the celebrity problem, and its cost is a more complex read path and a tuning threshold that changes with hardware.

Make the trade-off concrete with an illustrative calculation. Suppose a user follows 500 accounts and refreshes 20 times a day. With pull, each refresh might read recent posts from 500 accounts — if you can't cache that, you pay 10,000 account-reads per user per day. With push, the same user's feed reads are one list lookup, and the write cost is spread across the authors. Now flip it: an account with 5 million followers posting once under pure push triggers 5 million timeline insertions for a single event. Those numbers are not from any real system; they illustrate why the threshold exists. A reasonable starting threshold for a small build might be a few thousand followers, then raise it as you measure.

Caching matters in both models. Keep each user's recent timeline in a fast store with a bounded length — say the most recent few hundred entries — and let older entries be reconstructed from the post store. Bounded timelines cap memory and make invalidation on delete manageable.

Design Timeline Assembly and Ranking as a Separate Service

The timeline service should be its own component, consuming from the fan-out stores and the post store, and producing a ranked page on demand. Separate the stages:

Candidate generation: gather post IDs from the precomputed timeline, from pulled high-follower accounts, from recommendations, and from ads. Candidates carry minimal metadata at this stage. Hydration: fetch post content, author info, media, and social proof for the candidate IDs in batch. Batch fetching is essential — one query per candidate will dominate latency. Filtering: remove deleted posts, blocked authors, muted keywords, and already-seen duplicates. Ranking: score candidates. Chronological ordering is a valid and cheap baseline; a learned ranker adds engagement prediction and recency weighting but brings training pipelines, feature stores, and evaluation into scope. Assembly and pagination: return a page with a cursor, not an offset, because offsets break when new posts arrive.

Build chronological first. It gives you a correct feed and a baseline against which any ranker can be measured. Add ranking only when you have the instrumentation to evaluate it — impressions, engagement, and the ability to run a controlled comparison. Treat the ranker as an optional layer behind a flag, so the chronological path remains a fallback.

A check for this stage: load a feed for a test account following a mix of ordinary and high-follower accounts, delete one of the posts, and refresh. The deleted post should vanish and the page cursor should still return consistent results.

Real-time behavior in a Twitter-style system takes several forms, and each has a modest architectural footprint if you keep it event-driven.

Live updates: clients can poll the feed endpoint on a timer, or hold a long-lived connection and receive new post IDs pushed as fan-out completes. Start with polling — it's simpler and cache-friendly — and add streaming when you need lower latency. Push more IDs than the client will display, and let the client decide whether to insert them into the visible feed or show a "new posts" banner.

Search: a separate indexing pipeline consumes post events and writes to a full-text index sharded by time or by ID range. Recent-content search and historical search have different freshness needs; many designs keep a fast recent index and a slower comprehensive one. Search results must respect deletions and visibility rules, so the indexer needs the same filter logic as the timeline.

Trends: aggregate hashtags and terms from a sliding window of post events, counting with approximate methods if the volume is high. Trends are a derived view; losing a few minutes of trend data is acceptable, which lets you use cheaper, eventually consistent computation.

Notifications: a fan-out-like pipeline that emits events for mentions, replies, follows, and liked posts, deduplicated and rate-limited so one popular post doesn't notify a user repeatedly.

Counters: as noted, aggregate from events with a cache in front, and reconcile on a schedule. Keep the raw interaction tables so counts can be rebuilt.

These services all read from the same event stream, which is the payoff of the write path design: adding a new derived view doesn't touch ingestion.

Scale Storage Deliberately: Sharding, Replication, and the Read Path

You don't shard on day one. Start with a single relational database for posts, users, and edges, plus a cache. Introduce sharding when a table's write throughput or size exceeds what one machine handles comfortably, and shard by the key that matches your dominant access pattern: posts by author or by ID range, edges by the user whose list you read.

Replication follows: keep multiple copies of each shard, route reads to replicas where staleness is acceptable, and keep critical reads — like your own freshly posted content — on the primary or on a read-your-writes path. For the timeline store, replication is mostly about availability; losing a cached timeline is recoverable by rebuilding from the post store.

The read path deserves its own budget. A home feed request should hit: an auth check at the edge, a timeline cache lookup, a batched hydration of post and author data (itself cached), and assembly. Media never passes through your API servers — clients fetch it from the CDN. If a feed request is making dozens of small database calls, the architecture is wrong, not the database.

Failure handling is part of the storage design. Accepted posts must survive the loss of a queue consumer; that means the queue must be durable and consumers must be idempotent, since events will be delivered more than once. Fan-out workers should record progress so a restart resumes rather than re-inserting everything. Idempotency keys on writes prevent duplicate posts from retries.

Build in an Order That Keeps the System Testable

The sequence below is a workable order for a single engineer or small team. Prerequisites: a chosen language and web framework, a relational database, a cache, a durable queue, object storage for media, and a way to run more than one process.

1: Identity and profiles. Users, sessions, and profile records. Success check: sign up, log in, and fetch a profile. 2: Posts and the follow graph. The post store with sortable IDs, the two edge tables, and the endpoints to create posts and follow accounts. Success check: create two users, follow, post, and read the post by ID. 3: Naive pull feed. A timeline endpoint that reads recent posts from followed accounts and merges them. This is your correctness baseline. 4: Event stream and derived consumers. Publish post and follow events; add a counters consumer and a notification consumer. Success check: follower counts change without synchronous updates. 5: Push fan-out with a threshold. A fan-out worker maintains bounded per-user timeline lists for accounts below the threshold; the feed endpoint merges these with pulled high-follower accounts. Success check: a post from a normal account appears in a follower's feed after fan-out completes, and a post from a high-follower test account appears via the pull path. 6: Caching and batching. Cache hydrated posts and author records; batch all hydration queries. Success check: measured feed latency drops and database query counts per request are bounded. 7: Search indexing. Consume post events into a full-text index; filter deleted and blocked content. Success check: a new post is searchable within your freshness target, and a deleted post disappears. 8: Real-time delivery. Add polling first, then a streaming channel if needed, with a "new posts" indicator. Success check: a new post from a followed account surfaces without a manual refresh. 9: Observability and load testing. Emit metrics for write latency, fan-out lag, feed latency percentiles, cache hit rates, and queue depth. Load-test with a synthetic graph that includes a few high-follower accounts.

Each step should be deployable and reversible. Stop and reconsider if fan-out lag grows without bound, if feed latency percentiles degrade as follower counts grow, or if a single shard saturates — those are signals to revisit sharding, thresholds, or batching, and further work at that point may warrant a dedicated data-platform engineer rather than incremental patching.

Common Failure Modes and What They Teach

The instructive failures in this architecture cluster around a few themes. Treating a derived view as the source of truth is the worst: if timelines are the only place a post exists, a cache loss becomes data loss. Always be able to rebuild derived views from canonical stores and the event log.

Synchronous fan-out is the second trap. If posting waits for follower insertion, a single large account can stall the write path; the threshold hybrid exists precisely to keep write latency independent of follower count.

Unbounded timelines are the third. A timeline list that grows forever consumes memory and makes deletion expensive. Cap it and reconstruct older history on demand.

Finally, offset pagination and non-idempotent consumers cause subtle, hard-to-reproduce bugs: duplicates in feeds, skipped posts, and inconsistent pages. Cursors, idempotency keys, and progress tracking are cheap insurance.

What This Design Does and Doesn't Cover

This blueprint gives you a correct, scalable skeleton: cheap writes, event-driven derived views, a hybrid fan-out that handles celebrities, batched hydration, bounded caches, and separable search and notification pipelines. It deliberately leaves out details that depend on your constraints — exact shard counts, the ranking model, media transcoding, abuse detection, and region-specific compliance. Those are extensions, not foundations.

The honest limit is that real systems evolve under measurement, not blueprint. The thresholds and cache sizes here are starting points; the architecture is right when the write path stays simple, derived views are rebuildable, and each new feature attaches to the event stream rather than to the write path. Build chronologically, measure, and split only where the numbers demand it.