Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

Skip Lists &
Probabilistic Multi-Level Indexing.

A skip list layers probabilistic express lanes on top of a sorted linked list so searches, insertions, and range scans run in O(log N) expected time without global tree rebalancing.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep storage layouts predictable as data grows, unlike AVL or Red-Black trees that require multi-node rotations, skip lists balance probabilistically via coin flips and support lock-free concurrent updates with simple pointer swaps.

TL;DR30-second simplified summary
▾

Skip lists stack up to MAX_LEVEL sorted linked lists where each node's height is chosen geometrically (p = 1/4 yields 1.33 pointers/node). Top-down traversal reaches any key in O(log⁡N)O(\log N) expected steps.

Adding span weights to forward pointers enables O(log⁡N)O(\log N) order-statistic queries (ZRANK), while Level-0 CAS linking + logical-delete marking make skip lists ideal for lock-free concurrent structures.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
B-Tree vs. LSM-Tree Storage Engines
B-Trees update fixed-size disk pages (4-16 KiB) in place for fast, predictable point and range reads, whereas LSM-Trees buffer writes sequentially in memory (MemTable + WAL) and merge immutable sorted runs (SSTables) in the background for orders-of-magnitude h...
Tree Data Structures
Tree data structures organize hierarchical or sorted keys so lookups, range scans, and updates run in O(log⁡BN)O(\log_B N) time, bridging the gap between CPU L1 cache lines and block-based NVMe/SSD storage.
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

From O(N) Linked Lists to Multi-Level Express Lanes.

Why this matters: See how adding sparse upper levels turns linear linked-list traversal into logarithmic binary-like search.

Imagine a subway line with local stops (Level 0) and express stops (Levels 1–3). To travel from station 0 to station 52, you ride the top express lane until the next stop overshoots 52, drop down one level, and repeat.

Because each upper level skips roughly 1/p of the nodes below it, a list of NN elements has expected height O(log⁡1/pN)O(\log_{1/p} N) and expected search path length O(log⁡N)O(\log N).

Top-Down Express-Lane Search Path

Level 3 (Express)Level 2Level 1Level 0 (Target)
02
STAGE 02 · RANDOMIZATIONfoundation

Probabilistic Level Assignment & Memory Overhead.

Why this matters: Calculate the expected pointer count and why p = 1/4 is preferred in memory-sensitive engines like Redis.

When inserting a node, we pick its height using geometric coin flips:

  • With p=1/2p = 1/2: expected pointers per node = ∑k=0∞(1/2)k=2.0\sum_{k=0}^{\infty} (1/2)^k = 2.0.
  • With p=1/4p = 1/4 (used by Redis zskiplist): expected pointers per node drops to 1.33, saving ~33% pointer memory at the cost of a slightly taller constant factor in search.
  • Always cap height at MAX_LEVEL (e.g., 32 for 2322^{32} or 4164^{16} elements) and seed a fast PRNG (xorshift / splitmix64) rather than a global mutex-locked RNG.
Lifecycle & Failure Recovery

Probabilistic Level Assignment & Memory Overhead

index scanfsync WALdeadlock / skewTx Active(Snapshot)Row Lock HeldWAL FlushedSerializationRetry
Engineering Decision Framework
Problem
How to implement Skip Lists & Probabilistic Multi-Level Indexing without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep storage layouts predictable as data grows, unlike AVL or Red-Black trees that require multi-node rotations, skip lists balance probabilistically via coin flips and support lock-free concurrent updates with simple pointer swaps.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Skip Lists & Probabilistic Multi-Level Indexing experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · ORDER STATISTICSintermediate

Forward-Pointer Spans for O(log N) Rank & Range Queries.

Why this matters: Augment forward pointers with node-skip counts so rank lookups (ZRANK) run in O(log N) without scanning Level 0.

A standard skip list finds a key in O(log⁡N)O(\log N), but counting how many elements precede it would take O(N)O(N).

By storing span[lvl] on each forward pointer—the exact number of Level-0 nodes between the current node and forward[lvl]—we accumulate rank += current.span[lvl] every time we step right during search. That yields exact 0-based or 1-based rank in O(log⁡N)O(\log N).

04
STAGE 04 · IMPLEMENTATIONintermediate

Bounded Skip List Insert & Search with Safe Level Clamping.

Why this matters: Implement a clean skip list insert and search with bounded MAX_LEVEL and explicit update[] predecessor tracking.

Tracking the update[0..level] predecessor array on the way down makes insertion purely local—zero global rotations:

import random

class SkipNode:
    __slots__ = ('key', 'val', 'forward')
    def __init__(self, key, val, level):
        self.key = key
        self.val = val
        self.forward = [None] * (level + 1)

class SkipList:
    def __init__(self, max_level=32, p=0.25):
        self.max_level = max_level
        self.p = p
        self.level = 0
        self.head = SkipNode(float('-inf'), None, max_level)

def _random_level(self):
        lvl = 0
        while random.random() < self.p and lvl < self.max_level:
            lvl += 1
        return lvl
Design Trade-Off

Bounded Skip List Insert & Search with Safe Level Clamping

Before · Seq Scan + Unbounded Bloat
  • Implicit cast breaks B-Tree
  • Deadlock or XID wraparound risk
  • Long tx blocks VACUUM
After · Indexed Plan + Bounded MVCC
  • Index-only scan in <2 ms
  • Deterministic lock ordering
  • Autovacuum keeps bloat flat
05
STAGE 05 · CONCURRENCYintermediate

Why RocksDB MemTables and Java ConcurrentSkipListMap Prefer Skip Lists.

Why this matters: Understand why lock-free CAS insertion at Level 0 followed by bottom-up upper-level linking outperforms locked RB-trees.

In a Red-Black tree, inserting a node can trigger rotations up to the root, forcing coarse locks. In a skip list:

  • Insert: First CAS-link the node at Level 0 (the linearization point), then link upper levels bottom-up.
  • Delete: Atomically mark next pointer as logically deleted (mark_bit) before physically unlinking, preventing concurrent traversals from splicing a new node onto a deleted node.
06
STAGE 06 · TRADE-OFFSadvanced

Skip List vs. Red-Black Tree vs. B-Tree.

Why this matters: Choose the right ordered index structure based on RAM vs. disk residency, cache lines, and concurrency.

  • Skip List: Best for concurrent in-memory ordered maps (ConcurrentSkipListMap), LSM MemTables, and ZSET rank indexing.

Weak CPU cache locality due to pointer chasing. - B-Tree / B+Tree: Best for disk/SSD and cache-line-friendly in-memory scans because keys sit contiguously in 4–16 KB nodes.

07
STAGE 07 · GOTCHASadvanced

Weak RNG Seeds, Pointer-Chasing Cache Misses & Delete Races.

Why this matters: Prevent O(N) degeneration and concurrency corruption in production skip-list implementations.

  • Unseeded or Contended RNG: Sharing a global rand() across threads serializes inserts on an RNG mutex; use thread-local xorshift64*.
  • Unbounded MAX_LEVEL: If MAX_LEVEL is too small (e.g., 8 for 100M keys), upper express lanes saturate and degrade to O(N)O(N).
Request & State Flow

Weak RNG Seeds, Pointer-Chasing Cache Misses & Delete Races

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does Redis use `p = 1/4` instead of `p = 1/2` for its `zskiplist` implementation?

Recommended Learning Flow