Sub topic 13
Where skip lists are used in practice
This chapter assumes you can read the Python skip list from the earlier chapters and know that search, insert and delete take expected O(log n) time. It also assumes you know that spans give rank queries. Here you will see which real systems use skip lists and which properties made them the choice.
Redis sorted sets
A Redis sorted set (ZADD, ZRANGE, ZRANK) stores members ordered by a score. Large sorted sets use two structures together:
- A hash table maps each member to its score, so
ZSCOREis O(1). - A skip list orders entries by score, so range queries and rank queries are fast.
Redis stores a span in each forward pointer. That is the indexable skip list from the previous chapter, and it answers ZRANK in expected O(log n). Redis uses a promotion probability of 1/4 instead of 1/2, which gives shorter nodes and less memory per entry.
The sketch below shows the same two-structure design in Python. It uses a sorted list in place of the skip list, so insertion costs O(n) here. A skip list would bring that down to expected O(log n).
import bisect
class MiniSortedSet:
def __init__(self):
self.scores = {} # member -> score, O(1) lookup
self.order = [] # sorted (score, member) pairs
def add(self, member, score):
if member in self.scores:
old = (self.scores[member], member)
del self.order[bisect.bisect_left(self.order, old)]
self.scores[member] = score
bisect.insort(self.order, (score, member))
def score(self, member):
return self.scores.get(member)
def rank(self, member):
if member not in self.scores:
return None
return bisect.bisect_left(self.order, (self.scores[member], member))
def range(self, start, stop):
return [m for _, m in self.order[start:stop + 1]]
board = MiniSortedSet()
board.add("alice", 50)
board.add("bob", 30)
board.add("carol", 70)
print(board.rank("alice")) # 1
print(board.range(0, 1)) # ['bob', 'alice']Memtables in LSM-tree databases
LevelDB and RocksDB are write-optimized key-value stores. New writes go first to an in-memory table called a memtable. When the memtable is full, the store writes it to disk as a sorted file and starts a new memtable.
The memtable has to keep keys sorted, accept fast inserts, and allow range scans during the flush. A skip list meets all three requirements. It also has a concurrency advantage. LevelDB's memtable skip list never deletes nodes while the memtable is live, because a "delete" is stored as a new entry marking the key as deleted. Readers can therefore traverse without locks while a single writer inserts. HBase's in-memory store uses Java's ConcurrentSkipListMap for a similar job.
The flush works because level 0 of a skip list is a sorted linked list. Walking it once produces the file in order, with no extra sorting.
Java's concurrent collections
java.util.concurrent.ConcurrentSkipListMap and ConcurrentSkipListSet are the standard sorted, thread-safe collections in Java. Their operations use compare-and-swap on pointers instead of one global lock. Balanced trees are the usual alternative, but a rotation changes several nodes at once, so a lock-free version is much harder to write. A skip list insert changes only the pointers on the layers where the new node appears.
Search engine postings lists
Lucene stores, for each term, a sorted list of the documents that contain it. A query for two terms intersects two such lists. Stepping through both one document at a time is slow when one list is much longer than the other. Lucene writes skip data into the index at regular intervals, in several levels. The reader can jump ahead to the first entry at or past a target document ID. This uses the layered idea, but the structure is built once and then only read. It has no random heights and no inserts.
When the choice makes sense
| Need | Why a skip list fits |
|---|---|
| Sorted order plus fast inserts | Level 0 is a sorted list, and each insert touches few nodes |
| Concurrent readers and writers | Local pointer changes make lock-free designs practical |
| Rank or range queries | Spans and the bottom layer support both |
| Simple code | There are no rotations or rebalancing cases |
A skip list is a weaker choice when memory is tight, because each node stores several pointers. Cache locality also suffers, since nodes are scattered across the heap. If you need a hard worst-case bound, a balanced tree gives one, and a skip list only gives an expected bound.
Exercise
A database keeps its recent writes in memory and must flush them to disk in key order. Give two reasons a skip list suits this memtable.
Show answer
Level 0 is a sorted linked list, so one walk along it produces the sorted output with no extra sort. Inserts change only a few local pointers, which supports fast writes and makes it practical for readers to traverse without locks while a writer inserts.