A customer asked me recently how to optimize performance writing to PostgreSQL from a Flink pipeline. Without hesitation, I recommended using PostgreSQL’s COPY interface. The result was approximately twice the throughput. This post explores what makes COPY different, and when you should consider using it.

To be fair, my recommendation hadn’t come out of nowhere. I had previously had experience building high performance PostgreSQL applications on large datasets using COPY and have significant experience in this corner of PostgreSQL usage.

Key Takeaways

  • Moving a customer’s Flink pipeline from INSERT to COPY roughly doubled its write throughput.
  • COPY sets up a single stream: the statement is parsed once, rows are sent one line at a time into one running insert, and round trips happen only when the stream starts and finishes.
  • The gain grows with network latency, so COPY suits large loads in a single run. For small record sets, or where simple code matters more, INSERT is still the better fit, and COPY has no equivalent of UPDATE.
  • COPY TO streams query results back one line at a time, with no limit on rows and no need to hold the whole result in client memory, but errors arrive inside the stream.
  • Reading or writing server-side files, and COPY FROM PROGRAM, need superuser access and are not offered on major managed services, so most applications should use STDIN and STDOUT.

COPY: A pre-SQL Legacy

In 1994, the Postgres project adopted the SQL query language with a full replacement released in 1995. The codebase was already a decade old at the time, and previously used a query language called PostQUEL (hence the client library being named libpq).

Like all query languages, PostQUEL had its own quirks and ways of working and its own annoyances and failure modes. As SQL emerged as the industry standard, PostQUEL support was dropped in favor of the former. Except for COPY, that is.

In PostQUEL, COPY is the statement for bulk loading and exporting data. Insert and update equivalents existed (append and replace). But COPY allowed flexible and powerful import and export of data as a stream, which is a concept foreign to SQL.

What Makes COPY FROM Different from INSERT

Example (via psql):

COPY sometable FROM STDIN WITH CSV HEADER; ID,METRIC,VALUE 1,test,123 2,test,222 3,foo,64 .

COPY operates on streams. It can COPY FROM a stream to a table or to a stream FROM a table or a query. Rather than a purely set-based operation where sets are handed back and forth as a set, here the set is handed back and forth as a stream. This distinction is critical in order to understand when to use COPY and when to stick with INSERT.

COPY can replace both INSERT and SELECT in certain circumstances, but the semantics and practicalities are different. COPY operates, however, more closely to how the PostgreSQL client-server protocol works, which is as a bidirectional stream of messages. For this reason, at the expense of some extra coding and data management on the client-side, you can get performance benefits of using COPY where latency or batch size is an issue.

Compared to a row-by-row insert approach the difference becomes clear. In a naive row-by-row approach, for each row we send an insert statement which specifies the table, columns, and values. This statement gets parsed, planned and executed on the server and the response sent to the client (this could include a result if the statement uses RETURNING).

We can make this approach faster through using server-side prepared statements which avoids reparsing the query (and will reduce replanning it after a few runs), and by adding more rows to the same insert statement still has to have some rudimentary parsing and we still have to wait for execution and return until we can send the next rows.

We could also make this faster by batching multiple rows into the same insert. This avoids some of the round trip overhead at the expense of increasing complexity in some areas of code and the inability to use prepared statements on the server side, meaning that every insert is replanned.

COPY avoids these two bottlenecks by setting up a stream by which rows can be streamed to the server for parsing (of the values only) and immediate inserting in an ongoing executor action. In other words, the insert is parsed once, and we just start sending rows, one line at a time. Errors, if they happen, are streamed back and the whole COPY run succeeds or fails atomically.

Compared to batched inserts there is no replanning and the parsing is far faster, and you have even less overhead for round trips since the only round trips you typically have happen initiating and finalizing the stream.

Diagram: row-by-row INSERT adds a network round trip, parsing and planning for every row, while PostgreSQL COPY parses once and streams the rows, finishing in about half the time
Diagram: row-by-row INSERT adds a network round trip, parsing and planning for every row, while PostgreSQL COPY parses once and streams the rows, finishing in about half the time

This requires extra coding for error and row handling, but almost all PostgreSQL drivers handle it (ODBC drivers being a notable exception).

When to Use COPY FROM

COPY FROM improves performance in critical areas but it has a downside of requiring additional code management. The default JDBC implementation assumes writing rows in CSV which requires extra code to manage, and error handling can be more difficult. If further optimization is desired (for example, using native binary formats), the amount of code required can be significantly increased (though this can also improve server performance).

For this reason, COPY FROM is useful where large amounts of data are being loaded into PostgreSQL in a single run, particularly where latency is a concern. This gain increases with the latency of the database connection, so COPY FROM will be significantly faster within the local datacenter, and will not degrade in performance when writing intercontinentally the way INSERT will due to network roundtrip proliferation.

Where these considerations dominate, COPY FROM should be used. Where simplicity of code is a larger concern or the record set is small, then INSERT should be used as well. There is no immediate equivalent to UPDATE in the COPY world.

Benchmarking your ingestion path?

Our whitepaper compares data insertion performance in PostgreSQL and MongoDB, with guidance on which workloads suit each.

Read the ingestion benchmark →

How COPY TO Differs from SELECT

Example (from psql)

COPY customers TO stdout WITH CSV HEADER;

COPY TO is the reverse of COPY FROM and streams records back to the client which are then read as a stream by the client. This has important uses as well, particularly where large result sets must be processed.

COPY TO supports multiple different formats, namely a default text format, CSV, and a binary format which is best suited for applications very tightly coupled with the database. This means you can use PostgreSQL to assemble a CSV of results for you and often get some useful performance benefits along the way.

The second major difference is in client library expectations. While PostgreSQL streams results back anyway for performance reasons, with COPY, the client expects to hand the stream to the program to process while with SELECT it will assemble some sort of result set instead.

Let’s compare the standard SELECT case to COPY TO. In a SELECT, I send the statement to the database server, which parses, plans, and executes the statement, and streams the rows back in an internal format based on the client/server format. The client library will then assemble all rows returned into a result set that is handed to the application once all rows are received. The standard client library of libpq will throw an error if more than INT_MAX (a little over 2 billion) rows are sent into the result set.

In contrast, with COPY TO, the server parses, plans, and executes the statement, and streams the rows back in a format specified by the user (in the example above, CSV with the column names in the first line). The client library will then expose the stream to the application which can then read the result out one line at a time as they arrive.

When to Use COPY TO

Unlike SELECT, where the client library will throw an error before handing results back, COPY TO will inline the error in the result stream. This means you have to be prepared to handle the error during the processing of results rather than letting the client library do this for you.

On the other hand, there is no limit to the number of rows COPY TO can handle, and the fact that these can be processed as they arrive means that applications can stream results out onto the next stage without storing them in the client application’s memory.

As a result, COPY TO really shines when you want to take a query result and treat it as a stream, although there can be extra complexity required to handle errors.

A Brief Note about Files, Programs, and COPY

COPY can also copy to or from files, not merely the standard input or output descriptors. This requires superuser access because it requires reading or writing files through the Postgres process on the server.

One can ship files to a database server (or a network mount accessible by the PostgreSQL process) and create user defined functions capable of reading and writing these files. These can then be written in a way which is safe to operate for normal users, and they can then be run as superuser (by setting the function SECURITY DEFINER and having the function owned by a database superuser).

This approach is disfavored over using STDIN and STDOUT for a number of reasons including the capacity for security problems and for things to go dramatically wrong. It also increases complexity of code.

Additionally, COPY can also do COPY FROM PROGRAM which can run arbitrary binaries on the PostgreSQL system as the postgres operating system user. This also requires superuser access.

A critical mantra on this topic: On Postgres, superuser access is system access, and system access to the postgres account is superuser access. These are closely tied and this is one reason why these server-side copy options are not available on managed service offerings by any major cloud provider. This illustrates why most applications should use the standard input and output options rather than server-side resources for COPY.

Conclusions

COPY is a tool which can dramatically improve database performance in the right applications. It does not replace SELECT and INSERT but is an important alternative in certain high performance applications, and in the right place and time it can let PostgreSQL do things which would be far more complex to do otherwise.

As I often say: at scale, it is important to choose your problems carefully, and this is no exception.

Frequently Asked Questions

What is the PostgreSQL COPY command?

COPY is a statement for bulk loading and exporting data that works on streams. In the examples in this post, COPY ... FROM STDIN loads rows into a table and COPY ... TO STDOUT streams rows back to the client. COPY TO supports a default text format, CSV and a binary format. COPY dates back to PostQUEL, the query language Postgres used before it adopted SQL.

Why is COPY faster than INSERT?

With row-by-row INSERT, every statement is parsed, planned and executed, and the client waits for the response before sending the next rows. COPY parses the statement once and streams rows into a single running insert, so there is no replanning and round trips happen only when the stream starts and finishes. In a customer’s Flink pipeline, moving to COPY roughly doubled write throughput.

When should I use INSERT instead of COPY?

Use INSERT when the record set is small or when simplicity of code is the larger concern. COPY needs extra client code for row and error handling, and there is no COPY equivalent of UPDATE.

How is streaming results with COPY different from SELECT?

With SELECT, the client library collects every row into a result set and hands it to the application only once all rows have arrived, and libpq throws an error if more than INT_MAX (a little over 2 billion) rows are sent into the result set. With COPY TO, the application reads rows one line at a time as they arrive, with no limit on the number of rows and no need to store them in the application’s memory, but errors arrive inside the stream and the application has to handle them itself.

Do PostgreSQL drivers support COPY?

Almost all PostgreSQL drivers support it, with ODBC drivers a notable exception. The default JDBC implementation assumes rows are written in CSV, which requires extra code to manage.

Which COPY options need superuser access?

Copying to or from files on the database server, and COPY FROM PROGRAM, need superuser access, and these server-side options are not available on managed services from any major cloud provider. Most applications should use COPY with STDIN and STDOUT instead.

Writes or exports slowing your pipeline down?

Our Forward Deployed Engineers find where your PostgreSQL workload is losing time, from query patterns to configuration, and show you what to change first.

See PostgreSQL performance optimization →

The post PostgreSQL’s Best Kept Secret: COPY appeared first on Stormatics.