Choosing for Scale
Concepts covered: Collections
A production data layer is a set of structures kept in step, each answering one access pattern fast. Its design starts from the questions it must answer, and the shape of the incoming rows comes second. List the questions, pick one structure per question, and count what each structure adds to every write.
| Question the layer answers | Structure | Cost on every write |
|---|---|---|
| Fetch a listing by id | dict: id to record | 1 dict insert |
| All listings in a city | defaultdict(list): city to ids | 1 append |
| Listings priced between 2 values | Sorted prices plus bisect | Shifts later items on insert |
| Last 5 searches per user | dict of deque(maxlen=5) | 1 append, oldest drops |
| Top 3 by rating | heapq.nlargest at read time | None; work happens on read |
| Distinct guests today | set of guest ids | 1 set add |
- listing feed (source, in-memory events)
- store.add (transform, ListingStore method)
- by_id (storage, dict)
- by_city (storage, defaultdict(list))
- prices and ids (storage, sorted lists)
- listing page (consumer, lookup by id)
- city search (consumer, lookup by city)
- price filter (consumer, bisect range)
- listing feed -> store.add
- store.add -> by_id
- store.add -> by_city
- store.add -> prices and ids
- by_id -> listing page
- by_city -> city search
- prices and ids -> price filter
- Writes: listing feed, store.add
- Indexes: by_id, by_city, prices and ids
- Reads: listing page, city search, price filter
import bisect
from collections import defaultdict, namedtuple
Listing = namedtuple("Listing", ["listing_id", "city", "price"])
class ListingStore:
def __init__(self):
self.by_id = {}
self.by_city = defaultdict(list)
self.prices = []
self.ids = []
def add(self, listing):
self.by_id[listing.listing_id] = listing
self.by_city[listing.city].append(listing.listing_id)
pos = bisect.bisect_right(self.prices, listing.price)
self.prices.insert(pos, listing.price)
self.ids.insert(pos, listing.listing_id)
def price_between(self, low, high):
start = bisect.bisect_left(self.prices, low)
end = bisect.bisect_right(self.prices, high)
return self.ids[start:end]
store = ListingStore()
for row in [("L1", "Lisbon", 120), ("L2", "Porto", 85), ("L3", "Lisbon", 95),
("L4", "Lisbon", 210), ("L5", "Porto", 140)]:
store.add(Listing(*row))
print(store.by_id["L3"])
print(store.by_city["Lisbon"])
print(store.price_between(90, 150))Output:
Listing(listing_id='L3', city='Lisbon', price=95) ['L1', 'L3', 'L4'] ['L3', 'L1', 'L5']
Each read touches one index. by_city answers the city search without scanning listings. The price filter finds both ends of the range with 2 binary searches and slices between them, so it never looks at the listings priced at 85 or 210. prices and ids stay parallel because add inserts into both at the same pos.
Every index is a write you must not forget
Each index makes one read fast and makes every write touch one more structure. A delete that updates by_id and by_city but skips the price lists leaves a listing that no longer exists showing up in price searches. Routing every write through the class's own methods keeps the indexes consistent; code outside the class should never append to by_city directly.
Estimating before the layer stops fitting
Size the layer before it reaches production. Measure the deep size of the store at 10,000 listings, multiply by the growth factor to the real row count, and compare the result with the memory of the machine that will run it. Check the write path at that scale as well: inserting into a sorted list shifts every later element, and loading 1 million listings in random order moves roughly 250 billion references. A bulk load should append everything and sort once at the end.
A cache keyed by task goes stale along the graph: when a source table reloads, every task reachable from it in downstream computed its result from old data, so those entries leave with it.
About this lesson
This section is part of the Data Structures: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.