Streaming, Serialization, and IPC

Writing and Reading Streams

Arrow defines two types of binary formats for serializing record batches:

  • Streaming format: for sending an arbitrary length sequence of record batches. The format must be processed from start to end, and does not support random access
  • File or Random Access format: for serializing a fixed number of record batches. Supports random access, and thus is very useful when used with memory maps

To follow this section, make sure to first read the section on Memory and IO.

Using streams

First, let’s create a small record batch:

In [1]: import pyarrow as pa

In [2]: data = [
   ...:     pa.array([1, 2, 3, 4]),
   ...:     pa.array(['foo', 'bar', 'baz', None]),
   ...:     pa.array([True, None, False, True])
   ...: ]

In [3]: batch = pa.RecordBatch.from_arrays(data, ['f0', 'f1', 'f2'])

In [4]: batch.num_rows
Out[4]: 4

In [5]: batch.num_columns
Out[5]: 3

Now, we can begin writing a stream containing some number of these batches. For this we use RecordBatchStreamWriter, which can write to a writeable NativeFile object or a writeable Python object:

In [6]: sink = pa.BufferOutputStream()

In [7]: writer = pa.RecordBatchStreamWriter(sink, batch.schema)

Here we used an in-memory Arrow buffer stream, but this could have been a socket or some other IO sink.

When creating the StreamWriter, we pass the schema, since the schema (column names and types) must be the same for all of the batches sent in this particular stream. Now we can do:

In [8]: for i in range(5):
   ...:    writer.write_batch(batch)

In [9]: writer.close()

In [10]: buf = sink.getvalue()

In [11]: buf.size
Out[11]: 1980

Now buf contains the complete stream as an in-memory byte buffer. We can read such a stream with RecordBatchStreamReader or the convenience function pyarrow.ipc.open_stream:

In [12]: reader = pa.ipc.open_stream(buf)

In [13]: reader.schema
f0: int64
f1: string
f2: bool

In [14]: batches = [b for b in reader]

In [15]: len(batches)
Out[15]: 5

We can check the returned batches are the same as the original input:

In [16]: batches[0].equals(batch)
Out[16]: True

An important point is that if the input source supports zero-copy reads (e.g. like a memory map, or pyarrow.BufferReader), then the returned batches are also zero-copy and do not allocate any new memory on read.

Writing and Reading Random Access Files

The RecordBatchFileWriter has the same API as RecordBatchStreamWriter:

In [17]: sink = pa.BufferOutputStream()

In [18]: writer = pa.RecordBatchFileWriter(sink, batch.schema)

In [19]: for i in range(10):
   ....:    writer.write_batch(batch)

In [20]: writer.close()

In [21]: buf = sink.getvalue()

In [22]: buf.size
Out[22]: 4226

The difference between RecordBatchFileReader and RecordBatchStreamReader is that the input source must have a seek method for random access. The stream reader only requires read operations. We can also use the pyarrow.ipc.open_file method to open a file:

In [23]: reader = pa.ipc.open_file(buf)

Because we have access to the entire payload, we know the number of record batches in the file, and can read any at random:

In [24]: reader.num_record_batches
Out[24]: 10

In [25]: b = reader.get_batch(3)

In [26]: b.equals(batch)
Out[26]: True

Reading from Stream and File Format for pandas

The stream and file reader classes have a special read_pandas method to simplify reading multiple record batches and converting them to a single DataFrame output:

In [27]: df = pa.ipc.open_file(buf).read_pandas()

In [28]: df[:5]
   f0    f1     f2
0   1   foo   True
1   2   bar   None
2   3   baz  False
3   4  None   True
4   1   foo   True

Arbitrary Object Serialization

In pyarrow we are able to serialize and deserialize many kinds of Python objects. While not a complete replacement for the pickle module, these functions can be significantly faster, particular when dealing with collections of NumPy arrays.

As an example, consider a dictionary containing NumPy arrays:

In [29]: import numpy as np

In [30]: data = {
   ....:     i: np.random.randn(500, 500)
   ....:     for i in range(100)
   ....: }

We use the pyarrow.serialize function to convert this data to a byte buffer:

In [31]: buf = pa.serialize(data).to_buffer()

In [32]: type(buf)
Out[32]: pyarrow.lib.Buffer

In [33]: buf.size
Out[33]: 200028864

pyarrow.serialize creates an intermediate object which can be converted to a buffer (the to_buffer method) or written directly to an output stream.

pyarrow.deserialize converts a buffer-like object back to the original Python object:

In [34]: restored_data = pa.deserialize(buf)

In [35]: restored_data[0]
array([[ 0.30366949, -0.64627863,  1.22621577, ...,  0.07490635,
         0.24000932,  0.30399034],
       [-0.48920109,  1.24802674, -0.80832769, ...,  1.69083111,
         0.66914517,  0.07339462],
       [ 0.8988314 , -1.149941  ,  0.66666449, ..., -0.19295668,
         0.20513893,  1.06489177],
       [ 1.30046705,  0.1959505 ,  0.38984922, ...,  0.27002095,
        -0.28177866, -0.30867695],
       [-0.27108035, -1.52272187, -0.69425813, ...,  0.58968553,
        -2.39722588, -1.85534604],
       [ 0.80786145, -1.63944626, -1.64655649, ..., -0.98664626,
        -1.03516346,  0.21891727]])

When dealing with NumPy arrays, pyarrow.deserialize can be significantly faster than pickle because the resulting arrays are zero-copy references into the input buffer. The larger the arrays, the larger the performance savings.

Consider this example, we have for pyarrow.deserialize

In [36]: %timeit restored_data = pa.deserialize(buf)
1.48 ms +- 11.2 us per loop (mean +- std. dev. of 7 runs, 1000 loops each)

And for pickle:

In [37]: import pickle

In [38]: pickled = pickle.dumps(data)

In [39]: %timeit unpickled_data = pickle.loads(pickled)
50.8 ms +- 710 us per loop (mean +- std. dev. of 7 runs, 10 loops each)

We aspire to make these functions a high-speed alternative to pickle for transient serialization in Python big data applications.

Serializing Custom Data Types

If an unrecognized data type is encountered when serializing an object, pyarrow will fall back on using pickle for converting that type to a byte string. There may be a more efficient way, though.

Consider a class with two members, one of which is a NumPy array:

class MyData:
    def __init__(self, name, data): = name = data

We write functions to convert this to and from a dictionary with simpler types:

def _serialize_MyData(val):
    return {'name':, 'data':}

def _deserialize_MyData(data):
    return MyData(data['name'], data['data']

then, we must register these functions in a SerializationContext so that MyData can be recognized:

context = pa.SerializationContext()
context.register_type(MyData, 'MyData',

Lastly, we use this context as an additional argument to pyarrow.serialize:

buf = pa.serialize(val, context=context).to_buffer()
restored_val = pa.deserialize(buf, context=context)

The SerializationContext also has convenience methods serialize and deserialize, so these are equivalent statements:

buf = context.serialize(val).to_buffer()
restored_val = context.deserialize(buf)

Component-based Serialization

For serializing Python objects containing some number of NumPy arrays, Arrow buffers, or other data types, it may be desirable to transport their serialized representation without having to produce an intermediate copy using the to_buffer method. To motivate this, suppose we have a list of NumPy arrays:

In [40]: import numpy as np

In [41]: data = [np.random.randn(10, 10) for i in range(5)]

The call pa.serialize(data) does not copy the memory inside each of these NumPy arrays. This serialized representation can be then decomposed into a dictionary containing a sequence of pyarrow.Buffer objects containing metadata for each array and references to the memory inside the arrays. To do this, use the to_components method:

In [42]: serialized = pa.serialize(data)

In [43]: components = serialized.to_components()

The particular details of the output of to_components are not too important. The objects in the 'data' field are pyarrow.Buffer objects, which are zero-copy convertible to Python memoryview objects:

In [44]: memoryview(components['data'][0])
Out[44]: <memory at 0x2b9df2fced08>

A memoryview can be converted back to a Arrow Buffer with pyarrow.py_buffer:

In [45]: mv = memoryview(components['data'][0])

In [46]: buf = pa.py_buffer(mv)

An object can be reconstructed from its component-based representation using deserialize_components:

In [47]: restored_data = pa.deserialize_components(components)

In [48]: restored_data[0]
array([[-2.09789200e+00,  5.94339216e-01, -1.89475781e+00,
        -4.81971478e-01,  1.85361416e+00, -2.48043593e-01,
        -1.91022233e+00, -1.66680320e+00, -4.75172451e-01,
       [-4.34682250e-01,  4.92539674e-01, -3.03225585e-01,
         1.84949659e+00,  1.62949238e-01, -8.95536165e-01,
        -9.29900484e-02,  5.27484346e-01,  5.28215610e-02,
       [-9.40946713e-01, -6.02886217e-01, -8.72659161e-01,
         3.37241067e-01, -5.94084005e-01,  2.19576060e+00,
        -1.05733812e+00, -4.63555432e-01, -9.01911561e-01,
       [-1.09276186e+00, -3.01247838e-02,  1.30598257e+00,
         4.59392202e-01, -1.24863774e-01, -3.25880793e-01,
        -1.24870321e+00, -5.44737151e-01,  1.65106158e+00,
       [-1.50913019e+00,  4.26931594e-01,  8.65833501e-01,
        -7.27921563e-04,  8.81459680e-01, -1.10860082e+00,
         5.80277141e-01, -9.21908302e-01,  6.70112826e-01,
       [-9.93172401e-01,  1.17603956e+00,  2.78081026e-01,
        -5.93112374e-01,  1.07705486e+00,  1.72702081e-01,
        -3.78778646e-01, -8.03233351e-01, -1.24080896e+00,
       [ 1.15386891e+00,  1.78261183e-01,  1.78437672e+00,
         1.01860076e+00,  1.76424671e-01, -3.90386409e-01,
        -1.38297002e+00, -1.00368995e+00,  4.52121590e-01,
       [ 3.27654048e-01, -1.66681593e+00, -2.00937784e+00,
         5.35632835e-01,  1.82911440e-02,  1.46348812e+00,
        -5.71156731e-01, -7.94390580e-01, -7.42427754e-01,
       [-1.21857947e+00, -1.30020949e+00, -8.11947150e-01,
         9.86437650e-01,  1.16603312e+00,  4.24350389e-01,
        -5.77830018e-01,  1.00906832e+00, -3.34733893e-02,
       [ 5.83778158e-01, -8.48277161e-01, -1.28742560e+00,
        -1.32358493e+00, -6.25451228e-01,  1.56801147e+00,
         7.47072897e-01,  5.39554970e-01,  4.05169854e-01,

deserialize_components is also available as a method on SerializationContext objects.

Serializing pandas Objects

The default serialization context has optimized handling of pandas objects like DataFrame and Series. Combined with component-based serialization above, this enables zero-copy transport of pandas DataFrame objects not containing any Python objects:

In [49]: import pandas as pd

In [50]: df = pd.DataFrame({'a': [1, 2, 3, 4, 5]})

In [51]: context = pa.default_serialization_context()

In [52]: serialized_df = context.serialize(df)

In [53]: df_components = serialized_df.to_components()

In [54]: original_df = context.deserialize_components(df_components)

In [55]: original_df
0  1
1  2
2  3
3  4
4  5

Feather Format

Feather is a lightweight file-format for data frames that uses the Arrow memory layout for data representation on disk. It was created early in the Arrow project as a proof of concept for fast, language-agnostic data frame storage for Python (pandas) and R.

Compared with Arrow streams and files, Feather has some limitations:

  • Only non-nested data types and categorical (dictionary-encoded) types are supported
  • Supports only a single batch of rows, where general Arrow streams support an arbitrary number
  • Supports limited scalar value types, adequate only for representing typical data found in R and pandas

We would like to continue to innovate in the Feather format, but we must wait for an R implementation for Arrow to mature.

The pyarrow.feather module contains the read and write functions for the format. The input and output are pandas.DataFrame objects:

import pyarrow.feather as feather

feather.write_feather(df, '/path/to/file')
read_df = feather.read_feather('/path/to/file')

read_feather supports multithreaded reads, and may yield faster performance on some files:

read_df = feather.read_feather('/path/to/file', nthreads=4)

These functions can read and write with file-like objects. For example:

with open('/path/to/file', 'wb') as f:
    feather.write_feather(df, f)

with open('/path/to/file', 'rb') as f:
    read_df = feather.read_feather(f)

A file input to read_feather must support seeking.