Data Structures: Advanced
A nightly pipeline is a set of tasks plus a set of rules of the form "this task waits for that one". That structure is a directed graph: each task is a node and each rule is an edge. Python holds one with no graph library at all. A dict mapping every task to the list of tasks it depends on stores the whole graph, and deps["join"] answers "what must finish before join?" in a single lookup.
Arrows run from a task to the tasks waiting on it, the reverse of how deps stores them.
Flipping the edges to find downstream impact
deps answers upstream questions. The on-call question runs the other way: if listings fails tonight, which tasks will never get fresh data? Answering it from deps means scanning every list for the name listings. Building a reversed dict once, mapping each task to the tasks that wait on it, turns each step of the search into one lookup. A breadth-first walk with a deque and a broken set then collects everything reachable.
The broken set does 2 jobs. It holds the answer, and it stops the walk from processing report twice, since report is reachable through both join and pricing. On a graph with a shared upstream table and hundreds of tasks, that check is what keeps the walk from revisiting the same subtree again and again.
Ordering tasks with in-degree counts
A scheduler needs an order in which every task runs after all of its dependencies, called a topological order. Kahn's algorithm finds one with 2 dicts and a queue. remaining counts how many dependencies each task still waits on; that count is the task's in-degree. Tasks at 0 go into the queue. Each time a task runs, every task downstream of it loses 1 from its count, and any count that reaches 0 joins the queue.
from collections import dequedeps = {"bookings": [],"listings": [],"clean": ["bookings"],"join": ["clean", "listings"],"pricing": ["join"],"report": ["join", "pricing"],}remaining = {task: len(parents) for task, parents in deps.items()}downstream = {task: [] for task in deps}for task, parents in deps.items():for parent in parents:downstream[parent].append(task)queue = deque(t for t in deps if remaining[t] == 0)order = []while queue:task = queue.popleft()order.append(task)print("run", task)for child in downstream[task]:remaining[child] -= 1if remaining[child] == 0:queue.append(child)print(order)
Kahn's algorithm: a task joins the queue when its remaining count hits 0.
Watch remaining["join"] during the run: it starts at 2 and the task enters the queue only after both clean and listings have run. The printed order is one valid schedule among several. Swapping bookings and listings at the front would satisfy every rule too, which is why 2 schedulers can disagree on order and both be correct.
Batches that can run in parallel
Kahn's queue hands out one task at a time, but a scheduler with spare workers can do better. Process the ready tasks as a wave: every task whose count reaches 0 during a wave goes into the next one. Tasks in the same wave share no path between them, so they can run at the same time, and the number of waves is the shortest possible run length when each task takes one step.
Only the first wave holds 2 tasks. The chain bookings, clean, join, pricing, report is the critical path, and adding workers can't shorten the run below 5 waves: speeding up the run means splitting or shortening a task on that chain.
A cycle shows up as tasks left behind
Here clean was rewired to wait on report, which waits on join, which waits on clean. Both sources run, each lowers a count from 2 to 1, and the queue empties with 3 tasks unreached. Run this check before the first task starts: a cycle discovered halfway through a run leaves some tables rebuilt and others stale.
set().union(*deps.values()) - set(deps) lists every dependency with no entry of its own. Without that check, one misspelled task name surfaces as a KeyError halfway through building downstream.A teammate adds 2 tasks to a new pipeline file and builds the reversed dict. What does this program print?
These figures come from 64-bit CPython 3.9 and cover each container alone. The strings and numbers inside are separate objects, and the next section measures them. A regular class keeps its attributes in a per-instance __dict__, so every instance pays for an object plus a dict. The slots class and the namedtuple both store 4 references in a fixed row; the namedtuple adds an 8-byte length field, so it measures 72 to the slots class's 64.
Fixed attributes with __slots__
Assigning a tuple of names to __slots__ in the class body tells Python to reserve exactly those attributes in each instance, with no __dict__ behind them. Reading and writing them works as before. Creating any other attribute raises AttributeError, which turns a misspelled field name into an error on the line that misspelled it.
Without a __repr__, printing an instance shows its class name and memory address, which changes on every run. A record type that ends up in logs needs one.
This class has no __slots__. What does the program print?
namedtuple: a tuple with field names
collections.namedtuple builds a tuple subclass whose positions also have names. It costs the same as a plain tuple, prints its fields, and unpacks like any tuple. Because it is immutable, it can be a dict key or a set member whenever its fields are hashable. Changing a field means building a new record with _replace, which leaves the original untouched.
Enforcing the schema where rows enter
Rows usually arrive as dicts, decoded from JSON or built by an earlier step. Converting them with Booking(**row) at the point where they enter the job does 2 things at once: it shrinks each record, and it rejects any row whose keys differ from the declared fields, before that row reaches the join.
| Record type | Bytes, 4 fields | Change a field? | Add a field later? | Fits when |
|---|---|---|---|---|
| dict | 232 | Yes | Yes | Rows arrive with varying keys or go straight to JSON |
| regular class | 152 | Yes | Yes | You need methods and hold few instances |
| class with `__slots__` | 64 | Yes | No | Millions of mutable records share one schema |
| namedtuple | 72 | No | No | Fixed records you read, group or use as keys |
The byte counts above came from a measurement, and every claim about speed or memory should come the same way. The standard library covers both sides: time.perf_counter() for elapsed time and sys.getsizeof() for the bytes of one object.
Timing code with perf_counter
perf_counter() returns seconds as a float counted from an arbitrary starting point, so only the difference between 2 calls means anything. A single run is noisy because other processes take CPU time, and that noise only ever adds time. Repeat the measurement several times and keep the minimum: it's the closest estimate of what the code itself costs.
Every probe is odd and every id is even, so all 1,000 lookups miss: the list compares each probe against all 10,000 ids, while the set hashes the probe and checks one slot. The booleans hold on any machine. The raw seconds, which you can print yourself, change with the hardware. The last 2 lines show the bill for that speed: the set needs a hash table with spare room, and it pays for it in bytes.
Why sys.getsizeof is shallow
sys.getsizeof counts the object you hand it and none of the objects it refers to. A list's size is its header plus one 8-byte reference per slot, whether a reference points at a 1-character string or a 10 MB one. To measure a whole structure, walk it and add up every object you reach, counting each object once by its id(), because 2 records can share the same string.
The shallow figure is the list header and 2 references. The deep figure adds both dicts at 232 bytes each, then the keys and values. The 2 "Lisbon" literals are one shared object in this program, and so are the key strings, so seen counts each of them once. Without seen, the walk would report shared strings once per record and overstate the total.
What does this program print?
Trading memory for time, and back
The set bought speed with memory. A generator makes the opposite trade. It holds one value at a time, so its size stays fixed no matter how many values it will yield, but it produces them only once. A second pass over the same generator finds it already exhausted and sees nothing.
- A set or dict index beside a list for membership tests
- A cache holding results of slow calls
- A materialized list you will read many times
- A generator that recomputes values on each pass
- Scanning a list instead of keeping a set index beside it
- Recomputing a rare result instead of storing it
- ▸Measure at the size you run in production: a list and a set look alike at 10 items.
- ▸Repeat each timing and keep the minimum, since noise only adds time.
- ▸Time one change at a time, with the same input for both versions.
- ▸Treat
sys.getsizeofas the container alone; walk the structure for the real total. - ▸Measure before rewriting anything, then measure again to confirm the gain.
| Workload | Keys | Strategy |
|---|---|---|
| Currency code to display name | About 30, never change | Plain dict, no limit |
| Listing details for search pages | Millions, a few thousand hot | LRU with a size limit |
| Exchange rate per currency | Few, value changes hourly | TTL expiry plus a size limit |
| Fraud score per payment id | Every key unique | No cache: hit rate 0% |
A dict with no limit grows forever
LRU on top of dict ordering
A dict remembers insertion order, so it can double as the recency list. On a hit, pop the key and insert it again, which moves it to the end. On a miss with the cache full, the first key is the least recently used one, and next(iter(self.data)) reads it without building a list of all the keys.
class LRUCache:def __init__(self, capacity):self.capacity = capacityself.data = {}def get(self, key):if key not in self.data:return Nonevalue = self.data.pop(key)self.data[key] = valuereturn valuedef put(self, key, value):if key in self.data:self.data.pop(key)elif len(self.data) == self.capacity:oldest = next(iter(self.data))del self.data[oldest]print("evict", oldest)self.data[key] = valuecache = LRUCache(3)for listing in ["L1", "L2", "L3", "L1", "L4", "L2"]:if cache.get(listing) is None:print("miss", listing)cache.put(listing, listing.lower())else:print("hit", listing)print(list(cache.data))
Capacity 3: a hit moves a key to the end, a full miss evicts the first key.
L1 survives because its hit on the 4th access moved it behind L2 and L3. When L4 arrives, L2 is the oldest untouched entry and is evicted. However long the stream runs, data never holds more than 3 entries, and memory stays fixed at whatever 3 cached values cost.
collections.OrderedDict provides move_to_end() and popitem(last=False) for the same 2 moves, if you prefer named operations.
This loop uses the LRUCache class from the animation. What does it print?
Expiring entries with a time limit
Some values go stale. An exchange rate is right for an hour and then wrong. A TTL (time to live) cache stores each value with the moment it expires and treats an expired entry as a miss. Passing now in as an argument, instead of reading the clock inside, lets the example run with fixed numbers and print the same result every time.
Expiry fires only on a read. A key that is never read again stays in data forever, so a TTL by itself bounds staleness without bounding size. Production caches apply both rules: an entry leaves when it expires or when the size limit pushes it out.
Every caller shares the cached object
The cache returns the list it stores, so mine and cache["Lisbon"] are the same object. One caller's append changed what every later caller receives, and the cache now serves a listing that does not exist.
- Measure the hit rate before and after adding a cache
- Give every cache that sees unbounded keys a size limit
- Pair a TTL with a size limit so unread entries still leave
- Store immutable values, or hand callers a copy
- Cache results keyed on ids that never repeat
- Let a memo dict live as long as a server process
- Read the clock inside cache logic you need to test
- Return a cached list that callers can append to
| 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 |
One write path updates 3 indexes; each read path touches exactly one.
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
- ▸Only totals needed: stream the rows through a generator and keep running sums.
- ▸A small hot subset: keep it behind an LRU cache and fetch the rest on a miss.
- ▸Fixed schema, many rows: switch dict records to
__slots__classes or namedtuples. - ▸Every row needed by many processes: move it out of process memory into a database.
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.
> Picture the search side of a rental marketplace like Airbnb serving listing pages, city searches and price filters from an in-process layer that a nightly pipeline rebuilds. The rebuild must run its tasks in dependency order, fit millions of listings in one machine's memory, and drop exactly the cached results that a reloaded table made stale.
deps dict, and the same reversed graph tells the cache which entries to drop when bookings reloads.__slots__ class and 72 as a namedtuple on CPython 3.9.perf_counter, repeat and keep the minimum; sys.getsizeof counts one container, so walk structures for totals.Model pipelines as dict graphs, shrink records, measure before optimizing, bound caches, and pick structures per query.
- Category
- Python
- Difficulty
- advanced
- Duration
- 29 minutes
- Challenges
- 20 hands-on challenges
Topics covered: Representing a Graph With Dicts, Custom Structures, Performance Profiling, Caching Strategies, Choosing for Scale
Lesson Sections
- Representing a Graph With Dicts (concepts: Collections)
Exactly 2 tasks have empty lists. They are the sources: nothing sits upstream of them, so they can start the moment the run begins. Every other task waits until each name in its list has finished. Flipping the edges to find downstream impact Ordering tasks with in-degree counts Batches that can run in parallel A cycle shows up as tasks left behind If a task depends on itself through any chain of edges, no task on that loop ever reaches a count of 0. Kahn's algorithm then runs out of ready tasks
- Custom Structures (concepts: Dataclasses)
The join step loads every booking into memory before matching it to listings. With a few million bookings, the bytes each record's container costs decide whether the job fits on its machine. A dict per record is the default and also the largest option: each dict carries its own hash table, sized with room to grow, even though every record has the same 4 keys. Fixed attributes with __slots__ Without a __repr__, printing an instance shows its class name and memory address, which changes on every r
- Performance Profiling (concepts: Data Types)
Timing code with perf_counter Why sys.getsizeof is shallow Trading memory for time, and back
- Caching Strategies (concepts: functools)
A cache keeps the result of a slow call so the next call with the same input skips the work. Memoizing with a dict already does that. Running a cache in a long-lived service adds 2 questions: how often does a key come back, and when should an entry leave? The share of lookups answered from the cache is its hit rate. A cache with a 0% hit rate costs memory and saves nothing. A dict with no limit grows forever A memo dict never forgets an entry. That suits a small, fixed key space such as currency
- Choosing for Scale (concepts: 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. Every index is a write you must not forget 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