Skip to content

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 forGo to
The page in four tablesEverything in one minute
What a case study here may and may not claimWhy it exists
Dated posts and what changedWhere it comes from
Step 1: what the posts say the product needsStep 1: scope
Step 2: numbers from the posts and our estimatesStep 2: estimate
Step 3: the overall pictureStep 3: high-level design
Kafka and the logKafka and the commit log
Databus, BrooklinChange capture: Databus and Brooklin
SamzaStream processing: Samza
Espresso, Voldemort, VeniceOnline and derived data stores
PinotReal-time OLAP: Pinot
FollowFeedThe feed: FollowFeed
Galene, CleoSearch and typeahead
LIquidThe graph: LIquid
Rest.li, D2, DecoServing: Rest.li and D2
CouchbaseCaching
Pro-ML, FrameMachine learning platform
NurseReliability: Nurse
Step 4: the decisions as a tableStep 4: decisions
Which generic chapter to readWhat you can copy
CodeGo, Laravel
Numbers, labMechanics, Lab
Wrong beliefs, summary, quiz, terms, sourcesMisconceptions, 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.

SubsystemWhat it is, from the company's postsFirst dated source
KafkaDistributed commit-log messaging system built for log processingNetDB paper, June 2011
DatabusChange data capture system, in production in its latest revision since 2011Open-sourcing post, Feb 2013
SamzaStream processing framework on top of Kafka and YARNPost, Sep 2013
EspressoOnline, distributed, fault-tolerant NoSQL document store; MySQL storage nodesPost, Jan 2015
PinotReal-time analytics; a derived data store with columnar storagePost, Jun 2015
FollowFeedFeed infrastructure with fan-out on read; replaced SenseiPost, Mar 2016
BrooklinStreaming bridge between stores and messaging systems; in production since 2016Post, Jul 2019
VeniceDerived-data platform; in production since the end of 2016Post, Sep 2022
Galene, CleoSearch architecture (2014) and typeahead library (2012)Posts, Jun 2014 and Mar 2012
LIquidGraph database for the economic graphPost, Jul 2020
Rest.li, D2REST+JSON framework and dynamic discovery with client-side load balancingPost, Feb 2013
CouchbaseCaching tier, adopted in 2012Post, Dec 2017
Pro-ML, FrameMachine learning platform and feature systemPost, Jan 2019
NurseAuto-remediation platformPost, Jul 2015

The 4-step backbone.

StepQuestionWhere on this page
1. ScopeWhat does the product need, per the posts?Step 1
2. EstimateWhat numbers does the company publish; what can we derive?Step 2
3. High-level designWhich boxes, which arrows?Step 3 and the per-subsystem blocks
4. DecisionsWhat was chosen, what was rejected, why?Step 4

Numbers the posts publish.

QuantityValueSource
Kafka messages per daymore than 7 trillionKafka 2019 post
Kafka clusters / brokers / topics / partitionsover 100 / over 4,000 / over 100,000 / over 7 millionKafka 2019 post
Brooklinover 2 trillion messages per dayBrooklin 2019 post
Venice datasets / applicationsmore than 1,800 / over 300Venice 2022 post
LIquid270 billion edges, 2 million queries per secondLIquid 2023 post
Profile reads at peakover 4.8 million per secondProfile cache 2023 post
FollowFeed vs Senseip99 feed latency down fivefold, index 20 times larger, half the serversFollowFeed 2016 post
Fan-out on write vs read, data size62 times greater with fan-out on writeFollowFeed 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 studyThis chapter
"LinkedIn uses X" with no date or sourceA dated post or paper for each claim
Numbers repeated from memoryNumbers copied from the post, with its date
Our guess presented as company factMarked inference
Architecture as a finished pictureArchitecture 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 ​

  1. "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.
  2. "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.
  3. "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.

DateEvent (as the source states it)Source
2003LinkedIn starts; 2,700 members in the first weekScaling history post (2015)
2005Databus originally developedDatabus post (2013)
2011-06Kafka paper at NetDB 2011: in production at LinkedIn for more than 6 monthsKafka paper
2011Databus latest revision in production; Espresso requirements written; "Inversion" initiative starts late in the yearDatabus, Espresso, history posts
2012Couchbase first adopted; Cleo open-sourced (March)Couchbase 2017 post, Cleo post
2013Rest.li open-sourced (Feb), Databus open-sourced (Feb), Samza (Sep), The Log (Dec)respective posts
2014Galene search architecture (Jun); profile moved from Oracle to Espresso; Nurse implementation started in AprilGalene, profile cache, Nurse posts
2015Espresso post (Jan), Pinot open-sourced (Jun), history post (Jul): over 750 services, Kafka over 500 billion events per dayrespective posts
2016FollowFeed (Mar) replaces Sensei; Brooklin in productionFollowFeed, Brooklin posts
2016Venice in production at the end of the yearVenice post
2017Couchbase: over 10 million queries per second, over 200 clusters; Pro-ML started in AugustCouchbase, Pro-ML posts
2019Kafka over 7 trillion messages per day (Oct); Brooklin open-sourced (Jul); Pinot joins Apache Incubator (Mar)respective posts
2020LIquid post series (Jul)LIquid post
2022-2023Venice 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)
2011Kafka paper2012Cleo2013Rest.li, DatabusSamza, The Log2014Galene2015Espresso, PinotNurse, history2016FollowFeedBrooklin, Venicein production2017CouchbasePro-ML starts2019Kafka 7T/dayBrooklin, Pro-MLpost, Pinot Apache2020LIquid2022-23Venice OSSprofile cacheEvery dot is a dated post or paper that was fetched; positions are not to scale.

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 needEvidence in the postsSystem that answers it
Move data between many systems without N-by-M pipelinesHistory post: many custom pipelines for data warehouse, Hadoop, logs, tracking events, InMail, search updatesKafka
Keep search and caches current with the primary databaseDatabus post: search index must continually index the primary databaseDatabus, later Brooklin
Fast online reads and writes for member dataEspresso post: profile, InMail, homepageEspresso
Interactive analytics for members and customersPinot post: Who Viewed My Profile, ads analyticsPinot
A feed that is relevant and fastFollowFeed post: wider distribution and improved relevanceFollowFeed
Search over people, jobs, companiesGalene post: 300M+ members, personalised resultsGalene, Cleo
Second-degree connections in human real timeLIquid postLIquid
Many services with a consistent APIRest.li postRest.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 quantityCalculationValueLabel
Average Kafka message rate7 trillion / 86,400 sabout 81 million messages per secondinference (arithmetic on a post figure)
Partitions per broker7 million / 4,000about 1,750 on averageinference
Messages per partition per day7 trillion / 7 millionabout 1 millioninference
Profile reads that reach Espresso at 99% cache hit4.8 million x 1%about 48,000 per secondinference; assumes the hit rate applies at peak
FollowFeed partitions per node720 / 4018inference from the 720 figure in the post
Second-degree write amplificationabout 250 first-degree connectionsroughly 250 times the base write ratestated 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 ​

Espressoonline source of truthApps and servicesHadoop (batch)Databuschange captureKafkacommit logpartitionsBrooklin mirrorSamza stream jobsPinot real-time OLAPVenice derived dataSearch index, cachesArrows follow the posts' descriptions; the exact wiring per product is simplified (inference).

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 miss

Kafka 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
PropertyWhat the paper / post saysSource
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 layoutEach partition is a log of segment files, about 1 GB each in the paper's exampleNetDB 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
OperationsKafka ecosystem includes a REST proxy, schema registry (Avro), Brooklin for mirroring, Cruise Control, an audit called Bean CounterKafka 2019 post
Patch policyRelease branches are not a fork; "upstream first" or "LinkedIn first" hotfix with double-commit attemptKafka 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-independentOracle adapter open-sourced; MySQL adapter planned in 2013
Transactional in-order deliveryEvents grouped by transaction, in source commit order
Low latencyMilliseconds from source availability
Infinite lookbackBootstrap service for new or slow consumers
Server-side filteringConsumers can retrieve specific partitions
Brooklin (2019 post)Meaning
Streaming bridgeMoves data between stores (Espresso, Oracle) and messaging (Kafka, Event Hubs, Kinesis)
MultitenancyOne cluster serves many pipelines; MirrorMaker needed a cluster per pipeline
Dynamic provisioningPipelines created or modified with an HTTP call to a REST endpoint
DiagnosticsREST 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
UseSource
Counts and aggregations by member idSamza post
Nearline model evaluationPro-ML post
Cache updates from Espresso change eventsProfile 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)
SystemRoleSource saysSource
Oracle (RDBMS)earlier primary storeschema evolution and shard provisioning were manual and costlyEspresso post
Voldemortkey-value storefor apps needing key-value access but not a timeline-consistent change streamEspresso post
Espressoprimary, strongly consistent document storeabout 30 applications in 2015Espresso post
Venicederived data"more than 1800 of our datasets", over 300 applicationsVenice post
Venice write pathMeaning
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 pushAdds data to the existing dataset
Streaming writesNearline writes, for example from Samza
HybridReplay phase puts recent nearline writes on top of a newly loaded version before the swap
Partial updatesMutate some columns without read-modify-write, because all writes are asynchronous
Venice read pathMeaning
Single Get / Batch GetKey lookups; the feed uses batch gets; 45M key lookups per second at peak
Read ComputeServer-side arithmetic on embeddings, 46M lookups per second at peak
Da VinciA 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
ComponentRole (2019 post)
Pinot ServerHosts data segments, serves queries from them
Pinot BrokerAccepts queries, routes to servers, merges results
Pinot ControllerManages components, assigns segments to servers
HadoopSource of truth for fact data, used to re-bootstrap
KafkaReal-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)ChoiceReason in the post
Where computation runsOn nodes holding the dataLarge record sets feed relevance; remote fetches add latency
Fan-out strategyFan-out on read62x data with fan-out on write; model rollouts require rewriting every stored feed
Partition count720, over-partitionedDivisible by many numbers; moving whole partitions avoids splitting
StorageRocksDB, JNI binding contributed backEmbeddable key-value store tuned for SSDs
SerializationAvro with schema registry on the nodeSchema versions needed to read old data
IngestionKafka plus PartitionerRe-partitions to match the index partition range
Multi data centerSticky routing; cluster size follows read shareServe a viewer from the local data center
Viewer requestBrokerroutes by partitionIndex node Apartitions 0..11 (RocksDB)Index node Bpartitions 12..23Index node Cpartitions 24..35 ...Score, merge,top N720 partitions in the post; the numbers per node here are illustrative. Scoring runs on the nodes, next to the data.

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.

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
GenericSame query gives the same results for every member; ordered by a global ranking such as popularity
NetworkResults 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 hardIndex building moves to offline map-reduce jobs
Reactive stacking of componentsOne redesigned architecture
Relevance engineers tied up in infrastructureClear separation of infrastructure and relevance tasks
Query"linked"Inverted listprefix "link" (max 4)Bloom filter8 bytes per docForward indexdrop false hitsScore, mergeacross partitionsStages as listed in the 2012 Cleo post; each stage is a cheaper filter that shrinks the candidate set.

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
FactSource
2nd degree network is typically at least 50,000 entitiesLIquid part 1
Interface is declarative, Datalog-basedLIquid part 1
270 billion edges; 2M queries per secondLIquid 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
LayerRole (Rest.li post)
Rest.liResource modelling, IDL, batch operations, type-safe clients, compatibility-checked evolution
R2Asynchronous REST transport (Netty-based HTTP implementation)
D2Registry 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 postMechanism
Stale record inserted by a racing writerCompare SCN; largest SCN replaces the existing record
Deleted record resurrectedTombstone records instead of hard deletes
Cache drifting from the source of truthPeriodic bootstrap within the TTL
Miss due to expired TTLUpdate 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 assurance

Reliability: 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 ticket

Step 4: decisions ​

DecisionChosenAlternative the post namesSource
Integration of many pipelinesOne commit log (Kafka)Custom point-to-point pipelinesHistory post
Kafka consumption modelPullPushNetDB paper
Primary store for member dataEspressoOracle RDBMSEspresso post
Analytics store writesDerived store fed by Kafka and HadoopDirect user writesPinot post
Feed constructionFan-out on readFan-out on writeFollowFeed post
Index partitioningOver-partitioned (720)Splitting partitionsFollowFeed post
Second-degree connectionsCompute on demand in a graph databasePre-materialiseLIquid post
Service discoveryClient-side via D2 and ZooKeeper(not stated; hardware load balancers were used earlier)Rest.li, history posts
Cache placementNext to the data storeMid-tier caches over multiple domainsHistory post
Cache write orderingSCN with last-writer-wins and tombstonesUnordered upsertsProfile cache post
MirroringBrooklinKafka MirrorMakerBrooklin post
OperationsAutomate known remediationsMore operatorsNurse post

What you can copy ​

LinkedIn subsystemTransferable ideaRead next
KafkaReplayable log as the integration layerKafka, Backpressure & Flow Control
Databus, BrooklinOrdered change stream plus snapshot fallbackChange Data Capture, Outbox
SamzaStateful processing over a logStream Processing
EspressoPartition key as the unit of transactionSharding & Consistent Hashing, Consistent Hashing
Venice, PinotDerived data with an explicit freshness costOLTP vs OLAP, Replication Topologies
FollowFeedFan-out choice by measurement; over-partitioningFeeds
Galene, CleoStaged filters; offline index buildsSearch Systems, Top-K
LIquidGraph traversal instead of join pre-materialisationGraph Databases
Rest.li, D2Uniform API model, client-side balancingService Discovery, Load Balancing, API Versioning
Couchbase tierCache near the store, ordered by versionCaching
Pro-ML, FrameSame feature definitions online and offlineML Systems
NurseAutomate known fixes, escalate the restAlerting That Works, Cascading Failures
Leo to servicesExtract graduallyStrangler Fig Migration, Modular Monolith
Whole companyThe method itselfThe 4-Step Approach, X / Twitter case study

Mechanics ​

Knobs and names the posts expose ​

ProductName or settingMeaning (source)
Kafka-li branch suffixLinkedIn release branches, based on an Apache release (Kafka 2019 post)
KafkaKIPKafka Improvement Proposal filed when upstreaming (Kafka 2019 post)
EspressonumBucketsNumber of partitions in a database schema (Espresso post)
EspressoHelix IdealState and ExternalViewDesired vs current partition placement (Espresso post)
DatabusRelay, Bootstrap serviceIn-memory log and snapshot source (Databus post)
FollowFeed720 partitionsOver-partitioning (FollowFeed post)
Cleomax prefix length 4, 8-byte bloomWalkthrough values (Cleo post)
VenicePush Job, incremental push, swapWrite modes (Venice post)
CouchbaseSCN, tombstone, TTL, bootstrap periodOrdering and expiry (profile cache post)

Failures the posts describe ​

FailurePostHandling
Consumer too far behindDatabusSnapshot or bootstrap
Cache stale write raceProfile cacheSCN comparison
Memcached resize breaks the hash ringCouchbase 2018Moved to Couchbase
Index corruption forces full rebuildGaleneOffline map-reduce index build
Operator alert overloadNurseWorkflows

Limits of this evidence ​

LimitWhy it matters
Posts are dated snapshotsVoldemort and the early Databus are older than Venice and Brooklin
Posts give no failure ratesWe do not claim availability numbers
Deco and some products have no fetched postNot described
Rest.li project status can changeCheck 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):

go
// 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:

go
// 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:

go
// 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:

go
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
<?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
<?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
<?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
<?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
<?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
<?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:

sql
-- 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;
sql
-- 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 ​

ProblemSolution seen in the postsCost
Too many bespoke pipelinesOne log, many consumersOperating a very large Kafka estate
Search lags the databaseChange capture into the indexAnother stream to run
Hot feed reads with heavy rankingFan-out on read, scoring next to dataRead-time compute
Resizing a partitioned clusterOver-partition and move whole partitionsMore partitions than nodes
Cache and source divergeSCN ordering, tombstones, periodic bootstrapExtra jobs
Operator overloadAuto-remediation workflowsMaintaining 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 ​

SituationTake from LinkedInSkip
Several consumers need the same eventsA log with independent readersRunning your own cluster if a managed one exists (inference)
Search or cache must follow a databaseChange capture with a snapshot fallbackDual writes from application code (inference)
Product with learned ranking and moderate follow countsFan-out on readPre-materialised feeds you will have to rewrite per model
Relationship queries of depth two or moreA graph storeJoin pre-materialisation
Fewer than a few dozen servicesPlain DNS and a load balancerD2-style registry (inference)
Hot read-heavy storeA cache next to the store, version-orderedMany 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 ​

ScaleMoveEvidence
1xMonolith, one databaseLeo
10xReplicas, services, cachesHistory post
100xLog spine, derived stores, partitioned everythingKafka, 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
  1. Change Partitions to 700 and rerun; TestEvenAssignmentWhenDivisible fails for 45 and 360 (expected, not run).
  2. Shrink relay.New(3) to 1 and watch which consumers bootstrap.
  3. Add 5,000 documents with the same first four letters and print Stats; compare Candidates, BloomPass, TrueHits.
  4. Laravel (expected, not run): bind TypeaheadIndex as a singleton, call /typeahead/companies?q=link, expect a JSON hits array.

Common misconceptions ​

BeliefReality
LinkedIn invented the logThe Log post presents it as a long-standing idea in databases and distributed systems
Kafka deletes after readConsumers track offsets; retention removes data
Feeds are always precomputedFollowFeed chose fan-out on read
Derived stores need full transactional machineryPinot is a derived store; Venice is eventually consistent
A graph database is a niche toyLIquid serves 2 million queries per second
Caches below the service layer are harmfulThe 2015 post removed mid-tier caches; the 2023 post added a tier at the store
One search index serves everythingGalene, Cleo and the feed index are different
Auto-remediation removes on-callHumans handle what automation fails to fix
Posts show the current systemThey are dated
Our re-implementations are LinkedIn's codeThey are teaching code

Cheat sheet ​

TopicRemember
SpineOnline store, change stream, log, derived systems
KafkaPull, partitions, consumer groups, at-least-once
DatabusCommit order, relay, bootstrap
BrooklinBridge and mirror, replaced MirrorMaker
EspressoPartition key, MySQL storage nodes, Helix
VeniceDerived data, push jobs, swap
PinotColumnar, derived, no joins
FollowFeedFan-out on read, 720 partitions
CleoPrefix, bloom, forward index
LIquidSecond degree, Datalog, triples
Rest.li and D2Uniform API, client-side discovery
CachingNear the store; SCN order; tombstones
NurseMonitoring requests workflows
LabelsQuote it or call it inference

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Commit logAppend-only ordered record sequence
PartitionOne log shard of a topic
Consumer groupConsumers that split a topic's partitions
OffsetPosition in a partition
SCNSystem change number, a logical commit timestamp
DatabusLinkedIn's change data capture system
BrooklinStreaming bridge between stores and messaging systems
SamzaStream processing framework
EspressoLinkedIn's document store
VoldemortLinkedIn's earlier key-value store
VeniceDerived-data platform
Derived dataData computed from another source of truth
PinotReal-time OLAP store
FollowFeedFeed infrastructure
Fan-out on readBuild the feed at request time
GaleneSearch architecture
CleoTypeahead library
LIquidGraph database
Rest.liREST+JSON service framework
D2Dynamic discovery layer
CouchbaseDistributed store used as a cache tier
FrameFeature description system
Pro-MLProductive Machine Learning program
NurseAuto-remediation platform
InferenceClaim not stated by a cited source
TombstoneMarker 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.

Built by Morteza Negahi