Sub topic 10
Memory-mapped reads of Arrow files
This chapter assumes you have read the earlier chapters on buffers, record batches and tables, and on the IPC stream and file formats. You should also know what a page cache is in rough terms: the operating system keeps recently used file pages in RAM.
What a memory map does
Normally, reading a file means asking the operating system to copy bytes from disk, or from its page cache, into memory your process owns. A memory map (mmap) skips that copy. The operating system maps the file's bytes into your process's address space, and your code reads them as if they were an ordinary array in memory. Pages are loaded from disk only when your code touches them.
Arrow's IPC file format is built for this. The file stores each buffer (validity bitmap, offsets, values) as raw bytes in the same layout Arrow uses in memory. When pyarrow reads a mapped file, it does not parse or rebuild those buffers. It creates Buffer objects whose pointers refer directly into the mapped region. The resulting table is a set of views over the file.
Writing the file and reading it both ways
The next example writes a file with one 5-million-row int64 column, then reads it twice. It uses pa.total_allocated_bytes(), which reports bytes held by Arrow's default memory pool. Memory that comes from a memory map is not allocated from that pool, so the counter shows whether a copy happened.
import numpy as np
import pyarrow as pa
path = "big.arrow"
table = pa.table({"x": np.arange(5_000_000, dtype=np.int64)})
with pa.OSFile(path, "wb") as sink:
with pa.ipc.new_file(sink, table.schema) as writer:
writer.write_table(table)
del table
# Ordinary read: bytes are copied into pool-allocated buffers.
before = pa.total_allocated_bytes()
with pa.OSFile(path, "rb") as source:
copied = pa.ipc.open_file(source).read_all()
print("OSFile read:", pa.total_allocated_bytes() - before)
del copied
# Memory-mapped read: buffers point into the mapping.
before = pa.total_allocated_bytes()
with pa.memory_map(path, "r") as source:
mapped = pa.ipc.open_file(source).read_all()
print("memory map:", pa.total_allocated_bytes() - before)
print(mapped.num_rows)The first number is about 40 million bytes, which is 5 million values times 8 bytes. The second is near zero, apart from a few small allocations for metadata. In both cases read_all() returns in the same form, a pa.Table. The difference is who owns the bytes behind it.
Reading less than the whole file
Mapping a file does not load it. The operating system loads a page the first time your code reads it, an event called a page fault. Two things follow.
- Opening a multi-gigabyte file is fast, because almost nothing is read yet.
- You pay for what you touch. Aggregating one column faults in only that column's pages, and the other columns stay on disk.
The file format also supports random access by record batch. The footer lists the position of every batch, so you can fetch one batch without scanning the batches before it.
import pyarrow as pa
import pyarrow.compute as pc
with pa.memory_map("big.arrow", "r") as source:
reader = pa.ipc.open_file(source)
print("batches:", reader.num_record_batches)
batch = reader.get_batch(0)
print(pc.sum(batch.column(0)))This is the main reason to write many moderate-size batches instead of one huge one. Each batch becomes a unit you can fetch independently.
What stays zero-copy afterwards
A mapped table behaves like any other Arrow table. Compute functions, slicing, and passing it through the C data interface all work, and they continue to share the mapped buffers. Slicing is only a change of offset and length. Compute functions read the mapped pages and write their results into new buffers, so results are ordinary allocated memory.
Conversion to NumPy follows the rules from the zero-copy chapter. A single chunk of a primitive column without nulls can become a NumPy array that shares the mapped bytes:
import pyarrow as pa
with pa.memory_map("big.arrow", "r") as source:
table = pa.ipc.open_file(source).read_all()
chunk = table.column("x").chunk(0)
values = chunk.to_numpy(zero_copy_only=True)
print(values[:3])
print(values.flags.writeable)The last line prints False. The mapping is opened read-only, so the NumPy view cannot be written to. If you need a mutable array, call values.copy(). Converting with to_pandas() often copies anyway, for example for strings, so a mapped table does not guarantee a copy-free pandas DataFrame.
When the read is not zero-copy
The map only avoids copies if the bytes in the file are already the bytes Arrow needs in memory. Several situations break that.
Compressed files
IPC files can compress each buffer, using LZ4 or Zstandard. The bytes on disk are then not a valid Arrow buffer, so the reader must decompress them into newly allocated memory. The file can still be mapped, but every touched buffer is copied during decompression.
import numpy as np
import pyarrow as pa
table = pa.table({"x": np.arange(5_000_000, dtype=np.int64)})
options = pa.ipc.IpcWriteOptions(compression="lz4_frame")
with pa.OSFile("compressed.arrow", "wb") as sink:
with pa.ipc.new_file(sink, table.schema, options=options) as writer:
writer.write_table(table)
before = pa.total_allocated_bytes()
with pa.memory_map("compressed.arrow", "r") as source:
result = pa.ipc.open_file(source).read_all()
print(pa.total_allocated_bytes() - before)This prints roughly 40 million again, even though a memory map was used. Compression trades disk space and transfer size for the loss of zero-copy reads. Choose it for files you send over a network, and leave it off for files you plan to map.
Other cases
- Stream format. You can map a file written in the IPC stream format and read it with
pa.ipc.open_stream, and the batches are still zero-copy. But a stream has no footer, so you can only read batches in order, and you cannot jump to batch 500. - Conversion to non-Arrow structures.
to_pandas()on strings, nulls in integer columns, or timestamps may build new Python or NumPy objects. - Filesystems that do not support mmap well. Network filesystems and some container volumes can behave poorly or fail. Test on the real storage.
- Parquet. A Parquet file is encoded and compressed, so it cannot be mapped into Arrow buffers. Reading it always decodes into new memory.
Operational pitfalls
The mapping shares memory with the file, so changes to the file affect your process.
- Do not modify or truncate a file while it is mapped. If another process shortens the file, touching a now-missing page can crash your process with a bus error (
SIGBUSon Linux and macOS). If another process rewrites bytes in place, your table can change underneath you. Write a new file and rename it into place instead. - Memory accounting looks different. Mapped pages count toward the process's resident size (RSS) as shared file-backed memory, but the operating system can drop them under memory pressure and reload them later. Tools that watch RSS may report high usage that is not actually a leak.
- First access can be slow. With a cold page cache, the first scan pays disk latency through page faults. A second scan is fast because the pages are cached. Benchmark both cases.
- Lifetime of the mapping. Buffers hold a reference to the mapped region, so the table normally stays valid after the
withblock closes the file handle. To avoid doubt, finish your work on the table inside the block, or keep the file object open for as long as you use the table. - Sharing between processes. Several processes can map the same file and share one copy of its pages in the page cache. This is the main reason to use mmap for worker pools that all read the same dataset.
When to use it
Use memory-mapped Arrow files when several of these hold:
- The same data is read many times, or by many processes.
- Each reader needs only some columns or some batches.
- The file is on local disk and is written once, then treated as read-only.
- The file is uncompressed.
Skip it when the file is read once from start to finish, since a plain read costs about the same. Skip it also when the data lives on remote storage, or when you need compression to save space. For those cases, Parquet and the dataset scanner in later chapters are the better fit.
Exercise
You write an Arrow IPC file with compression="zstd", open it with pa.memory_map and pa.ipc.open_file, and call read_all(). pa.total_allocated_bytes() rises by roughly the uncompressed size of the data. Why, and what would you change if the goal were a zero-copy read?
Show answer
Compressed buffers on disk are not valid Arrow buffers, so the reader decompresses each one into newly allocated memory from the memory pool. The memory map is used, but it only supplies the compressed input. To get a zero-copy read, write the file without compression (the default for IpcWriteOptions), then map it again. The file will be larger, and you can compress separately for transfer.
Exercise
A worker pool of eight processes each needs to scan the price column of the same 20 GB uncompressed Arrow file on local disk. Describe what happens to memory use if each worker maps the file instead of reading it with pa.OSFile, and name one rule the pipeline must follow.
Show answer
With pa.OSFile, each worker copies what it reads into its own memory, so memory use can grow toward eight copies of the data it touches. With memory maps, all workers share the same file-backed pages in the page cache, and each loads only the pages of the price column it touches, so total physical memory stays near one copy of that column. The pipeline must not modify, truncate or overwrite the file while the workers have it mapped. New data should be written to a new file that is renamed into place.