In-Memory User File Store with Quota Eviction

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement an in-memory multi-tenant storage engine CloudStorage that tracks per-account byte budgets, stored files, and automatic space reclamation when an account's budget shrinks.

Support the following methods on CloudStorage:

  • create_user(user_id: str, capacity: int) -> bool — Provision a new account user_id with a byte ceiling of capacity. Raise ValueError if capacity < 0 (0 is allowed). If user_id already exists, leave its state and ceiling untouched and return False; otherwise create the account and return True.
  • upload_file(user_id: str, file_id: str, size: int) -> bool — Store a file named file_id consuming size bytes under user_id. Raise ValueError if size <= 0, and raise KeyError if user_id is unknown. Return False without modifying state if file_id already exists under user_id or if current_usage + size > capacity (an exact fit current_usage + size == capacity succeeds); otherwise record the file and return True.
  • delete_file(user_id: str, file_id: str) -> bool — Raise KeyError if user_id is unknown. If file_id is absent from user_id's account, return False; otherwise remove the file, reclaim its size bytes, and return True.
  • update_quota(user_id: str, new_capacity: int) -> List[str] — Raise ValueError if new_capacity < 0, and raise KeyError if user_id is unknown. Set user_id's byte ceiling to new_capacity. Whenever the account's stored byte total exceeds new_capacity, repeatedly evict one file at a time until total usage is <= new_capacity: always evict the file with the largest size first, breaking equal-size ties by the lexicographically smallest file_id. Return the evicted file_id strings in exact eviction order (or [] when no eviction is needed).
  • get_usage(user_id: str) -> int — Raise KeyError if user_id is unknown; otherwise return the sum of sizes of all live files currently held by user_id.

File namespaces are isolated per user (two different users may independently hold files with the same file_id), and concurrent calls across threads must execute atomically without violating byte ceilings.

Examples

Example 1

store = CloudStorage()
store.create_user("maya", 120)                # True
store.upload_file("maya", "video.mp4", 75)    # True  (75 / 120 bytes used)
store.upload_file("maya", "archive.zip", 60)  # False (75 + 60 = 135 > 120; rejected)
store.upload_file("maya", "notes.md", 30)     # True  (105 / 120 bytes used)
store.update_quota("maya", 50)                # ["video.mp4"]
store.get_usage("maya")                       # 30

Walk-through: Uploading "archive.zip" (60 bytes) would push Maya's usage to 135 > 120, so it fails without altering her 75-byte usage, allowing "notes.md" (30 bytes) to fit at 105 bytes. Lowering her ceiling to 50 forces eviction of her largest file "video.mp4" (75 bytes), dropping usage to 30 <= 50 and leaving "notes.md" intact.

Example 2

store = CloudStorage()
store.create_user("devon", 250)               # True
store.upload_file("devon", "log_b", 80)       # True
store.upload_file("devon", "log_a", 80)       # True
store.upload_file("devon", "readme", 45)      # True  (205 / 250 bytes used)
store.delete_file("devon", "readme")          # True  (160 / 250 bytes used)
store.update_quota("devon", 90)               # ["log_a"]
store.update_quota("devon", 0)                # ["log_b"]
store.get_usage("devon")                      # 0

Walk-through: Deleting "readme" frees 45 bytes, leaving two 80-byte files (160 bytes total). Cutting the ceiling to 90 requires evicting one 80-byte file; "log_a" precedes "log_b" lexicographically, so "log_a" is removed first (80 <= 90). Setting the ceiling to 0 then evicts "log_b".

Constraints

  • user_id and file_id are non-empty strings.
  • Valid capacity and new_capacity values satisfy 0 <= capacity <= 10^12; negative values raise ValueError.
  • Valid size values satisfy 1 <= size <= 10^12; non-positive values raise ValueError.
  • Up to 10^5 total operations may be executed; repeated update_quota calls must avoid re-sorting all remaining files from scratch on every call.

Step-by-step walkthrough

  1. Pin down the API contract and edge rules

    Before selecting data structures, settle every boundary condition from the specification:

    • Unknown accounts: Every method other than create_user raises KeyError when user_id is absent.
    • create_user(user_id, capacity): Returns True when registering a fresh account, or False (leaving state unchanged) if user_id already exists. Raises ValueError if capacity < 0 (capacity == 0 is valid).
    • upload_file(user_id, file_id, size): Raises ValueError if size <= 0. Returns False (leaving state unchanged) if file_id already exists under that account or if used + size > capacity (an exact fit used + size == capacity succeeds).
    • delete_file(user_id, file_id): Deletes the file, reclaims its bytes, and returns True; returns False when file_id is not present.
    • update_quota(user_id, new_capacity): Raises ValueError if new_capacity < 0. Updates the byte ceiling and repeatedly evicts files while used > new_capacity — largest size first, breaking ties by lexicographically smallest file_id — returning evicted file_ids in eviction order.
    • get_usage(user_id): Returns the account's current stored byte sum.
  2. Why sorting on every quota cut is too slow

    A naive implementation keeps files = {file_id: size} per account, giving O(1) upload_file and delete_file. Whenever update_quota drops the ceiling below used, it sorts all F live files by (-size, file_id) in O(F log F) time and pops from the front until usage fits.

    Why does that hit a wall at 10^5 calls? Suppose an account uploads 50,000 files of 2 bytes each (100,000 bytes total), followed by 50,000 calls to update_quota trimming the ceiling by 2 bytes per call:

    Cut 1 (ceiling 99,998): sorts 50,000 files just to evict 1 file
    Cut 2 (ceiling 99,996): sorts 49,999 files just to evict 1 file
    ...
    Total sort work: 50,000 + 49,999 + ... + 1 ≈ 1.25 * 10^9 elements sorted!
    

    We want a data structure that yields the next eviction victim in O(log F) time without re-sorting untouched files.

  3. Key idea: Max-heap via (-size, file_id) plus lazy deletion

    A min-heap (Python's heapq, a binary tree packed in a list whose smallest item sits at index 0) pops its minimum element in O(log h) time. How do we make a min-heap pop the largest size first while breaking equal-size ties by the smallest file_id? Push the 2-tuple (-size, file_id):

    Tuple comparison in Python's min-heap:
      (-80, "z_log") < (-45, "a_doc")   --> larger size (80 > 45) pops first!
      (-80, "log_a") < (-80, "log_b")   --> equal size (80 == 80): smaller ID ("log_a") pops first!
    

    Negating size reverses numeric order while keeping file_id in natural lexicographical order.

    What happens when delete_file(user_id, file_id) removes a file sitting deep inside the heap? Scanning the heap array would cost O(F). Instead we use lazy deletion:

    1. Pop file_id immediately from user.files and subtract size from user.used in O(1) time, leaving the old (-size, file_id) tuple inside user.heap.
    2. Later, when update_quota pops (-size, file_id) from user.heap, check user.files.get(file_id) == size. If file_id was deleted (or deleted and re-uploaded with a different size), that check is False, so we discard the stale tuple and continue!
    3. To prevent stale tuples from accumulating unboundedly when an account deletes thousands of files without cutting quota, whenever len(user.heap) > 2 * len(user.files) + 16 we rebuild user.heap from user.files via heapq.heapify in O(F) linear time (O(1) amortized per delete).
  4. Model per-account state and mutex protection

    Each account owns an isolated _User record holding capacity, used (a running byte counter for O(1) fit checks), files, and heap.

    To make check-then-act sequences safe across concurrent threads, CloudStorage guards public methods with with self._lock:. Even under CPython's Global Interpreter Lock (GIL), thread switches can occur between evaluating user.used + size <= user.capacity and incrementing user.used, which would let two racing uploads overshoot the ceiling without a mutex.

    from typing import Dict, List, Tuple
    import heapq
    import threading
    
    
    class _User:
        """Per-user storage record: byte quota, current usage, live files, and eviction heap."""
    
        def __init__(self, capacity: int):
            self.capacity: int = capacity
            self.used: int = 0
            # files: dict[str, int] mapping live file_id -> current size in bytes
            self.files: Dict[str, int] = {}
            # heap: min-heap of (-size, file_id) tuples so the largest size (most negative -size)
            # pops first, and equal sizes break ties by lexicographically smallest file_id.
            self.heap: List[Tuple[int, str]] = []
    
        def _compact_heap(self) -> None:
            """Rebuild the heap from live files in O(F) time so deleted entries cannot accumulate."""
            rebuilt: List[Tuple[int, str]] = []
            for file_id, size in self.files.items():
                rebuilt.append((-size, file_id))
            heapq.heapify(rebuilt)
            self.heap = rebuilt
    
    
    class CloudStorage:
        def __init__(self):
            # _users: dict[str, _User] mapping user_id -> per-user state
            self._users: Dict[str, _User] = {}
            self._lock = threading.Lock()
    
        def _get_user(self, user_id: str) -> _User:
            user = self._users.get(user_id)
            if user is None:
                raise KeyError(f"unknown user {user_id!r}")
            return user
    
        def create_user(self, user_id: str, capacity: int) -> bool:
            if capacity < 0:
                raise ValueError("capacity must be >= 0")
            with self._lock:
                if user_id in self._users:
                    return False
                self._users[user_id] = _User(capacity)
                return True
    
  5. Implement upload_file and delete_file

    upload_file checks size > 0, rejects duplicate file_ids or uploads where user.used + size > user.capacity, and otherwise updates files, used, and heap atomically.

    delete_file pops file_id from user.files and decrements user.used, compacting user.heap only when dead entries exceed 2 * len(user.files) + 16:

    def upload_file(self, user_id: str, file_id: str, size: int) -> bool:
        if size <= 0:
            raise ValueError("size must be positive")
        with self._lock:
            user = self._get_user(user_id)
            if file_id in user.files:
                return False
            # Strict '>' allows an exact fit where user.used + size == user.capacity.
            if user.used + size > user.capacity:
                return False
    
            user.files[file_id] = size
            user.used += size
            heapq.heappush(user.heap, (-size, file_id))
            return True
    
    
    def delete_file(self, user_id: str, file_id: str) -> bool:
        with self._lock:
            user = self._get_user(user_id)
            size = user.files.pop(file_id, None)
            if size is None:
                return False
    
            user.used -= size
            if len(user.heap) > 2 * len(user.files) + 16:
                user._compact_heap()
            return True
    
  6. Evict largest files first in update_quota

    update_quota assigns user.capacity = new_capacity (even when zero evictions occur!) and then loops while user.used > new_capacity:.

    Why can heapq.heappop(user.heap) never raise IndexError inside that loop? Because new_capacity >= 0, so user.used > new_capacity guarantees user.used > 0 — meaning at least one live file remains in user.files, and every live file still has its (-size, file_id) entry inside user.heap!

    Notice why we test user.files.get(file_id) != size rather than file_id not in user.files: if "log_a" was uploaded at 80 bytes, deleted, and re-uploaded at 15 bytes, user.heap holds both (-80, "log_a") and (-15, "log_a"). Testing != size skips the stale 80-byte tuple instead of evicting the 15-byte file prematurely!

    def update_quota(self, user_id: str, new_capacity: int) -> List[str]:
        if new_capacity < 0:
            raise ValueError("capacity must be >= 0")
        with self._lock:
            user = self._get_user(user_id)
            user.capacity = new_capacity
            deleted: List[str] = []
    
            while user.used > new_capacity:
                neg_size, file_id = heapq.heappop(user.heap)
                size = -neg_size
                # Skip stale heap entries from deleted files or files re-uploaded at a new size.
                if user.files.get(file_id) != size:
                    continue
    
                del user.files[file_id]
                user.used -= size
                deleted.append(file_id)
    
            return deleted
    
  7. Trace the examples and stale-entry skipping

    First, trace Example 1 ("maya" with ceiling 120):

    Operation                                  capacity  used  files                           heap (min first)                         Return
    ─────────────────────────────────────────  ────────  ────  ──────────────────────────────  ───────────────────────────────────────  ─────────────
    create_user("maya", 120)                        120     0  {}                              []                                       True
    upload_file("maya", "video.mp4", 75)            120    75  {"video.mp4": 75}               [(-75, "video.mp4")]                     True
    upload_file("maya", "archive.zip", 60)          120    75  {"video.mp4": 75}               [(-75, "video.mp4")]                     False (135>120)
    upload_file("maya", "notes.md", 30)             120   105  {"video.mp4":75,"notes.md":30}  [(-75, "video.mp4"), (-30, "notes.md")]  True
    update_quota("maya", 50)                         50    30  {"notes.md": 30}                [(-30, "notes.md")]                      ["video.mp4"]
    

    Second, trace tie-breaking plus a deleted-and-resized file (capacity = 250):

    1. Upload ("log_b", 80), ("log_a", 80), ("readme", 45)  --> used = 205
       heap sorted view: [(-80, "log_a"), (-80, "log_b"), (-45, "readme")]
    2. delete_file("log_a")                                 --> used = 125, files = {"log_b": 80, "readme": 45}
    3. upload_file("log_a", 15)                             --> used = 140, files = {"log_b": 80, "readme": 45, "log_a": 15}
       heap now holds: (-80, "log_a") [STALE!], (-80, "log_b"), (-45, "readme"), (-15, "log_a")
    4. update_quota(50):
       - pop (-80, "log_a"): files.get("log_a") is 15 != 80 -> STALE, skip!
       - pop (-80, "log_b"): files.get("log_b") is 80 == 80 -> EVICT "log_b", used becomes 60 (> 50)
       - pop (-45, "readme"): files.get("readme") is 45 == 45 -> EVICT "readme", used becomes 15 (<= 50), STOP!
       Returns ["log_b", "readme"], leaving "log_a" (15 bytes) untouched.
    
  8. Complete solution

    Putting _User and CloudStorage together:

    from typing import Dict, List, Tuple
    import heapq
    import threading
    
    
    class _User:
        """Per-user storage record: byte quota, current usage, live files, and eviction heap."""
    
        def __init__(self, capacity: int):
            self.capacity: int = capacity
            self.used: int = 0
            # files: dict[str, int] mapping live file_id -> current size in bytes
            self.files: Dict[str, int] = {}
            # heap: min-heap of (-size, file_id) tuples so the largest size (most negative -size)
            # pops first, and equal sizes break ties by lexicographically smallest file_id.
            self.heap: List[Tuple[int, str]] = []
    
        def _compact_heap(self) -> None:
            """Rebuild the heap from live files in O(F) time so deleted entries cannot accumulate."""
            rebuilt: List[Tuple[int, str]] = []
            for file_id, size in self.files.items():
                rebuilt.append((-size, file_id))
            heapq.heapify(rebuilt)
            self.heap = rebuilt
    
    
    class CloudStorage:
        """In-memory storage with a byte quota per user.
    
        Every method except create_user raises KeyError when user_id does not exist.
        """
    
        def __init__(self):
            # _users: dict[str, _User] mapping user_id -> per-user state
            self._users: Dict[str, _User] = {}
            # Single mutex ensures check-then-act sequences (check quota -> add file) execute
            # atomically across concurrent threads.
            self._lock = threading.Lock()
    
        def _get_user(self, user_id: str) -> _User:
            user = self._users.get(user_id)
            if user is None:
                raise KeyError(f"unknown user {user_id!r}")
            return user
    
        def create_user(self, user_id: str, capacity: int) -> bool:
            """Add a user with `capacity` bytes of space.
    
            Returns False (and changes nothing) if user_id already exists.
            Raises ValueError if capacity < 0.
            """
            if capacity < 0:
                raise ValueError("capacity must be >= 0")
            with self._lock:
                if user_id in self._users:
                    return False
                self._users[user_id] = _User(capacity)
                return True
    
        def upload_file(self, user_id: str, file_id: str, size: int) -> bool:
            """Store a file of `size` bytes for the user.
    
            Returns False (and changes nothing) if the user already has file_id or if
            the file does not fit in the remaining capacity. Raises ValueError if size <= 0.
            """
            if size <= 0:
                raise ValueError("size must be positive")
            with self._lock:
                user = self._get_user(user_id)
                if file_id in user.files:
                    return False
                # Strict '>' allows an exact fit where user.used + size == user.capacity.
                if user.used + size > user.capacity:
                    return False
    
                user.files[file_id] = size
                user.used += size
                heapq.heappush(user.heap, (-size, file_id))
                return True
    
        def delete_file(self, user_id: str, file_id: str) -> bool:
            """Remove a file and free its bytes. Returns False if the user has no such file."""
            with self._lock:
                user = self._get_user(user_id)
                size = user.files.pop(file_id, None)
                if size is None:
                    return False
    
                user.used -= size
                # Lazy deletion leaves the old tuple in user.heap; if stale entries outnumber live
                # files by more than 2x (+ 16 slack), rebuild in O(F) to keep memory O(live files).
                if len(user.heap) > 2 * len(user.files) + 16:
                    user._compact_heap()
                return True
    
        def update_quota(self, user_id: str, new_capacity: int) -> List[str]:
            """Set the user's capacity to new_capacity.
    
            While the user's usage is above new_capacity, delete the largest file; among files
            of equal size, delete the lexicographically smallest file_id first.
            Returns the deleted file ids in deletion order. Raises ValueError if new_capacity < 0.
            """
            if new_capacity < 0:
                raise ValueError("capacity must be >= 0")
            with self._lock:
                user = self._get_user(user_id)
                user.capacity = new_capacity
                deleted: List[str] = []
    
                # Invariant: while user.used > new_capacity >= 0, at least one live file exists,
                # and every live file has a matching (-size, file_id) entry in user.heap.
                while user.used > new_capacity:
                    neg_size, file_id = heapq.heappop(user.heap)
                    size = -neg_size
                    # Skip stale heap entries from deleted files or files re-uploaded at a new size.
                    if user.files.get(file_id) != size:
                        continue
    
                    del user.files[file_id]
                    user.used -= size
                    deleted.append(file_id)
    
                return deleted
    
        def get_usage(self, user_id: str) -> int:
            """Total bytes currently stored by the user."""
            with self._lock:
                return self._get_user(user_id).used
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of each user's storage account as a locker with a weight limit (capacity), an inventory sheet tracking live boxes and their combined weight (files dictionary + used counter), and a priority chute (heap) arranged so the heaviest box is always waiting right at the door if the locker shrinks. Because Python's heapq is a min-heap (a binary tree stored in an array that pops its smallest element in logarithmic time), pushing (-size, file_id) puts the largest size at the front while still breaking equal-size ties by the smallest alphabetical file_id. When a user deletes a file manually, we cross it off files immediately without searching the heap — a technique called lazy deletion (leaving outdated tuples inside the heap and skipping them later if they pop).

Why does the naive design fall short? Storing only a dictionary and sorting all F files inside update_quota costs O(F log F) on every quota cut — so 50,000 uploads followed by 50,000 small quota reductions performs over a billion comparisons just to evict one file per call! Conversely, scanning the heap array during delete_file to remove an arbitrary entry would cost O(F), whereas lazy deletion keeps manual deletes O(1) amortized.

Let's trace Example 2, where "devon" (capacity = 250) uploads ("log_b", 80), ("log_a", 80), and ("readme", 45), deletes "readme", and cuts the ceiling to 90:

1. Uploads:         used = 205, files = {"log_b": 80, "log_a": 80, "readme": 45}
                    heap order: [(-80, "log_a"), (-80, "log_b"), (-45, "readme")]
2. Delete "readme": used = 160, files = {"log_b": 80, "log_a": 80}  ((-45, "readme") stays lazily)
3. update_quota(90):
   - used (160) > 90 -> pop (-80, "log_a"): files.get("log_a") == 80 (live!) -> evict "log_a", used = 80
   - used (80) <= 90 -> stop! Returns ["log_a"] ("log_b" stays; tie broke to "log_a" < "log_b")

Complexity

Let U be the number of registered accounts and F be the number of currently live files under the target account (periodic compaction rebuilds user.heap whenever len(heap) > 2 * F + 16, keeping heap size h = O(F)).

  • create_user and get_usage: Time O(1) average, performing a single dictionary lookup (plus insertion for create_user) and reading an integer field.
  • upload_file: Time O(log F), since checking file_id in user.files and user.used + size > user.capacity are O(1) checks and heapq.heappush sifts across at most log2(h) = O(log F) heap levels.
  • delete_file: Time O(1) amortized, since popping from user.files and subtracting from user.used take O(1), and an O(F) heapq.heapify compaction runs only after at least F + 17 deletes have accumulated since the prior compaction.
  • update_quota: Time O((k + s) log F) for one call that evicts k live files and discards s stale heap tuples, and O(N log F) total across N operations because each uploaded tuple can be popped at most once in its lifetime (raising or keeping a non-binding ceiling takes O(1)).
  • Space: O(U + total_live_files), storing O(F) dictionary entries and at most 2 * F + 16 heap entries per user.

Edge cases

  • Updating ceiling to 0: Evicts all live files in (-size, file_id) order until used == 0; subsequent uploads return False until the ceiling is raised.
  • Exact-capacity fit and eviction stop condition: user.used + size == user.capacity succeeds (> rather than >=), and while user.used > new_capacity halts as soon as used == new_capacity.
  • Single file larger than entire ceiling: Rejected cleanly by user.used + size > user.capacity without mutating state.
  • Deleting a missing file (or deleting twice): user.files.pop(file_id, None) returns None, so delete_file returns False without altering used.
  • Delete followed by re-uploading the same file_id at a different size: If "log_a" was 80 bytes, deleted, and re-uploaded at 15 bytes, user.files.get("log_a") is 15 != 80, so update_quota skips the stale (-80, "log_a") tuple instead of evicting "log_a" early.
  • Ceiling increase or non-binding decrease: When user.used <= new_capacity, user.capacity updates in O(1) time and [] is returned.
  • Account isolation and invalid arguments: Identical file_ids under separate accounts never collide; unknown user_ids raise KeyError, and capacity < 0 or size <= 0 raises ValueError.

Common mistakes

  • Reversing both size and file_id on ties: Sorting (size, file_id) with reverse=True evicts "log_b" before "log_a" when sizes tie! Negating only size ((-size, file_id)) in a min-heap puts largest sizes first and smallest file_ids first.
  • Testing file_id in user.files instead of user.files.get(file_id) == size: When "log_a" (80B) is deleted and re-uploaded as "log_a" (15B), "log_a" in user.files is True when (-80, "log_a") pops — evicting "log_a" prematurely AND subtracting 80 instead of 15 from user.used!
  • Skipping user.capacity = new_capacity when used <= new_capacity: Returning [] early without updating user.capacity leaves the account stuck at its old ceiling.
  • Recomputing sum(user.files.values()) on every upload or eviction loop: Degrades O(1) fit checks into O(F) linear scans.
  • Relying on the Python GIL instead of an explicit lock: Two threads can both pass used + size <= capacity before either increments used, pushing stored bytes past capacity.

Alternative approaches

  • Balanced binary search tree / SortedList: Storing (-size, file_id) in an ordered tree (TreeSet in Java, std::set in C++, or sortedcontainers.SortedList in Python) gives worst-case O(log F) upload_file, delete_file, and per-file eviction with zero stale tuples, though Python's standard library lacks a balanced tree.
  • Indexed binary heap: Tracking file_id -> heap_index on every swap allows delete_file to remove arbitrary heap items directly in O(log F) time without lazy deletion, at the cost of hand-rolling sift-up and sift-down helpers instead of using heapq.

Follow-up questions

  • How would you adapt the data model for collaborative workspaces where files created by different members count toward one shared folder budget? Extract quota accounting into a standalone QuotaPool record (capacity, used, files, heap) so each personal drive and each shared workspace owns its own QuotaPool. Uploading into a shared workspace checks and charges that folder's QuotaPool (and if per-member ceilings also apply, verifies both the member pool and folder pool before mutating either). When locking per pool, acquire multiple pool locks in a fixed canonical order (such as sorted pool_id) so concurrent uploads can never deadlock.
  • Which locking strategies would let high-throughput multi-threaded callers operate on separate accounts without bottlenecking on one global mutex? A single threading.Lock serializes unrelated accounts, so a heavy eviction on Maya stalls uploads by Noah. Because distinct accounts share zero state, move to a per-account Lock stored on _User, holding a tiny directory lock (or sharded bucket locks / ConcurrentHashMap in Java) only long enough to look up or insert the _User reference. If read calls like get_usage dominate mutations, a readers-writer lock (allowing concurrent readers or one exclusive writer) or partitioning user_id hashes across single-threaded workers removes contention further.
  • If account quotas and file catalogs must survive sudden power loss on disk, how would you structure durable writes and crash recovery? Append every mutation (CREATE_USER, UPLOAD, DELETE, UPDATE_QUOTA with its evicted file_id list and a CRC32 checksum) to an append-only write-ahead log (WAL) and flush it to durable media via fsync (an OS call forcing buffered writes onto physical storage) before acknowledging the call. Periodically write a compact checkpoint snapshot of all accounts' capacity and files to a temporary file, fsync it, and atomically rename it into place alongside its covered WAL byte offset. On restart after a crash, load the latest snapshot, replay WAL entries past that offset (ignoring any truncated tail entry with a bad checksum), and rebuild each account's eviction heap in O(F) via heapq.heapify.

Follow-up questions

Similar questions

More CloudKitchens interview questions

All 7 CloudKitchens questions →