KatInterview

File Storage Manager with Quota Enforcement

Data Structure DesignModel answer
MediumModel answerData Structure Designhash-mapheaplazy-deletion

Last 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_id already 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:

  1. Largest file first
  2. 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