KatInterview

Prefix-Caching Transform Runner with Single-Flight and LRU

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencylru-cachehashing

Last 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.

  1. 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.
  2. 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.
  3. Bounded LRU cache. At most capacity completed 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 >= 1
  • 0 <= len(stages) <= 50
  • image_bytes can be up to 10 MB
  • Stage arguments are JSON-serializable dictionaries
  • apply_op is 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…