File handling: Open 16GB file on 4GB RAM and perform search
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-01-04
Problem Statement
Design a scalable file processing system that can open and perform searches (pattern matching, keyword search, etc.) inside a very large file (16GB) on a machine with limited memory (4GB RAM). The system should handle out-of-core processing (i.e., the dataset is larger than available memory) efficiently.
Functional Requirements
1.File Access
•Open large files efficiently without loading them entirely into memory.
•Support sequential and random access.
2.Search Functionality
•Search for a specific keyword / pattern inside the file.
•Support multiple queries concurrently (multi-threaded search).
•Return all matching offsets/line numbers.
3.Data Processing
•Read the file in chunks/buffers.
•Support both line-based (e.g., log files) and binary search.
Non-Functional Requirements
•Memory Efficiency: Must not exceed 4GB RAM usage.
•Performance: Minimize disk I/O with smart buffering and indexing.
•Scalability: Should be extendable to even larger files (e.g., 100GB+).
•Reliability: Handle file corruption, partial reads, and concurrent queries.
•Extensibility: Support future enhancements like regex search, parallel file scan, or index building.
Design Considerations
•Chunk-based Processing
•Read file in chunks (e.g., 64MB blocks).
•Use sliding windows to handle cases where search pattern overlaps across chunk boundaries.
•Indexing (Optional)
•Build an on-disk index (e.g., inverted index or suffix array) to accelerate future searches.
•Trade-off: extra precomputation time vs faster queries.
•File Access Method
•Memory-mapped files (mmap) for efficient OS-level paging.
•Or Buffered streaming I/O (read block by block).
•Concurrency
•Parallelize search across different file segments (using threads).
•Synchronize results merging.
•Failure Handling
•Retry mechanism for failed I/O.
•Graceful handling if file grows during search (append-only logs).
APIs / Interfaces (Conceptual)
•openFile(filePath) → Open file and return a file handle.
•search(fileHandle, pattern) → Perform keyword/pattern search.
•searchAsync(fileHandle, pattern, callback) → Asynchronous search.
•buildIndex(fileHandle) → Build an on-disk search index for faster future queries