liveBook · Manning

Law of large numbers

As explained in The Coder Cafe

The law of large numbers states that the average outcome of repeated random trials tends to approach the expected value as the number of trials increases.

The law of large numbers says that repeated random outcomes tend to approach their expected probability as the number of trials grows. In software, this supports probabilistic increment: replace many exact counter updates with fewer, weighted updates. section 6.11.1

Approximate like counts

For a popular post, choose N = 10. On each like, generate a random integer from 0 to 10; usually do nothing, but with probability 10%, increment the counter by 10. Across many likes, the counter approaches the true total while only about 1/N of requests query the database. section 6.11.1

The technique trades exactness for scalability:

  • Reduces database contention and latency by avoiding most counter updates. section 6.11.1
  • Fits popular posts whose counts tolerate approximation, but can produce odd results for posts with few likes. section 6.11.1
  • Requires careful selection of N; N may increase dynamically as the like count grows. section 6.11.1
// /like/{post_id} handler
function like(postID string) {
  if randomInt(N) == 0 {
    increment(postID, N)
  }
}

Shows the probabilistic like-handler implementation. section 6.11.1

How The Coder Cafe covers it

How deep it goes
Defines convergence, demonstrates coin flips and like counts, and discusses tuning and popularity limits without formal probability.
Examples
Uses repeated coin flips and a probabilistic social-media like counter with weighted increments.
What it assumes
Assumes basic counters, random integers, probabilities, and database updates while illustrating the convergence idea from zero.
What you can do after
Apply probabilistic increment to reduce counter-write frequency when approximate totals are acceptable.
How it connects
Ties probability to randomized algorithms, database contention, latency, hot rows, and approximate counters.

Also explained in

Compare how 2 books explain law of large numbers →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Coder Cafe. The section links point to the parts of the book it draws on.