Prefix-Caching Transform Runner with Single-Flight and LRU
Data Structure DesignModel answerLast updated
Build a thread-safe runner for chains of deterministic byte transforms that reuses cached prefixes, collapses concurrent duplicate work into one execution, and bounds memory with LRU eviction.
Context
Several worker threads in an image service repeatedly run chains of deterministic transforms (resize, blur, grayscale, and so on) on the same source images. Many chains begin with the same steps, so recomputing those steps wastes CPU time. Build a component that avoids this.
Task
Implement a thread-safe PipelineExecutor that runs an ordered list of transform stages and reuses intermediate outputs wherever possible. It must meet three requirements.
- Prefix caching by content identity. The identity of each intermediate result must be a deterministic function of three things: the identity of the previous stage's result, the operation name, and the operation's arguments. If a new request shares a leading run of stages with an earlier one on the same input, it must resume from the furthest stage already available instead of starting over.
- Single-flight execution. If several threads need the same intermediate result at the same moment and it is not yet cached, exactly one of them runs the transform. The others wait and then receive that result.
- Bounded LRU cache. At most
capacitycompleted intermediate results may be stored. When the limit is exceeded, discard the least recently used completed result. Work that is still running must never be evicted.
Interface
from typing import Callable, Any
class PipelineExecutor:
def __init__(self, capacity: int,
apply_op: Callable[[str, bytes, dict[str, Any]], bytes]):
"""
capacity: max number of completed intermediate results kept.
apply_op: deterministic f(op_name, input_bytes, kwargs) -> output_bytes.
"""
def run(self, image_bytes: bytes,
stages: list[tuple[str, dict[str, Any]]]) -> bytes:
"""
Apply each (op_name, kwargs) in order, starting from image_bytes,
and return the final bytes.
"""
Examples
Shared prefix
ex = PipelineExecutor(capacity=4, apply_op=my_apply)
a = ex.run(img, [("resize", {"w": 256}), ("blur", {"r": 3})])
# resize and blur both execute.
b = ex.run(img, [("resize", {"w": 256}), ("grayscale", {})])
# The resize result is found in the cache; only grayscale executes.
Simultaneous identical requests
# Two threads call at the same time:
# run(img, [("heavy_filter", {"k": 5})])
# apply_op("heavy_filter", img, {"k": 5}) must be invoked exactly once,
# and both threads must receive the same output.
Constraints
capacity >= 10 <= len(stages) <= 50image_bytescan be up to 10 MB- Stage arguments are JSON-serializable dictionaries
apply_opis deterministic and thread-safe, but may be slow and CPU-bound- Neither cache hits nor waiting on another thread's work may use busy waiting
What to deliver
Explain your design, then give working code. Cover how you build the identity keys, how you prevent duplicate work, how eviction interacts with running work, what happens when apply_op raises, and the complexity.
Hints
Hint 1
Give each intermediate result a key derived from the previous key plus the op name and kwargs, starting from a hash of the input bytes. Serialize the combination in a canonical form (sorted keys, fixed separators) so equal inputs always give equal keys and different stage lists cannot collide.
Hint 2
Keep two structures under one lock: an ordered map of completed results (this is the LRU) and a map of in-flight computations, each with an event that waiters block on. Decide whether you are the owner or a waiter inside a single critical section, and run apply_op outside the lock.
Hint 3
Compute all stage keys first, then scan from the last stage backwards to find the furthest key that is either completed or in flight. When finishing a computation, move the key from in-flight to completed in the same critical section, store the value on the flight object before signaling, and give waiters the value through that object rather than via a cache re-lookup, so eviction cannot hurt them…
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
1. Identity of an intermediate result
Define a chain of hashes:
k0 = SHA256(image_bytes)ki = SHA256(json([k(i-1), op_i, kwargs_i]))
Serialize with sort_keys=True and compact separators. Because apply_op is deterministic, ki fully identifies the bytes after stage i. Several properties follow:
- Two requests that share a prefix on the same image generate identical keys for that prefix, so the cache matches them with no extra logic.
- Order matters, because the previous key is hashed in.
resize then blurandblur then resizeget different keys. {"w":1,"h":2}and{"h":2,"w":1}serialize identically, thanks to key sorting.- Encoding a JSON list avoids delimiter ambiguity. Naive concatenation would let
"ab"+"c"collide with"a"+"bc". - A different source image gives a different
k0, so identical ops on different images never share entries.
Hashing 10 MB costs a few milliseconds, which is small next to a real image transform.
2. State
Guard both structures with one threading.Lock:
done: anOrderedDictfrom key to bytes, ordered by recency. It holds at mostcapacityentries.inflight: a dict from key to aFlightobject containing athreading.Event, a value slot and an error slot.
Keeping the two maps under the same lock means "not cached and not running" is a single atomic observation, which is exactly what single-flight needs.
3. Algorithm for run
- If
stagesis empty, returnimage_bytes(the raw input is not cached). - Compute all keys up front.
- Under the lock, scan from the last stage backwards. The first key found in
donegives the starting bytes (and is marked most recently used). The first key found ininflightgives a flight to wait on. Resume from the stage after it. - For each remaining stage, call
get_or_compute(key, op, input, kwargs).
get_or_compute, in one critical section, does one of three things:
- the key is in
done: touch it and return the value; - the key is in
inflight: take a reference to that flight and become a waiter; - neither: create a flight, register it, and become the owner.
Outside the lock, the owner runs apply_op. A waiter calls event.wait(), which blocks in the OS rather than spinning.
4. Publishing and eviction
When the owner finishes, it:
- takes the lock, removes the key from
inflight, inserts it intodone, and evicts oldest entries whilelen(done) > capacity; - releases the lock;
- stores the value on the flight, then calls
event.set().
A newcomer always sees the key in exactly one of the two maps. There is no window where it is in neither, which would trigger duplicate work. Waiters read the value from their flight reference, not from done. So even with capacity = 1, where the entry may be evicted right after insertion, waiters still get a correct result.
Only done is subject to eviction, so running work is never evicted by construction.
5. Failures
If apply_op raises, the owner removes the flight from inflight, stores the exception, sets the event and re-raises. Waiters re-raise the same exception. Nothing is cached for that key, so a later call can retry. No thread hangs.
Code
import hashlib
import json
import threading
from collections import OrderedDict
from typing import Any, Callable
class _Flight:
__slots__ = ("event", "value", "error")
def __init__(self):
self.event = threading.Event()
self.value = None
self.error = None
def wait(self) -> bytes:
self.event.wait()
if self.error is not None:
raise self.error
return self.value
class PipelineExecutor:
def __init__(self, capacity: int,
apply_op: Callable[[str, bytes, dict[str, Any]], bytes]):
if capacity < 1:
raise ValueError("capacity must be >= 1")
self._cap = capacity
self._apply = apply_op
self._lock = threading.Lock()
self._done: OrderedDict[str, bytes] = OrderedDict()
self._inflight: dict[str, _Flight] = {}
@staticmethod
def _next_key(prev: str, op: str, kwargs: dict) -> str:
s = json.dumps([prev, op, kwargs], sort_keys=True,
separators=(",", ":"))
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def run(self, image_bytes, stages):
if not stages:
return image_bytes
keys, k = [], hashlib.sha256(image_bytes).hexdigest()
for op, kw in stages:
k = self._next_key(k, op, kw)
keys.append(k)
start, data, flight = 0, image_bytes, None
with self._lock:
for i in range(len(keys) - 1, -1, -1):
if keys[i] in self._done:
self._done.move_to_end(keys[i])
data, start = self._done[keys[i]], i + 1
break
if keys[i] in self._inflight:
flight, start = self._inflight[keys[i]], i + 1
break
if flight is not None:
data = flight.wait()
for i in range(start, len(stages)):
op, kw = stages[i]
data = self._get_or_compute(keys[i], op, data, kw)
return data
def _get_or_compute(self, key, op, inp, kwargs):
with self._lock:
if key in self._done:
self._done.move_to_end(key)
return self._done[key]
flight = self._inflight.get(key)
owner = flight is None
if owner:
flight = _Flight()
self._inflight[key] = flight
if not owner:
return flight.wait()
try:
out = self._apply(op, inp, kwargs)
except BaseException as e:
with self._lock:
self._inflight.pop(key, None)
flight.error = e
flight.event.set()
raise
with self._lock:
self._inflight.pop(key, None)
self._done[key] = out
self._done.move_to_end(key)
while len(self._done) > self._cap:
self._done.popitem(last=False)
flight.value = out
flight.event.set()
return out
Complexity
With n stages and image size B:
- Hashing:
O(B)once for the input, plusO(n * |kwargs|)for the chain. - Cache operations:
O(1)each, and the backward scan isO(n)withn <= 50. - Compute: only the uncached suffix calls
apply_op, and each distinct key runs once while it remains cached. - Memory:
O(capacity * B)for completed results, plus any results that waiters or running calls still hold. - Lock hold time is short and independent of
B, since transforms run outside the lock.
Trade-offs and common mistakes
- Running
apply_opunder the lock. This is correct but serializes all workers and defeats the purpose. - Checking the cache and registering the flight in separate critical sections. Two threads can both see a miss and both compute.
- Moving a key from in-flight to done in two separate lock acquisitions. A newcomer can see neither and recompute.
- Having waiters re-read the cache. The result may already have been evicted, particularly at
capacity = 1. Pass the value through the flight object. - Signaling before storing the value. Waiters would read an empty result.
- Polling with sleep loops. Use an event or condition variable.
- Weak keys. String concatenation, unsorted kwargs, or leaving out the previous key produce collisions or missed hits.
- Forgetting that an error must wake waiters. Otherwise they block forever.
Edge cases
- Empty
stagesreturns the input unchanged. - Later stage still running after earlier ones were evicted: the backward scan finds the flight and waits instead of recomputing the prefix.
- A failed key is not poisoned, so a retry recomputes it.
- Non-JSON kwargs are excluded by the constraints. In production, validate them.
Possible extensions
Bound the cache by total bytes rather than entry count, since 10 MB images vary in size. Use per-key locks or sharded maps to reduce contention. For multiprocess deployments, replace the in-memory maps with a shared store and a distributed lock or lease for single-flight.