Airflow ETL for moving data from Postgres to Postgres 29 Jul 2018
This is the third post from the Airflow series. Here we’re covering a very common scenario: moving data from a table (or database) to another. In this case we are working with two PostgreSQL databases, and we need an incremental update approach. Let’s see how to do that using Python and Airflow.
A quick way would be to use the psycopg library to grab the data from the source using a regular client side cursor and then
insert it into the destination table. We can define both connections in Airflow by using the
PostgresHook class. This hook only needs the
connection_id parameter which you can get by creating a connection using the Airflow UI in the connections menu.
As you can see, we start the connections, get a cursor for the source table to get the data, and then insert it into the destination table. Pretty simple.
This would work fine for a small or medium amount of data. But it wouldn’t be performant if the size of the table is larger. The Airflow worker would have to load all the data retrieved from the query into memory before inserting it into the destination table, making it difficult if you are copying GB’s or even TB’s of data. For this case, we would do better using a server side cursor instead. This type of cursor doesn’t fetch all the rows at once, but instead it uses batches. This way you can control the amount of data that’s transfered to the client.
For example, let’s say you want to grab all the users created on a certain day and copy them to another table on a daily basis. You could use this simple PythonOperator:
As you can see, we are grabbing the users that were created on the execution date. This gives us more control when running backfills since we could parallelize the execution for each different day we need to copy. Also, notice that since we’re using a server side cursor, we have to iterate until the cursor is empty. I’m using a batch size of 2000 as an example.
Finally, psycopg2 provides a nice method called
execute_values that allows us to insert the whole batch at once.
Keep in mind that if you have several Dags and tasks using the same code, it’s more convenient to encapsulate the logic and write a custom Operator. On the other hand, the transformations in between the extract and load stages could vary a lot, so it can become a bit tricky to reuse the code. It’s up to you to decide.
If you are building an ETL that uses a different database engine, you should check if it has a similar feature, in which you can push the work onto the database server instead your worker machines. A good rule of thumb is that the Airflow workers should never be in charge of doing heavy work.
Thanks for reading!