File Storage Manager with Quota Enforcement
Data Structure DesignModel answerLast updated
Build an in-memory file manager that tracks user storage, enforces capacity limits, and evicts largest files when quotas shrink.
You're building a file storage manager that needs to track multiple users, their files, and enforce storage limits.
Implement a system with these operations:
create_user(user_id, capacity)
Register a new user with a maximum storage limit in bytes. Return False if the user already exists, True otherwise. Reject negative capacities with ValueError.
upload_file(user_id, file_id, size)
Store a file under a user's account. Return False if:
- The file would push usage over the capacity limit
- A file with that
file_idalready exists for this user
Return True on success. Raise KeyError if the user doesn't exist.
delete_file(user_id, file_id)
Remove a file and free its space. Return True if removed, False if the file wasn't found. Raise KeyError for unknown users.
update_quota(user_id, new_capacity)
Change the storage limit. If current usage exceeds the new limit, automatically remove files until usage fits. Evict in this order:
- Largest file first
- Break ties by choosing the lexicographically smallest
file_id
Return a list of evicted file_ids in removal order. Raise KeyError for unknown users.
Constraints
- User and file identifiers are strings
- File sizes are positive integers
- Expect up to 10⁵ total operations
- Quota updates must handle mass evictions efficiently
Example
storage = FileManager()
storage.create_user("bob", 100)
storage.upload_file("bob", "doc.txt", 60) # True
storage.upload_file("bob", "img.png", 50) # False, would exceed 100
storage.update_quota("bob", 40)
# Returns ["doc.txt"], evicts the 60-byte file
# Leaves 0 bytes used out of 40
Edge Cases
- Setting quota to zero should evict everything
- Uploading a file larger than total capacity should fail immediately
- Deleting nonexistent files should not error
Hints
Hint 1
Track both a file map and current usage to avoid recalculating totals
Hint 2
Use a heap with (-size, file_id) tuples for efficient largest-file lookups
Hint 3
Consider lazy deletion: mark heap entries stale rather than removing them immediately
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is efficiently finding the largest file during quota shrinkage while supporting fast arbitrary deletions.
Data Structures Per User
Each user needs three components:
- File registry: Hash map
file_id → sizefor O(1) lookups, additions, and removals - Usage counter: Running total of bytes to avoid recomputing sums
- Eviction priority queue: Min-heap storing
(-size, file_id)tuples
The heap key structure handles the eviction rules automatically:
- Negating size makes Python's min-heap return the largest file first
- Tuple comparison breaks ties lexicographically by
file_id
Lazy Deletion Strategy
Removing an element from the middle of a heap costs O(n). Instead, we mark entries as stale:
delete_fileremoves from the file map only, leaving the heap entry untouched- When
update_quotapops an entry, it validates whetherfiles[file_id] == size - Mismatched or missing entries are stale and get discarded
This works because:
- A stale entry either refers to a deleted file (missing from map) or a re-uploaded file with different size
- The size check catches both cases
- Live files always have at least one valid heap entry from their upload
To prevent unbounded heap growth, compact when stale entries exceed live files by 2×. Rebuild the heap from the current file map in O(n).
Operation Implementations
create_user: Initialize the user struct with capacity, empty file map, zero usage, and empty heap.
upload_file:
- Validate user exists and file is new
- Check
current_usage + size <= capacity - Add to file map, increment usage counter, push
(-size, file_id)to heap
delete_file:
- Remove from file map, decrement usage
- Heap entry becomes stale naturally
- Trigger compaction if needed
update_quota:
- Set new capacity
- Pop from heap while
usage > capacity:- Skip entries where
files.get(file_id) != size(stale) - For live entries: remove from map, decrement usage, record eviction
- Skip entries where
- Return list of evicted file IDs
Correctness Invariants
usage == sum(files.values())always holds: every change updates both atomically- Every live file has a matching heap entry: uploads push, compaction rebuilds
- Stale entries never cause incorrect evictions: validation checks prevent acting on outdated data
- Eviction order matches requirements: heap key structure plus validation enforce largest-first, ties by smallest-id
- Minimal evictions: loop exits as soon as usage fits, deleting exactly what's needed
Complexity Analysis
Let n = current file count for a user, k = heap pops during quota update (including stale).
| Operation | Time | Reason |
|---|---|---|
create_user | O(1) | Simple initialization |
upload_file | O(log n) | Hash insert + heap push |
delete_file | O(1) | Hash delete only |
update_quota | O(k log n) | k pops, each O(log n) |
Each heap entry is pushed once and popped at most once across all operations. Over 10⁵ operations, total work is O(m log m) where m = operation count.
Compaction runs after Θ(n) stale entries accumulate, costs O(n), amortizes to O(1) per operation. Space is O(live files) amortized.
Edge Cases Handled
- Quota = 0: Evicts all files, usage becomes 0
- File larger than quota: Fails capacity check before any changes
- Delete nonexistent file: Returns
False, no error - Delete then re-upload same ID: Old heap entry fails size match, new entry is valid
- Quota increase: No evictions, returns empty list
- Size ties with multiple files: Lexicographic order determines eviction sequence
Implementation
import heapq
from typing import Dict, List, Tuple
class _User:
def __init__(self, capacity: int):
self.capacity = capacity
self.used = 0
self.files: Dict[str, int] = {}
self.heap: List[Tuple[int, str]] = []
def compact_if_needed(self):
if len(self.heap) > 2 * len(self.files) + 16:
self.heap = [(-size, fid) for fid, size in self.files.items()]
heapq.heapify(self.heap)
class FileManager:
def __init__(self):
self._users: Dict[str, _User] = {}
def _get_user(self, user_id: str) -> _User:
if user_id not in self._users:
raise KeyError(f"user not found: {user_id}")
return self._users[user_id]
def create_user(self, user_id: str, capacity: int) -> bool:
if capacity < 0:
raise ValueError("capacity cannot be negative")
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:
user = self._get_user(user_id)
if file_id in user.files or 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:
user = self._get_user(user_id)
size = user.files.pop(file_id, None)
if size is None:
return False
user.used -= size
user.compact_if_needed()
return True
def update_quota(self, user_id: str, new_capacity: int) -> List[str]:
user = self._get_user(user_id)
user.capacity = new_capacity
evicted = []
while user.used > user.capacity and user.heap:
neg_size, file_id = heapq.heappop(user.heap)
size = -neg_size
if user.files.get(file_id) == size:
del user.files[file_id]
user.used -= size
evicted.append(file_id)
user.compact_if_needed()
return evicted
This solution efficiently handles all operations within the constraints while maintaining correctness through careful invariant management and lazy heap maintenance.