Case Study: LinkedIn
"A log is perhaps the simplest possible storage abstraction. It is an append-only, totally-ordered sequence of records ordered by time." — Jay Kreps, The Log: What every software engineer should know about real-time data's unifying abstraction, LinkedIn Engineering (2013)
Summary: LinkedIn is an unusually well-documented system: its own engineering blog and a 2011 paper describe how one commit log (Kafka) became the spine that connects an online database (Espresso), change capture (Databus, Brooklin), stream processing (Samza), derived-data stores (Venice, Pinot), search (Galene, Cleo), a feed (FollowFeed), a graph database (LIquid), services (Rest.li, D2), caches (Couchbase), ML tooling (Pro-ML, Frame) and auto-remediation (Nurse). Focus: The 4-step method (scope, estimate, high-level design, decisions) applied to what LinkedIn says about itself, one concept block per subsystem, a dated "what changed over time" timeline, and a map from each subsystem to the generic chapters of this site. Learning goal: Explain why each LinkedIn subsystem exists in terms of the problem that forced it, separate what the company published from what is our inference, and reuse the transferable ideas (log as spine, derived data, over-partitioning, client-side discovery) with small tested Go and Laravel code.
This chapter reads LinkedIn's own posts and paper and nothing else. Every architecture claim cites a post or paper that was fetched and read; short quotes are marked with the post. Anything we infer, generalise or compute ourselves is labelled inference. The code under Go and Laravel is our own small re-implementation of mechanisms the posts describe; it is not LinkedIn's code and makes no claim about how LinkedIn implements them. The method is from The 4-Step Approach; the generic mechanics live in the sibling chapters linked in What you can copy.
Page map
| If you are looking for | Go to |
|---|---|
| The page in four tables | Everything in one minute |
| What a case study here may and may not claim | Why it exists |
| Dated posts and what changed | Where it comes from |
| Step 1: what the posts say the product needs | Step 1: scope |
| Step 2: numbers from the posts and our estimates | Step 2: estimate |
| Step 3: the overall picture | Step 3: high-level design |
| Kafka and the log | Kafka and the commit log |
| Databus, Brooklin | Change capture: Databus and Brooklin |
| Samza | Stream processing: Samza |
| Espresso, Voldemort, Venice | Online and derived data stores |
| Pinot | Real-time OLAP: Pinot |
| FollowFeed | The feed: FollowFeed |
| Galene, Cleo | Search and typeahead |
| LIquid | The graph: LIquid |
| Rest.li, D2, Deco | Serving: Rest.li and D2 |
| Couchbase | Caching |
| Pro-ML, Frame | Machine learning platform |
| Nurse | Reliability: Nurse |
| Step 4: the decisions as a table | Step 4: decisions |
| Which generic chapter to read | What you can copy |
| Code | Go, Laravel |
| Numbers, lab | Mechanics, Lab |
| Wrong beliefs, summary, quiz, terms, sources | Misconceptions, Cheat sheet, Self-check, Glossary, References |
Everything in one minute
The spine in one sentence. LinkedIn's posts describe a pattern: writes land in an online store, a change stream leaves that store, a commit log (Kafka) carries it, and many derived systems (search, feed, analytics, caches, ML features) are built from the log.
| Subsystem | What it is, from the company's posts | First dated source |
|---|---|---|
| Kafka | Distributed commit-log messaging system built for log processing | NetDB paper, June 2011 |
| Databus | Change data capture system, in production in its latest revision since 2011 | Open-sourcing post, Feb 2013 |
| Samza | Stream processing framework on top of Kafka and YARN | Post, Sep 2013 |
| Espresso | Online, distributed, fault-tolerant NoSQL document store; MySQL storage nodes | Post, Jan 2015 |
| Pinot | Real-time analytics; a derived data store with columnar storage | Post, Jun 2015 |
| FollowFeed | Feed infrastructure with fan-out on read; replaced Sensei | Post, Mar 2016 |
| Brooklin | Streaming bridge between stores and messaging systems; in production since 2016 | Post, Jul 2019 |
| Venice | Derived-data platform; in production since the end of 2016 | Post, Sep 2022 |
| Galene, Cleo | Search architecture (2014) and typeahead library (2012) | Posts, Jun 2014 and Mar 2012 |
| LIquid | Graph database for the economic graph | Post, Jul 2020 |
| Rest.li, D2 | REST+JSON framework and dynamic discovery with client-side load balancing | Post, Feb 2013 |
| Couchbase | Caching tier, adopted in 2012 | Post, Dec 2017 |
| Pro-ML, Frame | Machine learning platform and feature system | Post, Jan 2019 |
| Nurse | Auto-remediation platform | Post, Jul 2015 |
The 4-step backbone.
| Step | Question | Where on this page |
|---|---|---|
| 1. Scope | What does the product need, per the posts? | Step 1 |
| 2. Estimate | What numbers does the company publish; what can we derive? | Step 2 |
| 3. High-level design | Which boxes, which arrows? | Step 3 and the per-subsystem blocks |
| 4. Decisions | What was chosen, what was rejected, why? | Step 4 |
Numbers the posts publish.
| Quantity | Value | Source |
|---|---|---|
| Kafka messages per day | more than 7 trillion | Kafka 2019 post |
| Kafka clusters / brokers / topics / partitions | over 100 / over 4,000 / over 100,000 / over 7 million | Kafka 2019 post |
| Brooklin | over 2 trillion messages per day | Brooklin 2019 post |
| Venice datasets / applications | more than 1,800 / over 300 | Venice 2022 post |
| LIquid | 270 billion edges, 2 million queries per second | LIquid 2023 post |
| Profile reads at peak | over 4.8 million per second | Profile cache 2023 post |
| FollowFeed vs Sensei | p99 feed latency down fivefold, index 20 times larger, half the servers | FollowFeed 2016 post |
| Fan-out on write vs read, data size | 62 times greater with fan-out on write | FollowFeed 2016 post |
Why it exists
A case study is useful only if the reader can tell what is evidence and what is story. LinkedIn is a good subject because the company wrote down the reason for each system, often including what it replaced.
| Weak case study | This chapter |
|---|---|
| "LinkedIn uses X" with no date or source | A dated post or paper for each claim |
| Numbers repeated from memory | Numbers copied from the post, with its date |
| Our guess presented as company fact | Marked inference |
| Architecture as a finished picture | Architecture as a sequence of problems and replacements |
Everyday picture. A city that grew from a village: the first road (one monolith called Leo) worked until traffic forced a ring road (services), a bus network (Kafka), and later separate post offices for different kinds of mail (derived stores). The posts tell you why each was built after the one before it hurt.
Three common misunderstandings, up front
- "LinkedIn is a Kafka company, so copy Kafka." The posts say Kafka was built to replace many custom pipelines; the lesson is the log as an integration layer, not the product.
- "Their numbers are our targets." A 7 trillion messages per day figure says nothing about what a 10,000 message per second system needs; see Step 2.
- "A blog post is the current architecture." Posts are dated snapshots; a system described in 2013 may be retired or replaced by 2022 (the Venice post says it gradually replaced Voldemort).
Where it comes from
What changed over time, from dated posts and the 2011 paper.
| Date | Event (as the source states it) | Source |
|---|---|---|
| 2003 | LinkedIn starts; 2,700 members in the first week | Scaling history post (2015) |
| 2005 | Databus originally developed | Databus post (2013) |
| 2011-06 | Kafka paper at NetDB 2011: in production at LinkedIn for more than 6 months | Kafka paper |
| 2011 | Databus latest revision in production; Espresso requirements written; "Inversion" initiative starts late in the year | Databus, Espresso, history posts |
| 2012 | Couchbase first adopted; Cleo open-sourced (March) | Couchbase 2017 post, Cleo post |
| 2013 | Rest.li open-sourced (Feb), Databus open-sourced (Feb), Samza (Sep), The Log (Dec) | respective posts |
| 2014 | Galene search architecture (Jun); profile moved from Oracle to Espresso; Nurse implementation started in April | Galene, profile cache, Nurse posts |
| 2015 | Espresso post (Jan), Pinot open-sourced (Jun), history post (Jul): over 750 services, Kafka over 500 billion events per day | respective posts |
| 2016 | FollowFeed (Mar) replaces Sensei; Brooklin in production | FollowFeed, Brooklin posts |
| 2016 | Venice in production at the end of the year | Venice post |
| 2017 | Couchbase: over 10 million queries per second, over 200 clusters; Pro-ML started in August | Couchbase, Pro-ML posts |
| 2019 | Kafka over 7 trillion messages per day (Oct); Brooklin open-sourced (Jul); Pinot joins Apache Incubator (Mar) | respective posts |
| 2020 | LIquid post series (Jul) | LIquid post |
| 2022-2023 | Venice open-sourced (Sep 2022); LIquid at 270 billion edges and Couchbase as the profile cache tier (May 2023) | Venice, LIquid, profile cache posts |
Timeline: the problem that forced each step (each line cites a post)
1 2003-2008 one app, "Leo"; separate in-memory graph service "Cloud"; Lucene search service (history post)
2 ~2008-2010 replica read DBs fed by the earliest Databus; "Kill Leo" -> services (150 by 2010) (history post)
3 2011 many custom pipelines -> Kafka as "universal pipeline"; paper at NetDB (history post, paper)
4 2013-2016 open-sourced pieces: Rest.li, Databus, Samza, Pinot; Espresso replaces Oracle for profile (posts)
5 2016-2019 derived data at scale: Venice, Brooklin; Kafka at 7 trillion messages per day (posts)
6 2020-2023 graph database LIquid; Couchbase tier added in front of Espresso for profile reads (posts)The Venice and profile-cache posts show that systems are replaced. The Venice post says it has been "gradually replacing many other systems, including Voldemort and several proprietary ones". The 2015 history post says "Over time, we actually removed many mid-tier caches", while the 2023 profile post adds a Couchbase tier back in front of Espresso; the difference is in what they cache and where (see Caching).
The concept catalogue
Step 1: scope
The posts do not publish one requirements list. They give requirements per system. We collect them here and label our grouping as inference.
| Product need | Evidence in the posts | System that answers it |
|---|---|---|
| Move data between many systems without N-by-M pipelines | History post: many custom pipelines for data warehouse, Hadoop, logs, tracking events, InMail, search updates | Kafka |
| Keep search and caches current with the primary database | Databus post: search index must continually index the primary database | Databus, later Brooklin |
| Fast online reads and writes for member data | Espresso post: profile, InMail, homepage | Espresso |
| Interactive analytics for members and customers | Pinot post: Who Viewed My Profile, ads analytics | Pinot |
| A feed that is relevant and fast | FollowFeed post: wider distribution and improved relevance | FollowFeed |
| Search over people, jobs, companies | Galene post: 300M+ members, personalised results | Galene, Cleo |
| Second-degree connections in human real time | LIquid post | LIquid |
| Many services with a consistent API | Rest.li post | Rest.li, D2 |
Inference: the common theme is "one write, many reads in different shapes", which is why the spine is a log plus derived stores.
Step 2: estimate
Published numbers are in Everything in one minute. The arithmetic below is ours and is labelled.
| Derived quantity | Calculation | Value | Label |
|---|---|---|---|
| Average Kafka message rate | 7 trillion / 86,400 s | about 81 million messages per second | inference (arithmetic on a post figure) |
| Partitions per broker | 7 million / 4,000 | about 1,750 on average | inference |
| Messages per partition per day | 7 trillion / 7 million | about 1 million | inference |
| Profile reads that reach Espresso at 99% cache hit | 4.8 million x 1% | about 48,000 per second | inference; assumes the hit rate applies at peak |
| FollowFeed partitions per node | 720 / 40 | 18 | inference from the 720 figure in the post |
| Second-degree write amplification | about 250 first-degree connections | roughly 250 times the base write rate | stated in the LIquid post |
Two lessons carry over. First, the average hides peaks; see Capacity Estimation for the method and Capacity Planning & Disaster Recovery for headroom. Second, the per-partition rate (about a million messages per day in our arithmetic) is small, which is why partition count, not broker speed, is the scaling lever in the post.
Step 3: high-level design
The picture is our synthesis of several posts (the Espresso post says Databus carries its change stream to downstream consumers; the Kafka 2019 post lists Brooklin for mirroring; the Pinot post says it ingests from Hadoop and Kafka). The exact wiring for any one product is simplified: inference.
Sequence: one profile edit travels through the spine (assembled from the posts; exact hops are inference)
1 member edits profile -> Profile backend serializes to Avro -> Espresso router -> storage node (MySQL)
2 MySQL binlog -> change capture (Databus / Brooklin) -> change event with SCN
3 consumers: search index update, cache updater (Samza job), downstream derived stores
4 next read: Espresso router -> cache tier (Couchbase) -> storage node on a missKafka and the commit log Must-know
In plain words: Kafka is an append-only log per partition. Producers append; consumers read from an offset they remember; many consumers can read the same data independently.
Common misunderstanding: "Kafka is a queue that deletes messages when read." In the paper the broker does not track consumption: "the information about how much each consumer has consumed is not maintained by the broker, but by the consumer itself" (NetDB paper). Messages are removed by retention, not by being read.
Definition: A topic is divided into partitions; each partition is a logical log stored as segment files; consumers pull by offset; a consumer group splits partitions among its members (paper, section 3). The 2013 The Log post generalises this: the log gives each record a position that works as a timestamp independent of any physical clock. See Kafka for the full mechanics.
Timeline: Kafka at LinkedIn, only dated facts
1 2011-06 NetDB paper: pull model, partitions as logs, consumer groups, at-least-once, hundreds of GB per day
2 2013-12 "The Log" post: the log as the unifying abstraction for data integration
3 2015-07 history post: "well over 500 billion events per day"
4 2019-10 7 trillion messages per day; 100+ clusters; LinkedIn release branches suffixed -li, open-sourced| Property | What the paper / post says | Source |
|---|---|---|
| Pull vs push | "At LinkedIn, we find the 'pull' model more suitable for our applications" | NetDB paper |
| Delivery | "In general, Kafka only guarantees at-least-once delivery." | NetDB paper |
| Partition layout | Each partition is a log of segment files, about 1 GB each in the paper's example | NetDB paper |
| Scale in 2011 | "hundreds of gigabytes of new data each day" | NetDB paper |
| Scale in 2019 | "recently surpassed 7 trillion per day" | Kafka 2019 post |
| Operations | Kafka ecosystem includes a REST proxy, schema registry (Avro), Brooklin for mirroring, Cruise Control, an audit called Bean Counter | Kafka 2019 post |
| Patch policy | Release branches are not a fork; "upstream first" or "LinkedIn first" hotfix with double-commit attempt | Kafka 2019 post |
Real scenarios (from the posts): activity tracking, metrics, message exchange (Kafka 2019 post); keeping the people search system updated after a profile change (history post).
Fix / how to use it: the transferable idea is a durable, replayable log between producers and many independent consumers. The Go code in this chapter's relay package models a bounded log with a checkpoint-based consumer; the sibling Kafka chapter owns producer, consumer-group and replication mechanics.
Change capture: Databus and Brooklin Must-know
In plain words: instead of every system asking the database "what changed?", the database's own commit order is turned into a stream that search, caches and replicas subscribe to.
Common misunderstanding: "Change capture is just reading the table again every minute." Databus "preserves transactional guarantees of the source database and delivers change events grouped in transactions, in source commit order" (Databus post).
Definition: A relay pulls changes from a primary store into an in-memory log; consumers pull from the relay; a bootstrap service provides a consistent snapshot to consumers that are new or too far behind. The Databus post states: "Originally developed in 2005, Databus has been in production in its latest revision at Linkedin since 2011". Brooklin generalises the idea: "running in production at LinkedIn since 2016, powering thousands of data streams and over 2 trillion messages per day" and it replaced Kafka MirrorMaker at LinkedIn (Brooklin post). See Change Data Capture.
Timeline: a consumer falls behind (Databus post, shape only)
1 consumer checkpoint at SCN 100; relay holds SCN 180..260
2 consumer asks for events after 100 -> not in the relay's log
3 relay answers with a consolidated snapshot of changes since 100 (post: "delivered a consolidated snapshot")
4 new consumer with no data -> Bootstrap service gives a point-in-time snapshot, then catches up from the relay| Feature (Databus post) | Meaning |
|---|---|
| Source-independent | Oracle adapter open-sourced; MySQL adapter planned in 2013 |
| Transactional in-order delivery | Events grouped by transaction, in source commit order |
| Low latency | Milliseconds from source availability |
| Infinite lookback | Bootstrap service for new or slow consumers |
| Server-side filtering | Consumers can retrieve specific partitions |
| Brooklin (2019 post) | Meaning |
|---|---|
| Streaming bridge | Moves data between stores (Espresso, Oracle) and messaging (Kafka, Event Hubs, Kinesis) |
| Multitenancy | One cluster serves many pipelines; MirrorMaker needed a cluster per pipeline |
| Dynamic provisioning | Pipelines created or modified with an HTTP call to a REST endpoint |
| Diagnostics | REST endpoint returns per-partition lag and errors |
Real scenarios: search index kept in sync with the primary database (Databus post); mirroring Kafka between data centers and to Azure (Brooklin post).
Fix / how to use it: transferable lesson is an ordered change stream with a snapshot fallback; the relay package is a tested miniature of that shape.
Stream processing: Samza Important
In plain words: jobs that read Kafka topics continuously, keep local state, and write results to other topics.
Common misunderstanding: "Stream processing replaces the database." The Samza post gives the analogy that "Kafka plays a role similar to HDFS and Samza a role similar to MapReduce": a processing layer over a log, not a store of record.
Definition: Samza is described in the 2013 post as a lightweight framework that builds on Hadoop YARN for distributed execution; processors may "accumulate a significant amount of state" such as counts per member id. See Stream Processing.
Timeline: Samza in the posts
1 2013-09 post: open sourced; at that time "over 26 billion unique messages per day" in Kafka feeds
2 2019-01 Pro-ML post: nearline scoring "in Samza"
3 2023-05 profile cache post: cache updater and bootstrapper are Samza jobs reading Brooklin streams| Use | Source |
|---|---|
| Counts and aggregations by member id | Samza post |
| Nearline model evaluation | Pro-ML post |
| Cache updates from Espresso change events | Profile cache post |
Online and derived data stores: Espresso, Voldemort, Venice Must-know
In plain words: one store takes the live writes and is the source of truth (Espresso). Other stores are built from its output or from batch jobs and exist only to answer reads fast (Venice, Pinot).
Common misunderstanding: "A derived-data store needs its own replication, backup and transaction story." Pinot's post chose the opposite: it was designed "as a derived data store", accepting "a few seconds of data freshness" in exchange for simplicity. Venice is "eventually-consistent" by its own description.
Definition (Espresso, 2015 post): hierarchy database, table, collection, document; documents are Avro; the leading key is the partitioning key; router hashes the partition key to pick a storage node; storage nodes use MySQL (InnoDB) as the storage engine; Helix computes partition placement; each partition has one master. Per the post: "Every partition must have only 1 master." Secondary indexes are updated synchronously with the base data. The change stream goes out through Databus.
Timeline: Espresso write and read (Espresso post, simplified)
1 client -> router: parse URL, hash partition key (MailboxID)
2 router -> storage node holding the master of that partition
3 storage node: MySQL transaction, index update, binlog
4 binlog -> Databus -> search index / caches / remote data centers
5 read: master for read-after-write, replica for eventually consistent reads (the post lists both as requirements; routing detail is inference)| System | Role | Source says | Source |
|---|---|---|---|
| Oracle (RDBMS) | earlier primary store | schema evolution and shard provisioning were manual and costly | Espresso post |
| Voldemort | key-value store | for apps needing key-value access but not a timeline-consistent change stream | Espresso post |
| Espresso | primary, strongly consistent document store | about 30 applications in 2015 | Espresso post |
| Venice | derived data | "more than 1800 of our datasets", over 300 applications | Venice post |
| Venice write path | Meaning |
|---|---|
| Push Job (full) | Loads a new version of the dataset from Hadoop in the background, then swaps reads; the previous version is kept for rollback |
| Incremental push | Adds data to the existing dataset |
| Streaming writes | Nearline writes, for example from Samza |
| Hybrid | Replay phase puts recent nearline writes on top of a newly loaded version before the swap |
| Partial updates | Mutate some columns without read-modify-write, because all writes are asynchronous |
| Venice read path | Meaning |
|---|---|
| Single Get / Batch Get | Key lookups; the feed uses batch gets; 45M key lookups per second at peak |
| Read Compute | Server-side arithmetic on embeddings, 46M lookups per second at peak |
| Da Vinci | A client library that keeps partitions locally and updates from the changelog |
Real scenarios: People You May Know and Jobs You May Be Interested In use Venice (Venice post); profile storage moved from Oracle to Espresso in 2014 (profile cache post).
Fix / how to use it: SQL below shows an Espresso-style hierarchical table; read Wide-Column & Key-Value at Scale and SQL vs NoSQL for the general decision.
Real-time OLAP: Pinot Important
In plain words: a database that answers "slice and dice" questions over billions of rows in milliseconds, fed from Kafka and Hadoop rather than written to directly.
Common misunderstanding: "Fast analytics means pre-computing every answer." The Pinot post names pre-materialised data cubes as an alternative that "comes with additional storage footprint", and chose columnar storage with a SQL-like query language instead; joins were left out: "Currently we do not support joins in order to ensure predictable latency."
Definition: Pinot is a "scalable distributed OLAP data store" (2019 post) with servers that host segments, brokers that route queries, and controllers that assign segments; Helix is the control plane. Requirements stated in 2015: ingest billions of events per day, serve thousands of queries per second, millisecond latency for site-facing apps, data freshness of a few seconds. See OLTP vs OLAP & Columnar Storage.
Timeline: Pinot
1 2014-09 introduced as LinkedIn's real-time analytics infrastructure
2 2015-06 open sourced; 25+ member and customer products, 30+ internal products; 400+ experiments daily on XLNT
3 2019-03 joins Apache Incubator; 50+ site-facing use cases; thousands of QPS, tens to hundreds of ms| Component | Role (2019 post) |
|---|---|
| Pinot Server | Hosts data segments, serves queries from them |
| Pinot Broker | Accepts queries, routes to servers, merges results |
| Pinot Controller | Manages components, assigns segments to servers |
| Hadoop | Source of truth for fact data, used to re-bootstrap |
| Kafka | Real-time ingestion |
Real scenarios: Who Viewed My Profile, Talent Insights, ads and job-posting analytics, the XLNT A/B testing platform, ThirdEye metric monitoring (Pinot posts).
The feed: FollowFeed Must-know
In plain words: to show a member's feed, gather recent items from the people, companies and schools they follow and rank them.
Common misunderstanding: "Big feeds always precompute each user's timeline." The generic chapter Feeds presents both models. LinkedIn's own post evaluated both and chose fan-out on read: "In our experiments, we found out that data size with this model was 62 times greater than pull based architecture." The second reason was feed ranking: a pre-materialised feed is stored in the order a relevance model chose, so changing the model means rewriting every stored feed.
Definition: FollowFeed keeps a timeline per entity (member, company, school), a chronologically ordered list of records. A broker routes a viewer's request to index nodes; nodes score locally (computation moves to data) and the broker merges. Timelines live in RocksDB, partitions number 720, ingestion is asynchronous through Kafka and a Partitioner service, and the system is eventually consistent. Result: "a fivefold reduction in feed query's 99th percentile latency", 20 times larger index, half the servers compared with Sensei.
Timeline: why Sensei was replaced (FollowFeed post)
1 Sensei: Lucene-based, in-memory inverted index, BQL queries, broker fans out to all searcher nodes
2 growth: members 200M -> 400M+ in three years; denser graph; heavier ranking
3 problems: memory-bound index, code complexity (Bobo, Norbert, Zoie), shrinking leverage after Galene, "senescence"
4 FollowFeed: fan-out on read, over-partitioned RocksDB timelines, code-generated scoring| Decision (FollowFeed post) | Choice | Reason in the post |
|---|---|---|
| Where computation runs | On nodes holding the data | Large record sets feed relevance; remote fetches add latency |
| Fan-out strategy | Fan-out on read | 62x data with fan-out on write; model rollouts require rewriting every stored feed |
| Partition count | 720, over-partitioned | Divisible by many numbers; moving whole partitions avoids splitting |
| Storage | RocksDB, JNI binding contributed back | Embeddable key-value store tuned for SSDs |
| Serialization | Avro with schema registry on the node | Schema versions needed to read old data |
| Ingestion | Kafka plus Partitioner | Re-partitions to match the index partition range |
| Multi data center | Sticky routing; cluster size follows read share | Serve a viewer from the local data center |
Fix / how to use it: the overpartition Go package and the Laravel PartitionRouter and FeedReader re-implement over-partitioning, rebalancing by whole partitions and the scatter-gather read. Inference: the choice would flip for a product with a small follower count and no learned ranking; use Feeds to decide with numbers.
Search and typeahead: Galene and Cleo Must-know
In plain words: search finds documents for a query; typeahead answers after each keystroke from a smaller, faster index.
Common misunderstanding: "Search is one index." The Galene post lists a pre-Galene stack of many parts: Lucene, Sensei for sharding, Zoie for live updates, a Search Content Store, Bobo, Cleo, Krati, Norbert. It says "Our approach to scaling the system was reactive, often narrowly focused" and that this "hit a wall".
Definition (Galene, 2014): a redesign that moves index building to offline map-reduce jobs and separates infrastructure tasks from relevance tasks. Cleo (2012) is a library for "partial, out-of-order, real-time typeahead": "Cleo can do out-of-order prefix matching over a very large number of elements by means of in-memory scanning", using an inverted index, a Bloom filter, a forward index and external scores. For members' network typeahead it reports "~20 milliseconds on average". See Search Systems and Bloom Filters.
Timeline: Cleo query "linked" (Cleo post walkthrough)
1 partition takes prefix "link" (max length 4) -> inverted list of document ids
2 for each id, check the 8-byte bloom filter against the query's bloom bits
3 on a potential hit, consult the forward index so every query term is a prefix of an indexed term
4 return true hits with external scores; hits from all partitions are merged| Typeahead kind (Cleo post) | Behaviour |
|---|---|
| Generic | Same query gives the same results for every member; ordered by a global ranking such as popularity |
| Network | Results filtered by the member's 1st and 2nd degree connections; PYMK scores rank results |
| Galene pain point (2014 post) | Direction |
|---|---|
| Rebuilding a complete index is extremely hard | Index building moves to offline map-reduce jobs |
| Reactive stacking of components | One redesigned architecture |
| Relevance engineers tied up in infrastructure | Clear separation of infrastructure and relevance tasks |
Fix / how to use it: the typeahead Go package and the Laravel TypeaheadIndex implement the same three-stage filter; they are teaching code, not Cleo.
The graph: LIquid Important
In plain words: a database for relationships, built so that "friends of friends" is a fast lookup instead of a huge join.
Common misunderstanding: "Just precompute second-degree connections." The post explains why not: "the set of second degree connections is too large to pre-materialize and store", and keeping it current would cost "roughly 250 times the base write rate".
Definition: LIquid is described as a graph database "to support human real-time querying of the economic graph" with a relational model, a Datalog-based query language and in-memory, wait-free index structures. Edges are triples (subject, predicate, object). Earlier systems were "increasingly general-purpose graph serving systems", the first storing (source, dest, score). See Graph Databases.
Timeline: the graph at LinkedIn
1 early years: in-memory member graph service "Cloud" feeds a Lucene search service (history post, 2015)
2 2014-2018: team builds LIquid for four years (LIquid part 1, 2020)
3 2020-07: LIquid replaces hand-coded queries that added hundreds of ms to page loads
4 2023-05: 270 billion edges, 2 million queries per second, expected to double in 18 months| Fact | Source |
|---|---|
| 2nd degree network is typically at least 50,000 entities | LIquid part 1 |
| Interface is declarative, Datalog-based | LIquid part 1 |
| 270 billion edges; 2M queries per second | LIquid 2023 post |
Serving: Rest.li, D2 and the services Must-know
In plain words: many teams, one API style, and clients that find servers without a central load balancer.
Common misunderstanding: "Microservices were the plan from day one." The history post says LinkedIn began as one application, Leo, and "Kill Leo" was the internal mantra "for many years"; by 2010 it had "over 150 separate services" and by 2015 "over 750 services".
Definition: Rest.li (2013) is "a REST+JSON framework for building robust, scalable service architectures using dynamic discovery and simple asynchronous APIs", with R2 as the transport layer and D2 as "our dynamic discovery and client-side load balancing layer" using ZooKeeper as the registry. Deco is named in this chapter's scope but no company blog post on it was fetched, so no claim is made about it here. See Service Discovery, REST API Design, Microservices Architecture.
Timeline: serving architecture
1 2003-2008 Leo monolith; first service is the member graph "Cloud" (Java RPC)
2 2009-2012 services extracted; Inversion pause in late 2011 for tooling and deployment
3 2013-02 Rest.li open sourced: new services use it, existing ones migrated
4 2015-07 over 750 services; mid-tier caches removed where they stored derived multi-domain data| Layer | Role (Rest.li post) |
|---|---|
| Rest.li | Resource modelling, IDL, batch operations, type-safe clients, compatibility-checked evolution |
| R2 | Asynchronous REST transport (Netty-based HTTP implementation) |
| D2 | Registry lookup in ZooKeeper, client-side load balancing, avoids overloaded servers |
Caching Important
In plain words: keep hot reads in a fast tier so the primary store does less work.
Common misunderstanding: "More cache layers is always better." The 2015 post says mid-tier caches stored "derived data from multiple domains" and "the complexity around invalidation and the call graph was getting out of hand"; it recommends keeping "the cache closest to the data store as possible".
Definition: Couchbase was "first adopted at LinkedIn in 2012" and by 2017 "handles over 10 million queries per second with over 200 clusters" (2017 post). In 2023 it became a cache tier for the profile datastore: ">99% read and <1% write" traffic, "a cache hit rate of over 99%, reduced tail latencies by more than 60%". Updates are ordered by SCN with last-writer-wins and tombstones for deletes. See Caching.
Timeline: profile reads (profile cache post)
1 before 2014: memcached read cache over Oracle; problems on expansion, replacement, warm-up
2 2014: migrate to Espresso; no read cache needed, scale by adding nodes
3 hitting limits of shared Espresso components
4 2023: Couchbase tier in the storage layer; Samza jobs apply Brooklin change events; SCN decides which write wins| Problem in the post | Mechanism |
|---|---|
| Stale record inserted by a racing writer | Compare SCN; largest SCN replaces the existing record |
| Deleted record resurrected | Tombstone records instead of hard deletes |
| Cache drifting from the source of truth | Periodic bootstrap within the TTL |
| Miss due to expired TTL | Update cache from the storage node's response if its SCN is the same or greater |
Machine learning platform: Pro-ML and Frame Good to know
In plain words: one shared toolchain so non-specialists can build and run models, and a shared catalogue of features.
Common misunderstanding: "A feature store is just a table." The post describes Frame as describing features "both offline and online", with metadata published to a central UI connected to the model repository: "We have tens of thousands of features that need to be produced, discovered, consumed, and monitored."
Definition: Pro-ML began in August 2017 with the goal "to double the effectiveness of machine learning engineers". Pillars cover exploring, training, deploying, running and health assurance. A named risk is a "small delta between the training and serving environments". See ML Systems Architecture.
Timeline: Pro-ML
1 before 2017: bespoke ML stacks per team, little sharing
2 2017-08: Productive Machine Learning program starts
3 2019-01: post: DSL, feature marketplace (Frame), model repository, health assuranceReliability: Nurse Good to know
In plain words: a system that runs scripted fixes when monitoring sees a known problem, so people handle only what automation cannot.
Common misunderstanding: "Auto-remediation means no humans." The post's goal: "Only when automation has failed should a human be tasked to investigate", and the stated design keeps monitoring separate from workflow and action ("separation of powers").
Definition: Nurse is "our auto-remediation platform that we started implementing in April 2014". Monitoring requests a workflow instead of an engineer's attention; a workflow gathers data, restarts the process and records the result in a ticket. The post's figure: "more than 150 hours of remediation workflows every week". See Alerting That Works and Observability.
Timeline: Nurse
1 2014-04 implementation starts
2 2015-07 post: symptom-based alerts as the long-term goal; workflows triggered by monitoring
3 workflow: gather data -> restart process -> put the result in a ticketStep 4: decisions
| Decision | Chosen | Alternative the post names | Source |
|---|---|---|---|
| Integration of many pipelines | One commit log (Kafka) | Custom point-to-point pipelines | History post |
| Kafka consumption model | Pull | Push | NetDB paper |
| Primary store for member data | Espresso | Oracle RDBMS | Espresso post |
| Analytics store writes | Derived store fed by Kafka and Hadoop | Direct user writes | Pinot post |
| Feed construction | Fan-out on read | Fan-out on write | FollowFeed post |
| Index partitioning | Over-partitioned (720) | Splitting partitions | FollowFeed post |
| Second-degree connections | Compute on demand in a graph database | Pre-materialise | LIquid post |
| Service discovery | Client-side via D2 and ZooKeeper | (not stated; hardware load balancers were used earlier) | Rest.li, history posts |
| Cache placement | Next to the data store | Mid-tier caches over multiple domains | History post |
| Cache write ordering | SCN with last-writer-wins and tombstones | Unordered upserts | Profile cache post |
| Mirroring | Brooklin | Kafka MirrorMaker | Brooklin post |
| Operations | Automate known remediations | More operators | Nurse post |
What you can copy
| LinkedIn subsystem | Transferable idea | Read next |
|---|---|---|
| Kafka | Replayable log as the integration layer | Kafka, Backpressure & Flow Control |
| Databus, Brooklin | Ordered change stream plus snapshot fallback | Change Data Capture, Outbox |
| Samza | Stateful processing over a log | Stream Processing |
| Espresso | Partition key as the unit of transaction | Sharding & Consistent Hashing, Consistent Hashing |
| Venice, Pinot | Derived data with an explicit freshness cost | OLTP vs OLAP, Replication Topologies |
| FollowFeed | Fan-out choice by measurement; over-partitioning | Feeds |
| Galene, Cleo | Staged filters; offline index builds | Search Systems, Top-K |
| LIquid | Graph traversal instead of join pre-materialisation | Graph Databases |
| Rest.li, D2 | Uniform API model, client-side balancing | Service Discovery, Load Balancing, API Versioning |
| Couchbase tier | Cache near the store, ordered by version | Caching |
| Pro-ML, Frame | Same feature definitions online and offline | ML Systems |
| Nurse | Automate known fixes, escalate the rest | Alerting That Works, Cascading Failures |
| Leo to services | Extract gradually | Strangler Fig Migration, Modular Monolith |
| Whole company | The method itself | The 4-Step Approach, X / Twitter case study |
Mechanics
Knobs and names the posts expose
| Product | Name or setting | Meaning (source) |
|---|---|---|
| Kafka | -li branch suffix | LinkedIn release branches, based on an Apache release (Kafka 2019 post) |
| Kafka | KIP | Kafka Improvement Proposal filed when upstreaming (Kafka 2019 post) |
| Espresso | numBuckets | Number of partitions in a database schema (Espresso post) |
| Espresso | Helix IdealState and ExternalView | Desired vs current partition placement (Espresso post) |
| Databus | Relay, Bootstrap service | In-memory log and snapshot source (Databus post) |
| FollowFeed | 720 partitions | Over-partitioning (FollowFeed post) |
| Cleo | max prefix length 4, 8-byte bloom | Walkthrough values (Cleo post) |
| Venice | Push Job, incremental push, swap | Write modes (Venice post) |
| Couchbase | SCN, tombstone, TTL, bootstrap period | Ordering and expiry (profile cache post) |
Failures the posts describe
| Failure | Post | Handling |
|---|---|---|
| Consumer too far behind | Databus | Snapshot or bootstrap |
| Cache stale write race | Profile cache | SCN comparison |
| Memcached resize breaks the hash ring | Couchbase 2018 | Moved to Couchbase |
| Index corruption forces full rebuild | Galene | Offline map-reduce index build |
| Operator alert overload | Nurse | Workflows |
Limits of this evidence
| Limit | Why it matters |
|---|---|
| Posts are dated snapshots | Voldemort and the early Databus are older than Venice and Brooklin |
| Posts give no failure rates | We do not claim availability numbers |
| Deco and some products have no fetched post | Not described |
| Rest.li project status can change | Check the project site before adopting |
Go
Example
Three small packages, each re-implementing one mechanism. They are ours, tested, and make no claim about LinkedIn's code.
The first is a Cleo-style typeahead (prefix inverted list, 64-bit bloom, forward check, external score):
// Package typeahead is a small re-implementation of the idea described in
// LinkedIn's 2012 Cleo post: prefix inverted list -> bloom-filter check ->
// forward-index verification -> external score. It is NOT LinkedIn's code.
package typeahead
import (
"hash/fnv"
"sort"
"strings"
)
// MaxPrefix is the length of the prefix used as the inverted-index key.
// The Cleo post uses a maximum prefix length of 4 in its walkthrough.
const MaxPrefix = 4
// Doc is one indexed element (a company, a member, a skill).
type Doc struct {
ID int
Terms []string
Score float64 // external score, for example popularity
}
type entry struct {
doc Doc
bloom uint64 // 8-byte bloom filter over the document's term prefixes
}
// Index is one partition of the typeahead index.
type Index struct {
inverted map[string][]int // prefix -> doc ids
docs map[int]*entry
}
func New() *Index {
return &Index{inverted: map[string][]int{}, docs: map[int]*entry{}}
}
func prefixOf(t string) string {
if len(t) > MaxPrefix {
return t[:MaxPrefix]
}
return t
}
// bit maps a token to one of 64 bits.
func bit(token string) uint64 {
h := fnv.New32a()
_, _ = h.Write([]byte(token))
return 1 << (h.Sum32() % 64)
}
// bloomOf sets one bit for every prefix (length 1..len) of every term, so a
// query term can be tested against it as a prefix.
func bloomOf(terms []string) uint64 {
var b uint64
for _, t := range terms {
for i := 1; i <= len(t); i++ {
b |= bit(t[:i])
}
}
return b
}
// Add indexes a document. Terms are lower-cased.
func (x *Index) Add(d Doc) {
terms := make([]string, len(d.Terms))
for i, t := range d.Terms {
terms[i] = strings.ToLower(t)
}
d.Terms = terms
x.docs[d.ID] = &entry{doc: d, bloom: bloomOf(terms)}
seen := map[string]bool{}
for _, t := range terms {
p := prefixOf(t)
if !seen[p] {
seen[p] = true
x.inverted[p] = append(x.inverted[p], d.ID)
}
}
}
// Stats counts how much work a query did at each stage.
type Stats struct{ Candidates, BloomPass, TrueHits int }
// Search returns documents in which every query term is a prefix of at
// least one indexed term (out-of-order, partial matching), best score first.
func (x *Index) Search(query string) ([]Doc, Stats) {
var st Stats
qs := strings.Fields(strings.ToLower(query))
if len(qs) == 0 {
return nil, st
}
var qbloom uint64
for _, q := range qs {
qbloom |= bit(q)
}
// Stage 1: inverted list for the prefix of the first query term.
cands := x.inverted[prefixOf(qs[0])]
st.Candidates = len(cands)
var out []Doc
for _, id := range cands {
e := x.docs[id]
// Stage 2: the document bloom must contain all query bits.
if e.bloom&qbloom != qbloom {
continue
}
st.BloomPass++
// Stage 3: forward index rejects bloom false positives.
if allPrefixes(qs, e.doc.Terms) {
st.TrueHits++
out = append(out, e.doc)
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Score != out[j].Score {
return out[i].Score > out[j].Score
}
return out[i].ID < out[j].ID
})
return out, st
}
func allPrefixes(qs, terms []string) bool {
for _, q := range qs {
ok := false
for _, t := range terms {
if strings.HasPrefix(t, q) {
ok = true
break
}
}
if !ok {
return false
}
}
return true
}The second is the over-partitioned router with whole-partition rebalancing and a fan-out-on-read merge:
// Package overpartition re-implements two ideas from LinkedIn's 2016
// FollowFeed post: an over-partitioned index (720 partitions, a number with
// many divisors) so rebalancing moves whole partitions, and a fan-out-on-read
// merge of per-entity timelines. It is NOT LinkedIn's code.
package overpartition
import (
"hash/fnv"
"sort"
)
// Partitions is the fixed partition count. 720 is divisible by 40, 45, 60,
// 80 and 360, so many cluster sizes divide it evenly.
const Partitions = 720
// PartitionOf maps an entity id to a partition; it never changes when the
// cluster is resized.
func PartitionOf(entity string) int {
h := fnv.New32a()
_, _ = h.Write([]byte(entity))
return int(h.Sum32() % Partitions)
}
// Assign spreads the partitions round-robin over n nodes.
func Assign(n int) []int {
a := make([]int, Partitions)
for p := range a {
a[p] = p % n
}
return a
}
// Move is one whole-partition transfer.
type Move struct{ Partition, From, To int }
// Rebalance plans the moves from an old assignment to a new node count,
// keeping every partition on its current node when that node still exists
// and the node is not over its fair share. Partitions are never split.
func Rebalance(old []int, newNodes int) (next []int, moves []Move) {
next = make([]int, len(old))
load := make([]int, newNodes)
fair := (len(old) + newNodes - 1) / newNodes
var orphans []int
for p, n := range old {
if n < newNodes && load[n] < fair {
next[p] = n
load[n]++
} else {
orphans = append(orphans, p)
}
}
for _, p := range orphans {
best := 0
for n := 1; n < newNodes; n++ {
if load[n] < load[best] {
best = n
}
}
next[p] = best
load[best]++
moves = append(moves, Move{Partition: p, From: old[p], To: best})
}
return next, moves
}
// Record is one content record in a timeline.
type Record struct {
Entity string
TS int64
ID string
}
// Feed merges the timelines of the entities a viewer follows and returns the
// newest n records (fan-out on read). Each timeline must be newest first.
func Feed(timelines map[string][]Record, followed []string, n int) []Record {
var all []Record
for _, e := range followed {
tl := timelines[e]
if len(tl) > n {
tl = tl[:n]
}
all = append(all, tl...)
}
sort.Slice(all, func(i, j int) bool {
if all[i].TS != all[j].TS {
return all[i].TS > all[j].TS
}
return all[i].ID < all[j].ID
})
if len(all) > n {
all = all[:n]
}
return all
}The third is a Databus-shaped relay with SCN ordering, bounded memory and a snapshot fallback:
// Package relay re-implements the shape of the change-capture design in
// LinkedIn's 2013 Databus post: a bounded in-memory relay of commit-ordered
// events, a consumer that pulls since its last checkpoint, and a bootstrap
// snapshot for consumers that fell behind or are new. NOT LinkedIn's code.
package relay
import "errors"
// Event is one committed change, identified by a monotonically increasing SCN
// (system change number).
type Event struct {
SCN int64
Key string
Value string
Del bool
}
// ErrTooOld means the requested position has been evicted from the relay.
var ErrTooOld = errors.New("relay: position older than buffer; bootstrap required")
// Relay keeps the newest cap events in memory and the full state as a
// snapshot (the "bootstrap service").
type Relay struct {
cap int
buf []Event
snapshot map[string]string
last int64
}
func New(capacity int) *Relay {
return &Relay{cap: capacity, snapshot: map[string]string{}}
}
// Append records a committed change. SCNs must increase.
func (r *Relay) Append(e Event) error {
if e.SCN <= r.last {
return errors.New("relay: SCN must increase")
}
r.last = e.SCN
r.buf = append(r.buf, e)
if len(r.buf) > r.cap {
r.buf = r.buf[1:]
}
if e.Del {
delete(r.snapshot, e.Key)
} else {
r.snapshot[e.Key] = e.Value
}
return nil
}
// Pull returns events with SCN greater than since, in commit order.
func (r *Relay) Pull(since int64) ([]Event, error) {
if len(r.buf) == 0 || since >= r.last {
return nil, nil
}
oldest := r.buf[0].SCN
// Events between since and oldest may have been evicted.
if oldest > since+1 {
return nil, ErrTooOld
}
var out []Event
for _, e := range r.buf {
if e.SCN > since {
out = append(out, e)
}
}
return out, nil
}
// Bootstrap returns a copy of the consistent snapshot and its SCN.
func (r *Relay) Bootstrap() (map[string]string, int64) {
cp := make(map[string]string, len(r.snapshot))
for k, v := range r.snapshot {
cp[k] = v
}
return cp, r.last
}
// Consumer maintains a derived view (for example a search index or cache).
type Consumer struct {
View map[string]string
Checkpoint int64
}
// Sync catches the consumer up: pull, and bootstrap on ErrTooOld.
func (c *Consumer) Sync(r *Relay) (bootstrapped bool, err error) {
evs, err := r.Pull(c.Checkpoint)
if errors.Is(err, ErrTooOld) {
c.View, c.Checkpoint = r.Bootstrap()
return true, nil
}
if err != nil {
return false, err
}
if c.View == nil {
c.View = map[string]string{}
}
for _, e := range evs {
if e.Del {
delete(c.View, e.Key)
} else {
c.View[e.Key] = e.Value
}
c.Checkpoint = e.SCN
}
return false, nil
}Tests that pin the behaviour:
package relay
import "testing"
func fill(r *Relay, n int) {
for i := 1; i <= n; i++ {
_ = r.Append(Event{SCN: int64(i), Key: "k" + string(rune('a'+i%5)), Value: "v"})
}
}
func TestPullInCommitOrder(t *testing.T) {
r := New(10)
fill(r, 5)
evs, err := r.Pull(2)
if err != nil || len(evs) != 3 || evs[0].SCN != 3 || evs[2].SCN != 5 {
t.Fatalf("unexpected %+v %v", evs, err)
}
}
func TestFastConsumerNeverBootstraps(t *testing.T) {
r := New(10)
c := &Consumer{}
fill(r, 3)
if b, _ := c.Sync(r); b {
t.Fatal("new relay with full history must not need bootstrap")
}
_ = r.Append(Event{SCN: 4, Key: "x", Value: "1"})
if b, _ := c.Sync(r); b || c.View["x"] != "1" || c.Checkpoint != 4 {
t.Fatalf("view %+v cp %d", c.View, c.Checkpoint)
}
}
func TestSlowConsumerGetsSnapshot(t *testing.T) {
r := New(3)
c := &Consumer{}
fill(r, 2)
_, _ = c.Sync(r)
fill2 := func() {
for i := 3; i <= 10; i++ {
_ = r.Append(Event{SCN: int64(i), Key: "n", Value: "v"})
}
}
fill2()
_ = r.Append(Event{SCN: 11, Key: "gone", Value: "x"})
_ = r.Append(Event{SCN: 12, Key: "gone", Del: true})
b, err := c.Sync(r)
if err != nil || !b {
t.Fatalf("expected bootstrap, got b=%v err=%v", b, err)
}
if _, ok := c.View["gone"]; ok || c.Checkpoint != 12 {
t.Fatalf("snapshot wrong: %+v cp %d", c.View, c.Checkpoint)
}
}
func TestSCNMustIncrease(t *testing.T) {
r := New(3)
_ = r.Append(Event{SCN: 5, Key: "a"})
if err := r.Append(Event{SCN: 5, Key: "b"}); err == nil {
t.Fatal("duplicate SCN must be rejected")
}
}The Go angle
Go's standard library is enough for all three: hash/fnv for stable partitioning, sort for merges, errors.Is for the "bootstrap required" signal. A real consumer would run Sync in a goroutine with a context.Context; the version here is synchronous so the tests are deterministic. The bloom filter uses 64 bits, so false positives are common with many terms per document; the forward-index stage exists precisely to remove them, and TestForwardIndexRejectsFalsePositive checks that.
Laravel
Example
The same mechanisms with Laravel 13 features: the Cache facade with Cache::lock(), the Http client with Http::pool(), and routing.
<?php
declare(strict_types=1);
namespace App\Search;
/**
* Cleo-style typeahead (inverted prefix list, 64-bit bloom, forward check).
* A teaching re-implementation of the mechanism in LinkedIn's 2012 post.
*/
final class TypeaheadIndex
{
public const MAX_PREFIX = 4;
/** @var array<string, list<int>> */
private array $inverted = [];
/** @var array<int, array{terms: list<string>, score: float, bloom: int, name: string}> */
private array $docs = [];
public function add(int $id, string $name, float $score = 0.0): void
{
$terms = array_values(array_filter(preg_split('/\s+/', mb_strtolower($name)) ?: []));
$this->docs[$id] = [
'terms' => $terms,
'score' => $score,
'bloom' => $this->bloomOf($terms),
'name' => $name,
];
foreach (array_unique(array_map(fn (string $t) => mb_substr($t, 0, self::MAX_PREFIX), $terms)) as $p) {
$this->inverted[$p][] = $id;
}
}
/** @return list<array{id: int, name: string, score: float}> */
public function search(string $query, int $limit = 10): array
{
$qs = array_values(array_filter(preg_split('/\s+/', mb_strtolower($query)) ?: []));
if ($qs === []) {
return [];
}
$qbloom = 0;
foreach ($qs as $q) {
$qbloom |= $this->bit($q);
}
$hits = [];
foreach ($this->inverted[mb_substr($qs[0], 0, self::MAX_PREFIX)] ?? [] as $id) {
$d = $this->docs[$id];
if (($d['bloom'] & $qbloom) !== $qbloom) {
continue; // bloom says "cannot match"
}
if ($this->allPrefixes($qs, $d['terms'])) { // forward index check
$hits[] = ['id' => $id, 'name' => $d['name'], 'score' => $d['score']];
}
}
usort($hits, fn (array $a, array $b) => [$b['score'], $a['id']] <=> [$a['score'], $b['id']]);
return array_slice($hits, 0, $limit);
}
/** @param list<string> $terms */
private function bloomOf(array $terms): int
{
$b = 0;
foreach ($terms as $t) {
for ($i = 1; $i <= mb_strlen($t); $i++) {
$b |= $this->bit(mb_substr($t, 0, $i));
}
}
return $b;
}
private function bit(string $token): int
{
return 1 << (crc32($token) % 62); // 62 keeps the mask inside PHP's signed 64-bit int
}
/**
* @param list<string> $qs
* @param list<string> $terms
*/
private function allPrefixes(array $qs, array $terms): bool
{
foreach ($qs as $q) {
$ok = false;
foreach ($terms as $t) {
if (str_starts_with($t, $q)) {
$ok = true;
break;
}
}
if (! $ok) {
return false;
}
}
return true;
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Search\TypeaheadIndex;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
// routes/web.php or routes/api.php:
// Route::get('/typeahead/companies', [TypeaheadController::class, 'companies'])->middleware('throttle:60,1');
final class TypeaheadController
{
public function companies(Request $request, TypeaheadIndex $index): JsonResponse
{
$q = trim((string) $request->query('q', ''));
if (mb_strlen($q) < 2) {
return response()->json(['hits' => []]);
}
// Generic (network-agnostic) typeahead: same query, same answer for every member,
// so a short shared cache is safe. A network-aware typeahead must NOT share this key.
$hits = Cache::remember('typeahead:companies:'.md5($q), 30, fn () => $index->search($q, 8));
return response()->json(['hits' => $hits]);
}
}<?php
declare(strict_types=1);
namespace App\Feed;
/**
* Over-partitioned routing in the spirit of LinkedIn's FollowFeed post:
* a fixed 720 partitions; changing the node count moves whole partitions.
*/
final class PartitionRouter
{
public const PARTITIONS = 720;
/** @param list<string> $nodes e.g. ['http://feed-0.internal', ...] */
public function __construct(private array $nodes)
{
}
public function partitionOf(string $entity): int
{
return crc32($entity) % self::PARTITIONS; // crc32 is non-negative on 64-bit PHP
}
public function nodeFor(string $entity): string
{
return $this->nodes[$this->partitionOf($entity) % count($this->nodes)];
}
/**
* Group the followed entities by node so one request goes to each node
* (scatter-gather), instead of one request per entity.
*
* @param list<string> $followed
* @return array<string, list<string>>
*/
public function plan(array $followed): array
{
$byNode = [];
foreach ($followed as $entity) {
$byNode[$this->nodeFor($entity)][] = $entity;
}
return $byNode;
}
}<?php
declare(strict_types=1);
namespace App\Feed;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
/** Fan-out on read: scatter to index nodes in parallel, merge newest first. */
final class FeedReader
{
public function __construct(private PartitionRouter $router)
{
}
/**
* @param list<string> $followed
* @return list<array{id: string, ts: int}>
*/
public function read(array $followed, int $n = 20): array
{
$plan = $this->router->plan($followed);
$responses = Http::pool(function (Pool $pool) use ($plan, $n) {
$reqs = [];
foreach ($plan as $node => $entities) {
$reqs[] = $pool->as($node)->timeout(2)->get($node.'/timelines', [
'entities' => implode(',', $entities),
'limit' => $n,
]);
}
return $reqs;
});
$all = [];
foreach ($responses as $response) {
if ($response instanceof \Illuminate\Http\Client\Response && $response->ok()) {
array_push($all, ...$response->json('records', []));
}
// A failed or slow node degrades the feed instead of failing it.
}
usort($all, fn (array $a, array $b) => [$b['ts'], $a['id']] <=> [$a['ts'], $b['id']]);
return array_slice($all, 0, $n);
}
}<?php
declare(strict_types=1);
namespace App\Cache;
use Illuminate\Support\Facades\Cache;
/**
* Last-writer-wins by change number, with tombstones, as described in
* LinkedIn's 2023 profile-cache post (their version is a Couchbase tier
* fed by Samza jobs; this is a small Laravel illustration).
*/
final class ScnGuardedCache
{
public function put(string $key, ?array $value, int $scn, int $ttlSeconds = 3600): bool
{
return Cache::lock("scn-lock:{$key}", 5)->block(2, function () use ($key, $value, $scn, $ttlSeconds): bool {
$current = Cache::get("scn:{$key}");
if (is_array($current) && $current['scn'] >= $scn) {
return false; // stale writer loses
}
// A null value is a tombstone: it remembers the delete so an older upsert cannot resurrect it.
Cache::put("scn:{$key}", ['scn' => $scn, 'value' => $value], $ttlSeconds);
return true;
});
}
public function get(string $key): ?array
{
$entry = Cache::get("scn:{$key}");
return is_array($entry) ? $entry['value'] : null; // tombstone and miss both read as null
}
}<?php
declare(strict_types=1);
namespace App\Rpc;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
/**
* Client-side discovery and load balancing, the idea behind D2 in the Rest.li
* post: the client holds the host list for a service and picks a host itself.
* The registry (ZooKeeper in the post) is a plain array here.
*/
final class D2StyleClient
{
/** @var array<string, int> host => in-flight requests */
private array $inflight = [];
/** @param list<string> $hosts */
public function __construct(private array $hosts)
{
$this->inflight = array_fill_keys($hosts, 0);
}
public function get(string $path, array $query = []): Response
{
$tried = [];
for ($attempt = 0; $attempt < 2; $attempt++) {
$host = $this->pick($tried);
$tried[] = $host;
$this->inflight[$host]++;
try {
$response = Http::baseUrl($host)->timeout(1)->get($path, $query);
if (! $response->serverError()) {
return $response;
}
} catch (\Illuminate\Http\Client\ConnectionException) {
// fall through and try another host
} finally {
$this->inflight[$host]--;
}
}
throw new \RuntimeException('no healthy host for '.$path);
}
/** Least in-flight requests wins; hosts already tried are skipped when possible. */
private function pick(array $tried): string
{
$candidates = array_diff_key($this->inflight, array_flip($tried)) ?: $this->inflight;
asort($candidates);
return array_key_first($candidates);
}
}The Laravel angle
Http::pool() sends the per-node requests concurrently, which is what the FollowFeed read path needs; a failed node is skipped so the feed degrades instead of failing. Cache::lock() serialises writers per key, which is the in-process counterpart of ordering updates by SCN; it needs a cache store that supports locks (Redis, Memcached, database, DynamoDB, file, array). The D2-style client keeps its host list in an array; a real deployment would refresh it from a registry such as Consul or Kubernetes endpoints. These files were checked with php -l only; they were not run inside a Laravel application.
SQL
An Espresso-style hierarchical table and a Databus-style change log, with the partition key as the leading primary-key column:
-- Espresso-style hierarchical document table (database -> table -> collection -> document).
-- The leading key (mailbox_id) is the partitioning key; message_id is the sub-key.
-- Written by us from the structure described in LinkedIn's 2015 Espresso post; not LinkedIn's DDL.
CREATE TABLE messages (
mailbox_id BIGINT NOT NULL, -- partitioning key
message_id BIGINT NOT NULL, -- sub-key
doc JSON NOT NULL, -- document body (Espresso stores Avro blobs)
schema_ver INT NOT NULL,
scn BIGINT NOT NULL, -- commit order, source of the change stream
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (mailbox_id, message_id)
);
-- A collection read: everything in one mailbox, one partition, one transaction scope.
SELECT message_id, doc FROM messages WHERE mailbox_id = 100 ORDER BY message_id DESC LIMIT 20;
-- Change stream the way a Databus-style relay would read it: by SCN, in commit order.
CREATE TABLE change_log (
scn BIGINT PRIMARY KEY,
mailbox_id BIGINT NOT NULL,
message_id BIGINT NOT NULL,
op CHAR(1) NOT NULL -- U upsert, D delete
);
SELECT scn, mailbox_id, message_id, op FROM change_log WHERE scn > 41200 ORDER BY scn LIMIT 500;-- Idempotent apply on the consumer side: only move forward in SCN.
UPDATE profile_cache SET doc = :doc, scn = :scn WHERE member_id = :id AND scn < :scn;Solving the classic problems
| Problem | Solution seen in the posts | Cost |
|---|---|---|
| Too many bespoke pipelines | One log, many consumers | Operating a very large Kafka estate |
| Search lags the database | Change capture into the index | Another stream to run |
| Hot feed reads with heavy ranking | Fan-out on read, scoring next to data | Read-time compute |
| Resizing a partitioned cluster | Over-partition and move whole partitions | More partitions than nodes |
| Cache and source diverge | SCN ordering, tombstones, periodic bootstrap | Extra jobs |
| Operator overload | Auto-remediation workflows | Maintaining workflows |
Falling behind
A consumer behind the relay window must bootstrap; see the relay tests.
Racing cache writers
Compare version numbers, never wall-clock time; keep tombstones.
Rebalancing without splitting
Choose a partition count with many divisors; move whole partitions.
Choosing
| Situation | Take from LinkedIn | Skip |
|---|---|---|
| Several consumers need the same events | A log with independent readers | Running your own cluster if a managed one exists (inference) |
| Search or cache must follow a database | Change capture with a snapshot fallback | Dual writes from application code (inference) |
| Product with learned ranking and moderate follow counts | Fan-out on read | Pre-materialised feeds you will have to rewrite per model |
| Relationship queries of depth two or more | A graph store | Join pre-materialisation |
| Fewer than a few dozen services | Plain DNS and a load balancer | D2-style registry (inference) |
| Hot read-heavy store | A cache next to the store, version-ordered | Many mid-tier caches |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
LinkedIn began as "a single monolithic application doing it all" (history post). One process, one database, and the first extraction was an in-memory graph service. Example: the typeahead index and the feed merge both run in-process in a small app.
Modular monolith / multiple databases
Before services, replica read databases were fed by the earliest Databus. The lesson is boundaries by data ownership; see Modular Monolith.
Microservices
Rest.li gave 750+ services one API style; D2 gave discovery. A profile read crosses frontend, backend and store (profile cache post). See Microservices Data Ownership.
Distributed data (replicas, caches, sharding, multi-region)
Espresso replicates across data centers via its Data Replicator, a Databus consumer; FollowFeed sticky-routes viewers; the profile cache is ordered by SCN. Eventual consistency is explicit in FollowFeed and Venice.
Scaling path: 1x, 10x, 100x
| Scale | Move | Evidence |
|---|---|---|
| 1x | Monolith, one database | Leo |
| 10x | Replicas, services, caches | History post |
| 100x | Log spine, derived stores, partitioned everything | Kafka, Venice, Espresso posts |
Lab
Expected, not run for the Laravel parts; the Go commands can be run locally.
$ cd docs/snippets/system-design/case-study-linkedin/go
$ go test ./...
ok academy/case-study-linkedin/overpartition
ok academy/case-study-linkedin/relay
ok academy/case-study-linkedin/typeahead- Change
Partitionsto 700 and rerun;TestEvenAssignmentWhenDivisiblefails for 45 and 360 (expected, not run). - Shrink
relay.New(3)to 1 and watch which consumers bootstrap. - Add 5,000 documents with the same first four letters and print
Stats; compareCandidates,BloomPass,TrueHits. - Laravel (expected, not run): bind
TypeaheadIndexas a singleton, call/typeahead/companies?q=link, expect a JSONhitsarray.
Common misconceptions
| Belief | Reality |
|---|---|
| LinkedIn invented the log | The Log post presents it as a long-standing idea in databases and distributed systems |
| Kafka deletes after read | Consumers track offsets; retention removes data |
| Feeds are always precomputed | FollowFeed chose fan-out on read |
| Derived stores need full transactional machinery | Pinot is a derived store; Venice is eventually consistent |
| A graph database is a niche toy | LIquid serves 2 million queries per second |
| Caches below the service layer are harmful | The 2015 post removed mid-tier caches; the 2023 post added a tier at the store |
| One search index serves everything | Galene, Cleo and the feed index are different |
| Auto-remediation removes on-call | Humans handle what automation fails to fix |
| Posts show the current system | They are dated |
| Our re-implementations are LinkedIn's code | They are teaching code |
Cheat sheet
| Topic | Remember |
|---|---|
| Spine | Online store, change stream, log, derived systems |
| Kafka | Pull, partitions, consumer groups, at-least-once |
| Databus | Commit order, relay, bootstrap |
| Brooklin | Bridge and mirror, replaced MirrorMaker |
| Espresso | Partition key, MySQL storage nodes, Helix |
| Venice | Derived data, push jobs, swap |
| Pinot | Columnar, derived, no joins |
| FollowFeed | Fan-out on read, 720 partitions |
| Cleo | Prefix, bloom, forward index |
| LIquid | Second degree, Datalog, triples |
| Rest.li and D2 | Uniform API, client-side discovery |
| Caching | Near the store; SCN order; tombstones |
| Nurse | Monitoring requests workflows |
| Labels | Quote it or call it inference |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why did the NetDB paper prefer pull over push? Important
Answer
Answer: Each consumer reads at the rate it can sustain and can rewind, because it owns its offset.
2 — What does Databus do for a consumer that is too far behind? Important
Answer
Answer: It delivers a consolidated snapshot of changes; a new consumer is bootstrapped from a snapshot.
3 — Name two reasons FollowFeed chose fan-out on read. Must-know
Answer
Answer: 62 times more data with fan-out on write, and model rollouts would rewrite every stored feed.
4 — Why 720 partitions? Good to know
Answer
Answer: It divides evenly by many cluster sizes (for example 40, 45, 60, 80, 360), so whole partitions can be moved.
5 — Why is Pinot a derived store? Important
Answer
Answer: To avoid building replication, backup and user-write handling; it accepts seconds of staleness.
6 — What orders racing cache writers in the profile cache? Important
Answer
Answer: The SCN, with last-writer-wins and tombstones.
7 — What is D2? Good to know
Answer
Answer: Dynamic discovery and client-side load balancing, with ZooKeeper as registry.
8 — What does the forward index in Cleo do? Good to know
Answer
Answer: It rejects bloom false positives.
9 — What is inference in this chapter? Must-know
Answer
Answer: Anything not stated in a fetched company source, such as our arithmetic and generalisations.
10 — Why not pre-materialise second-degree connections? Important
Answer
Answer: Too large to store and roughly 250 times the base write rate to maintain.
Glossary
| Term | Meaning |
|---|---|
| Commit log | Append-only ordered record sequence |
| Partition | One log shard of a topic |
| Consumer group | Consumers that split a topic's partitions |
| Offset | Position in a partition |
| SCN | System change number, a logical commit timestamp |
| Databus | LinkedIn's change data capture system |
| Brooklin | Streaming bridge between stores and messaging systems |
| Samza | Stream processing framework |
| Espresso | LinkedIn's document store |
| Voldemort | LinkedIn's earlier key-value store |
| Venice | Derived-data platform |
| Derived data | Data computed from another source of truth |
| Pinot | Real-time OLAP store |
| FollowFeed | Feed infrastructure |
| Fan-out on read | Build the feed at request time |
| Galene | Search architecture |
| Cleo | Typeahead library |
| LIquid | Graph database |
| Rest.li | REST+JSON service framework |
| D2 | Dynamic discovery layer |
| Couchbase | Distributed store used as a cache tier |
| Frame | Feature description system |
| Pro-ML | Productive Machine Learning program |
| Nurse | Auto-remediation platform |
| Inference | Claim not stated by a cited source |
| Tombstone | Marker that remembers a delete |
References
All URLs returned HTTP 200 when fetched on 2026-11-26. Posts that now return 404 on the company site are cited through their web.archive.org copy.
- Kreps, Narkhede, Rao, Kafka: a Distributed Messaging System for Log Processing, NetDB 2011: https://notes.stephenholiday.com/Kafka.pdf
- The Log (2013, archived copy): https://web.archive.org/web/2023/https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying
- How LinkedIn customizes Apache Kafka for 7 trillion messages per day (2019): https://engineering.linkedin.com/blog/2019/apache-kafka-trillion-messages
- Open sourcing Databus (2013): https://engineering.linkedin.com/data-replication/open-sourcing-databus-linkedins-low-latency-change-data-capture-system
- Open sourcing Brooklin (2019): https://engineering.linkedin.com/blog/2019/brooklin-open-source
- Apache Samza (2013): https://engineering.linkedin.com/data-streams/apache-samza-linkedins-real-time-stream-processing-framework
- Introducing Espresso (2015): https://engineering.linkedin.com/espresso/introducing-espresso-linkedins-hot-new-distributed-document-store
- Open Sourcing Venice (2022): https://engineering.linkedin.com/blog/2022/open-sourcing-venice--linkedin-s-derived-data-platform
- Voldemort 1.10 (2015): https://engineering.linkedin.com/blog/2015/10/voldemort-1-10-open-source-release
- Open Sourcing Pinot (2015): https://engineering.linkedin.com/pinot/open-sourcing-pinot-scaling-wall-real-time-analytics
- Pinot Joins Apache Incubator (2019): https://engineering.linkedin.com/blog/2019/03/pinot-joins-apache-incubator
- FollowFeed (2016): https://engineering.linkedin.com/blog/2016/03/followfeed--linkedin-s-feed-made-faster-and-smarter
- Did you mean Galene? (2014): https://engineering.linkedin.com/search/did-you-mean-galene
- Cleo (2012, archived copy): https://web.archive.org/web/2023/https://engineering.linkedin.com/open-source/cleo-open-source-technology-behind-linkedins-typeahead-search
- LIquid part 1 (2020): https://engineering.linkedin.com/blog/2020/liquid-the-soul-of-a-new-graph-database-part-1
- How LIquid Connects Everything (2023): https://engineering.linkedin.com/blog/2023/how-liquid-connects-everything-so-our-members-can-do-anything
- Rest.li (2013): https://engineering.linkedin.com/architecture/restli-restful-service-architecture-scale
- A Brief History of Scaling LinkedIn (2015, archived copy): https://web.archive.org/web/2023/https://engineering.linkedin.com/architecture/brief-history-scaling-linkedin
- Couchbase Ecosystem at LinkedIn (2017): https://engineering.linkedin.com/blog/2017/12/couchbase-ecosystem-at-linkedin
- Evolution of Couchbase at LinkedIn (2018): https://engineering.linkedin.com/blog/2018/05/evolution-of-couchbase-at-linkedin
- Upscaling LinkedIn's Profile Datastore (2023): https://engineering.linkedin.com/blog/2023/upscaling-profile-datastore-while-reducing-costs
- Scaling Machine Learning Productivity at LinkedIn (2019): https://engineering.linkedin.com/blog/2019/01/scaling-machine-learning-productivity-at-linkedin
- Introducing Nurse (2015, archived copy): https://web.archive.org/web/2023/https://engineering.linkedin.com/sre/introducing-nurse-auto-remediation-linkedin