Sub topic 14
Arrow Flight and ADBC: Moving Arrow Data Between Processes and Databases
This chapter assumes you have read the earlier chapters on schemas, record batches and the IPC stream format. You should also be comfortable running a small Python script that opens a local network port. Install the packages with pip install pyarrow adbc-driver-sqlite.
The IPC format gives Arrow data a byte layout. It does not say how to move those bytes between machines, how to authenticate, or how to ask a database for a result. Two projects fill those gaps:
- Arrow Flight is an RPC framework (a way to call functions on a remote server) for sending Arrow record batches over gRPC.
- ADBC (Arrow Database Connectivity) is a client API for running SQL against a database and receiving the results as Arrow data.
Flight is a wire protocol between a client and a server. ADBC is a driver API inside the client process. The two can work together. An ADBC driver for a Flight SQL server uses Flight to move the bytes.
The problem these tools solve
Consider a service that returns a large query result to a Python client. With a row-oriented protocol, the server turns its columnar data into rows. The client then parses the rows and rebuilds columns. Every value is converted twice, even if both sides use Arrow internally.
Flight and ADBC remove those conversions. The server sends record batches in the IPC layout. The client receives buffers that already have the Arrow layout, so it can use them directly. Nothing is parsed value by value.
How Flight works
A Flight service exposes a small set of operations. The main ones are:
| Operation | Purpose |
|---|---|
| `GetFlightInfo` | Describe a dataset: its schema and where to fetch it |
| `DoGet` | Stream record batches from the server to the client |
| `DoPut` | Stream record batches from the client to the server |
| `DoExchange` | Stream batches in both directions on one call |
| `DoAction` | Run a custom command, such as "clear cache" |
| `ListFlights` | List the datasets the server offers |
A dataset is identified by a descriptor, which is either a path (a list of names) or a command (opaque bytes the server understands). GetFlightInfo returns one or more endpoints. Each endpoint holds a ticket, an opaque token the client passes to DoGet, and optionally a list of server locations.
The two-step design lets a server split a large result into several endpoints. A client can then fetch the endpoints in parallel, possibly from different machines. Each stream is the IPC stream format you already know: a schema message followed by record batches.
A working Flight round trip
This script starts a server in a background thread, uploads a table with DoPut, and downloads it with DoGet. The server keeps tables in a dictionary keyed by the path in the descriptor.
import threading
import pyarrow as pa
import pyarrow.flight as flight
class DemoServer(flight.FlightServerBase):
def __init__(self, location):
super().__init__(location)
self._tables = {}
def do_put(self, context, descriptor, reader, writer):
# descriptor.path is a list of bytes
self._tables[descriptor.path[0]] = reader.read_all()
def do_get(self, context, ticket):
table = self._tables[ticket.ticket]
return flight.RecordBatchStream(table)
server = DemoServer("grpc://127.0.0.1:0") # port 0 picks a free port
thread = threading.Thread(target=server.serve, daemon=True)
thread.start()
client = flight.connect(f"grpc://127.0.0.1:{server.port}")
table = pa.table({"id": [1, 2, 3], "name": ["a", None, "c"]})
descriptor = flight.FlightDescriptor.for_path("events")
writer, _ = client.do_put(descriptor, table.schema)
writer.write_table(table)
writer.close()
result = client.do_get(flight.Ticket(b"events")).read_all()
print(result.equals(table))
client.close()
server.shutdown()The script prints True. The schema, including the null in name, survives the trip. The script uses the ticket b"events", which equals the path name, only because this toy server defines it that way. In a real server a ticket is whatever the server chooses. It might encode a query, a partition or a session.
Streaming and memory
RecordBatchStream sends one batch at a time, so a server can stream a result much larger than its memory. The client can also read batch by batch. Call reader.read_chunk() in a loop, or iterate over the reader, instead of read_all(). Use read_all() only when the whole result fits in memory.
Security
The example uses plain grpc:// on localhost. A real deployment should use grpc+tls:// and an authentication handler. Flight supports TLS, mutual TLS and custom middleware for headers or tokens. Never expose an unauthenticated Flight server on a shared network. do_get here would hand any table to anyone who can guess its name.
Flight SQL
Flight itself has no notion of SQL. Flight SQL is a protocol built on top of Flight that defines a standard set of commands for SQL databases. These include running a query, listing tables, reading metadata and using prepared statements. A database that implements Flight SQL can be queried by any Flight SQL client, with no custom client code. Results come back as Arrow batches.
ADBC: a database API that returns Arrow
JDBC and ODBC are standard database APIs, but both return data row by row. A client that wants columns must convert. ADBC keeps the idea of a standard driver API but makes Arrow the data format in both directions.
An ADBC driver is a shared library with a C API. Language bindings load it. In Python, each driver package includes a dbapi module that follows the familiar DB-API 2.0 shape (connect, cursor, execute) and adds Arrow methods. The same ADBC code can talk to different databases by swapping the driver. Drivers exist for SQLite, PostgreSQL, Snowflake, BigQuery, Flight SQL and others.
import pyarrow as pa
from adbc_driver_sqlite import dbapi
table = pa.table({"id": [1, 2, 3], "name": ["a", None, "c"]})
with dbapi.connect() as conn:
with conn.cursor() as cur:
cur.adbc_ingest("people", table, mode="create")
cur.execute("SELECT id, name FROM people WHERE id > 1")
result = cur.fetch_arrow_table()
conn.commit()
print(result.num_rows)
print(result.schema)The script prints 2 and then the schema. adbc_ingest bulk-loads an Arrow table into a new table, with no per-row INSERT loop. fetch_arrow_table returns the query result as a pyarrow.Table. If you only need pandas, fetch_df converts for you. Cursors also have fetch_record_batch for streaming large results.
Where the zero-copy benefit stops
How much ADBC saves depends on the driver. A driver for a database whose native format is columnar, or one that talks Flight SQL, can pass Arrow data through with little work. A driver for a row-based database, such as SQLite or PostgreSQL over its row protocol, must still read rows from the database and build Arrow arrays. ADBC does not remove that conversion. It moves it into the driver, which is usually written in C, C++, Go or Rust and is much faster than a Python loop. It also gives you one consistent Arrow interface across databases.
Choosing between Flight, ADBC and neighbors
| Situation | Reasonable choice |
|---|---|
| Two programs in one process, such as Python and a Rust extension | C data interface (previous chapter) |
| Two programs on one machine sharing a file | IPC file with a memory map |
| A service sends large tables to remote clients | Arrow Flight |
| An application runs SQL and wants Arrow results | ADBC |
| A database server should accept queries from many client types | Flight SQL, with ADBC or another client |
| Long-term storage of a table | Parquet |
Common errors and failure modes
- Treating a ticket as a stable ID. Tickets are opaque and a server may expire them. Fetch them from
GetFlightInfoeach time instead of storing them. - Calling
read_all()on huge results. This builds the whole table in client memory. Stream batches instead. - Forgetting to close the
DoPutwriter. The server'sdo_putreturns only after the stream ends. If you skipclose(), the upload may be incomplete or the call may hang. - Assuming one endpoint. A server may return several endpoints. Code that reads only the first one will silently lose data.
- Expecting ADBC to speed up every query. If the database spends its time executing the query, an Arrow result format does not help. The saving is in transfer and conversion.
- Schema mismatches in ingest. If the target table exists with different column types, ingest can fail or coerce. Check the mode (
create,append,replace,create_append) and the types before loading.
Exercise
A Flight client calls GetFlightInfo and receives three endpoints, each with its own ticket. What should it do to get the complete dataset, and why is this design useful?
Show answer
It must call DoGet once per endpoint, using each endpoint's ticket, and combine the results. It can run these calls in parallel and may need to connect to different locations. The design lets a server split a large result across several streams or machines, so throughput scales beyond one connection.
Exercise
Your application reads from a PostgreSQL database with an ADBC driver. A colleague says ADBC means no per-value conversion happens anywhere. Is that right?
Show answer
No. PostgreSQL sends rows over its own protocol, so the driver still reads each value and builds Arrow arrays. ADBC moves that work into compiled driver code and gives you Arrow output through a standard API. The saving is the extra conversion in Python or in a row-based client library, not all conversion.