Sub topic 9
Sending Arrow data: IPC streams and files
This chapter assumes you can build Arrow arrays, schemas and tables in pyarrow, and that you know what a record batch is. You should also be comfortable with the difference between data in memory and data in a file.
Why Arrow needs a wire format
An Arrow table lives in memory as a set of buffers. Those buffers contain pointers and offsets that only make sense inside one process. To send a table to another process, or to save it, you need a byte sequence that carries the same layout.
Arrow's IPC format (inter-process communication format) does this. It stores the buffers as they already exist in memory, with a small amount of metadata around them. A reader does not parse values one by one. It reads the metadata, finds where each buffer starts, and points Arrow arrays at those bytes.
This is why IPC is cheap compared with CSV or JSON. There is no text to format and no text to parse.
Two formats: stream and file
Arrow defines two framings of the same underlying messages.
| Property | IPC stream | IPC file (Feather V2) |
|---|---|---|
| Typical use | Sockets, pipes, HTTP bodies | Files on disk |
| Length known up front | No | Yes, a footer records it |
| Random access to a batch | No | Yes, through the footer |
| Can be memory-mapped | Only if stored in a file | Yes, designed for it |
| Can be written incrementally | Yes, and read while being written | Yes, but the footer is written at close |
The stream format is a sequence of messages. First comes the schema, then zero or more record batches, then an end-of-stream marker. A reader must read from the start and moves forward only.
The file format wraps the same messages. It adds a magic string at the start (ARROW1), and a footer at the end that holds the schema and the position of every record batch. The footer lets a reader jump to batch number 7 without reading batches 0 to 6.
Choose the stream when data flows and the total size is unknown. Choose the file when you want to store data and read parts of it later.
Writing and reading a stream
The first example writes a table to an in-memory buffer and reads it back. The buffer stands in for a socket or a pipe.
import pyarrow as pa
table = pa.table({"id": [1, 2, 3], "name": ["a", "b", "c"]})
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema) as writer:
writer.write_table(table)
buf = sink.getvalue()
reader = pa.ipc.open_stream(buf)
result = reader.read_all()
print(result.equals(table))Three things happen here:
new_streamwrites the schema first. The writer needs the schema before any data, because the reader needs it to interpret every batch that follows.write_tablesplits the table into record batches and writes each one. You can also callwrite_batchto send one batch at a time.- Leaving the
withblock writes the end-of-stream marker. If you skip this, a reader may wait for more data or report a truncated stream.
getvalue() returns a pyarrow Buffer. You can pass it to open_stream directly, or turn it into Python bytes with buf.to_pybytes() when a library needs plain bytes. The conversion copies the data.
Reading batch by batch
read_all() collects every batch into a table. When the stream is large or still arriving, iterate instead:
import pyarrow as pa
table = pa.table({"x": list(range(10))})
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema) as writer:
for batch in table.to_batches(max_chunksize=4):
writer.write_batch(batch)
reader = pa.ipc.open_stream(sink.getvalue())
print(reader.schema)
for batch in reader:
print(batch.num_rows)This prints the schema, then the batch sizes 4, 4 and 2. Only one batch needs to be in memory at a time, so a consumer can process a stream that is larger than its RAM. This is the main reason to prefer streams for pipelines.
Writing and reading a file
The file API mirrors the stream API. The main difference is that the reader can ask how many batches exist and fetch any one of them.
import pyarrow as pa
table = pa.table({"x": list(range(10))})
with pa.OSFile("batches.arrow", "wb") as sink:
with pa.ipc.new_file(sink, table.schema) as writer:
for batch in table.to_batches(max_chunksize=4):
writer.write_batch(batch)
with pa.OSFile("batches.arrow", "rb") as source:
reader = pa.ipc.open_file(source)
print(reader.num_record_batches)
print(reader.get_batch(2).num_rows)The output is 3, then 2. get_batch(2) reads only the third batch, using the offset stored in the footer.
The file writer must be closed for the file to be valid. The footer is written at close time, and a reader that opens a file without a footer fails. A crash in the middle of a write leaves a file that cannot be opened as an IPC file, although the batches already written are intact.
What is inside a message
Each message has a small header and a body. The header is metadata written with FlatBuffers, a serialization library. It states the message type, the length of the body, and for a record batch, the length and offset of each buffer. The body is the buffers laid out one after another.
Buffers are padded so each starts at an 8-byte boundary. Current writers align to 64 bytes by default in some configurations, which suits SIMD instructions (CPU instructions that process several values at once). A reader relies on this alignment to use the bytes in place.
Because the body holds the buffers unchanged, the cost of reading is mostly the cost of getting the bytes into memory. If the bytes are already there, as in a memory map, the cost is close to zero. The next chapter covers that case.
Schema, dictionaries and metadata
The stream carries the schema once, so a reader knows every column name and type before the first batch. Every batch must match it. write_batch raises an error if a batch has a different schema than the writer was created with.
import pyarrow as pa
schema = pa.schema([("id", pa.int64())])
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, schema) as writer:
bad = pa.record_batch([pa.array(["x"])], names=["id"])
try:
writer.write_batch(bad)
except pa.ArrowInvalid as err:
print("rejected:", type(err).__name__)Two details matter in practice.
- Dictionary-encoded columns. A dictionary column stores a list of distinct values and small integer codes that refer to it. In IPC, the dictionary is sent as its own message, and batches refer to it. A reader needs the dictionary before it can decode the codes.
- Custom metadata. A schema and each field can carry key-value metadata as bytes. pandas uses this to remember index information when you call
Table.from_pandas. Metadata travels with the schema, so it survives a round trip through IPC.
Compression
IPC can compress each buffer in a record batch. Supported codecs include lz4_frame and zstd. Compression is set through write options:
import pyarrow as pa
table = pa.table({"x": list(range(100000))})
options = pa.ipc.IpcWriteOptions(compression="zstd")
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, table.schema, options=options) as writer:
writer.write_table(table)
print(sink.getvalue().size < table.nbytes)
result = pa.ipc.open_stream(sink.getvalue()).read_all()
print(result.equals(table))Compression trades CPU time for smaller bytes. It also gives up the zero-copy benefit: a reader must decompress each buffer into new memory. For data that moves across a network, this is often a good trade. For local files that you plan to memory-map, leave compression off.
Common errors
- Reading a stream with
open_file, or the reverse. The two formats have different framings.open_fileon a stream fails because it looks for theARROW1magic string and a footer. Check which writer produced the bytes. - Forgetting to close the writer. Without the end marker or the footer, readers see truncated or invalid data. Use
withblocks. - Assuming a stream can be re-read. A reader over a socket or pipe consumes the bytes. To read twice, keep the buffer or use a file.
- Mixing schemas. Every batch must match the stream's schema, including nullability and field order.
- Expecting zero-copy from compressed data. Compressed buffers are always decoded into fresh memory.
Choosing between them
Use a stream when you send data to another process, when the total size is unknown, or when you want a consumer to start working before the producer finishes. Use a file when you want to keep data on disk, jump to a batch, or memory-map the result.
Neither format is a replacement for Parquet. IPC files are fast to read and write because they hold the in-memory layout, so they are usually larger than Parquet files. Parquet adds encoding and compression for storage. A later chapter compares them.
Exercise
You write a table with pa.ipc.new_file, and the process crashes before the with block ends. Some batches were already written. Why can a reader not open the file with open_file, and what would you change to lose less work next time?
Show answer
The file format stores the schema and the offsets of all batches in a footer, which is written only when the writer is closed. A crashed process leaves no footer, so open_file fails. To lose less work, use the stream format, which has no footer and can be read up to the last complete batch, or write to a temporary file and rename it after the writer closes.
Exercise
A consumer needs to process 50 GB of Arrow data on a machine with 16 GB of RAM, and the data arrives over a network connection. Which IPC format and which reading pattern would you use, and why?
Show answer
Use the IPC stream format and iterate over the reader batch by batch (for batch in reader) instead of calling read_all(). The stream does not need a known total size, and only one batch is held in memory at a time, so memory use is bounded by the batch size rather than the total data size.