skip to content

Keeping an exact removal order over millions of entries costs work on every access; what do stores buy instead, and what does it cost?

level: seniorimportance: should knowfreq 55%

answer

  1. order kept, or order guessed
  2. a maintained structure on every read
  3. a small sample at removal time
  4. close to worst, not worst
  5. near-miss severity depends on the entry

basics

~20 s

Exact order needs a per-entry structure maintained on every access, so most stores inspect a small sample at removal time and take the best candidate in it. The removal is usually a near-miss rather than the true worst entry.

solid answer

~40 s

An exact ranking means holding every resident entry in an order the store repairs on each access: bytes per entry, reads that write metadata, and on a multi-threaded server one structure every request must modify. Few stores pay it. Instead, when a write needs memory, the store inspects a small sample, scores those entries on whatever criterion it ranks by, and removes the best candidate found; some designs carry the strongest candidates forward in a small pool, so later rounds compare against earlier survivors. The removal is therefore close to the worst entry but not guaranteed to be it. For a recomputable entry a near-miss costs one extra fetch; for state with no other copy it destroys the wrong irreplaceable entry. Sample size trades removal quality against latency, and stores differ throughout.

code

pseudocode · 10 lines
pseudocode
choose_victim(keyspace, candidate_pool, sample_count):
    sample = draw_random_entries(keyspace, sample_count)
    for entry in sample:
        candidate_pool.offer(entry, staleness_score(entry))
    candidate_pool.keep_strongest(pool_capacity)

    victim = candidate_pool.take_strongest()
    if victim is null or not still_resident(keyspace, victim):
        return no_victim_this_round
    return victim

go deeper

for a junior

Know that a store under memory pressure picks something to remove and that picking perfectly would be expensive, so the entry that goes is a good guess rather than a guaranteed worst case.

for a middle

Explain the three costs of an exact order - per-entry structure, work on every read, and a shared hot spot - and describe the sample-and-take-the-best alternative without quoting any sample size.

for a senior

Connect it to what you would see in production: removal work lands inside the write that triggered it, so a tier pinned at its ceiling shows latency as well as memory, and removal quality degrades exactly when pressure is highest.

for a principal

Decide whether a near-miss is tolerable for the population you hold. If the entries are irreplaceable, no sample size fixes it, and the real levers are eligibility, a separate tier, or headroom.

## What exact order would actually cost A policy that removes *the* least recently touched entry, or *the* least frequently accessed one, implies a total order over every resident entry, kept correct at all times. Concretely that means: - **Per-entry structure.** Links or an index position, stored alongside every entry. On a tier whose entries are small, that overhead competes with the entries themselves for the same ceiling. - **Work on every access, including reads.** The order changes when an entry is touched, so a read must repair the order. A read path that mutates shared state is a different thing from a read path that does not. - **A contention point.** Where the server handles requests on more than one thread, one global ordering structure is the hottest shared object in the process, and every request wants to modify it. The price is paid on every access forever, to improve a decision that is made only when memory is tight. That is a bad trade, and most stores decline it. ## What they buy instead At the moment a write needs memory, the store does something bounded and local: 1. Draw a **small sample** of resident entries — cheap, because it needs no maintained ordering, only the ability to reach arbitrary entries. 2. Score each sampled entry on the criterion the configured family names: how long since it was touched, how popular it is, how much lifetime remains. 3. Remove the best candidate in the sample. 4. Optionally **carry good candidates forward**: keep the strongest few in a small pool between rounds, so a later round compares new samples against survivors rather than starting from nothing. That makes successive removals better than independent draws without ever materialising a global order. The sample size is a design choice, and different stores choose differently; a larger sample gives a better victim and spends more time inside the write that provoked it. ## What the approximation costs The removed entry is drawn from a sample, so it is usually close to the worst but is not guaranteed to be the worst — that guarantee is exactly what was not paid for. Two consequences matter: - **Quality**: a genuinely warm entry can be removed while a colder one survives, simply because the colder one was not in the sample. Carrying candidates forward reduces how often this happens; it does not eliminate it. - **Blast radius**: the severity of a near-miss depends entirely on what the entries are. If the entry is a copy of something durable, the cost is one refetch. If the entry is a lease, a deduplication record or a half-built aggregate, the store just destroyed the wrong irreplaceable thing, and no policy quality would have made removal safe — only eligibility or a bigger ceiling would. ## The cost lands on the caller that triggered it Removal happens inside a write that could not otherwise be served, so sampling work is latency the caller experiences. A store under sustained pressure removes repeatedly, which is why a tier sitting hard against its ceiling often shows a latency change, not just a memory number. This is also why sample size is bounded: it is a knob between removal quality and write latency at the worst possible moment. ## Where implementations diverge - Some stores keep an exact order within a narrow scope where it is affordable — for example among entries sharing one fixed-size block class — and no global order at all. - Some sample and carry candidates forward; some sample afresh each time. - Some maintain an approximate age marker of reduced precision rather than a true last-touch time, trading resolution for bytes. - A store that allocates from fixed-size blocks is not asking *which entry in the keyspace is worst* at all; it is asking *which entry in the block size I need is worst*, which is a different and much smaller question. So the defensible framing is: exact order is a cost, not a feature that better stores buy. The interesting question is what the store does instead and whether the resulting near-miss is acceptable for the population held. ## What a strong answer sounds like It names the three costs of exact order, describes sampling as bounded work done at removal time rather than continuous work done at access time, states that the removed entry is a good candidate rather than the true worst, and then splits the consequence by what the entries are — because that split is the whole reason this matters on a store rather than only on a cache.

  • Why not just raise the sample size until the choice is effectively exact?
    Because the sampling runs inside the write that could not be served, so every extra candidate inspected is latency added at the moment the store is already under pressure. Quality improves with diminishing returns while cost rises linearly, which is why designs stop at a small sample and instead carry good candidates forward between rounds.
  • What does carrying candidates forward add over sampling afresh each time?
    Successive removals stop being independent draws. A pool of the best candidates seen so far means a new sample is compared against earlier survivors, so the store approaches the true worst entry over several rounds without ever holding a global order. It is memory for a handful of references rather than for every resident entry.
  • Does approximation matter if the tier is purely disposable copies?
    Much less. A near-miss then costs one extra fetch from the source, which is a small latency cost spread thinly. The reason to know about it anyway is that tiers rarely stay purely disposable: one team adds locks or deduplication records to the same store, and the same approximation quietly changes from a latency cost to a correctness one.

A librarian has to clear a shelf. Keeping a perfect ranking means recording every book's last borrow date at the desk on every single loan, forever, to win an argument that happens twice a year. Instead she walks the aisle, pulls five books at random, and removes the dustiest of the five, keeping a note of the dustiest few from earlier rounds. It is fast, it is close, and now and then it removes a book someone was about to want - and if that book was the only copy in existence, close was not good enough.

saying these in an interview costs you the question

  • Assumes eviction always removes the true worst entry.
  • Thinks sampling is a bug rather than a deliberate trade.
  • Says a bigger sample is free because removal is rare.
  • Believes exact ordering costs only memory, not access-path work.
  • Treats a near-miss as harmless because the entry can be refetched.
  • Assumes selection always ranges over the entire keyspace.