Building a Python Data Pipeline: Lessons from a Code Review

A reviewed intern pipeline shows how retry logic, error handling and database writes go wrong, and why the loop style was never the real performance problem.

Binary Buddies · 5 min read · 10 views

An intern was given a homework-style task: pull hourly weather data from an API for a list of sites, insert it into a database, handle every possible error, and never crash. The result was a Python script built on pandas and the Open-Meteo client. Its single parser() function holds a retry loop with a separate branch for each error condition. The author posted it for review on Code Review Stack Exchange.

Two things in the post matter beyond this one script. The senior engineer said to use .apply() instead of a for loop because it is 'faster 9 x times', and the author was considering .itertuples() as an alternative. And 'handle all errors' had become roughly a dozen near-identical elif blocks matching on the text of the exception.

The reviews are short, but they point at the real problems. This article works through them, since the same mistakes show up in most first pipelines that talk to a rate-limited API and write to a database.

The apply() versus loop question is the wrong question

The script calls the API once per row of a sites DataFrame, and each call goes over the network. One reviewer made the obvious point: the bottleneck is network I/O, not Python's loop overhead, so swapping a loop for apply() will not make the pipeline 9x faster. DataFrame.apply(axis=1) is itself a Python-level loop over rows. Whatever speedup the senior had measured probably came from a different workload, such as arithmetic on columns.

The same applies to .itertuples(). It is a fine way to iterate, and usually quicker than iterrows(), but it still makes one API request per site, one after another. If the pipeline is slow, measure where the time goes before choosing a loop style. A thirty-second timer around openmeteo.weather_api() will tell you more than any micro-benchmark of the iteration.

Matching on str(e) is fragile

The retry logic catches Exception, converts it to a string, and checks whether it contains '429', '500', '502' and so on. This breaks in ways that are hard to see. Any error message that happens to contain those digits gets classified as an HTTP status. A reworded message from the library's next release turns a retryable error into the 'Unknown API error' branch, and that branch gives up on the site.

The review advice is to use a specific exception type or a status code if the client exposes one. If it does not, catch the narrowest exception you can and read the status from the response object rather than from prose. The Open-Meteo-specific strings, such as 'Hourly API request limit exceeded', are the same kind of coupling to message text. Keep them in one place, as named constants, so a wording change is a one-line fix.

One retry policy instead of nine copies

The retry branches differ in only two ways: how long to wait, and whether to retry at all. Everything else is copy-pasted, and the copies have drifted. In the 502 branch, the 'maximum attempts' path prints the 'Waiting 1 minute...' message instead of the maximum-attempts message. The code returns None correctly, but the log is wrong. In a pipeline that is meant to run unattended, the log is the only evidence you will have.

Reduce the policy to data plus one function:

RETRY_DELAYS = {429: 3600, 500: 60, 502: 60, 503: 60, 504: 60}
NO_RETRY = {400, 404}
MAX_ATTEMPTS = 5

def next_action(status, attempt):
    if status in NO_RETRY:
        return None
    if status in RETRY_DELAYS and attempt < MAX_ATTEMPTS:
        return RETRY_DELAYS[status]
    return None

The function returns a delay or None, the loop does the sleeping, and the log message is written once. Adding a status code becomes a dictionary entry rather than a new twelve-line block.

Sleeping for an hour inside the loop

Look at the worst case. For an hourly-limit error, attempts increments and the function returns None on the fifth, so it sleeps four times at 3600 seconds. One unlucky site can block the process for four hours. The counter is also shared across error types within a call, so a mix of 429s and 503s burns the same budget.

The review suggests retry and backoff scheduling instead of a process that sleeps. In practice that means one of two things. Either record the failed site in a tracking table with a next-attempt time and let a scheduler such as cron or an orchestrator pick it up, or use a short exponential delay with a cap for transient 5xx errors. The script already has a tracking table and a failed-sites retry pass, so the structure is there. The long sleep inside parser() works against it.

Keep fetch, transform and load apart

The parser both calls the API and builds the DataFrame. That makes it hard to test any part without hitting the network. Split it into a function that returns the raw response, a function that turns a response into a DataFrame, and the database call. The transform can then be tested with a saved response.

The transform step also shows a naming problem. The request asks for temperature_2m, relative_humidity_2m and shortwave_radiation, and the code comment says the order of variables must match the request. But the third variable is read into hourly_global_tilted_irradiance_instant. That name looks like it came from a different request, probably a copied example. The code works because it reads Variables(2) by position, but anyone loading that column later will assume it holds a different quantity. Positional indexing makes this easy to get wrong silently, so build the column list from the same list you send in params.

Loading into PostgreSQL without duplicating rows

The database module is not shown in the question, so what follows is a suggestion rather than a review of it. The request window runs from seven days ago to tomorrow, and that window is recomputed on every run. Each run therefore re-fetches mostly the same hours. If the weather table has no uniqueness constraint, every run inserts duplicates.

In PostgreSQL, put a unique constraint on the site and timestamp, then insert with INSERT ... ON CONFLICT (site_code, date) DO UPDATE. Forecast values change as the forecast is revised, so updating is usually what you want. Wrap each site's insert in a transaction so a failure halfway through does not leave a partial week. With pandas, DataFrame.to_sql alone will not give you the upsert, so you will need a custom insert method or a direct driver call.

The cleanups the reviewer flagged

The other review is mostly about style, and most of it is cheap to apply:

  • Delete comments that restate the code, such as the one above the failed_sites.empty check, and the banner-style comment blocks. Named constants such as INTERNAL_SERVER_ERROR = '500' replace them.
  • Use upper case for constants per PEP 8, so max_attempts = 10 becomes MAX_ATTEMPTS.
  • Add docstrings and type hints to each function.
  • Fix the typos in comments ('varaibles', 'calcualting', 'interupted'). They are small, but they signal that nobody reread the file.

Skip the suggestion to collapse the two lines that read the CSV and insert it into one. It is harmless, but a named intermediate DataFrame is easier to inspect when something goes wrong.

Where this approach does not fit, and what to watch for

A row-by-row script like this suits a few dozen sites and a daily run. It does not suit hundreds of thousands of rows, or any job where you need to finish within a fixed window. In that case, batch the requests if the API supports multiple coordinates, and fetch concurrently while staying under the provider's limits. Neither review covers that case, and the question does not say how many sites the real file holds, so check before deciding.

Treat 'handle all possible errors and never crash' as a warning sign. A pipeline that swallows every exception and returns None will not crash, but it will quietly produce a database with missing sites. Decide which failures should stop the run, which should be retried, and which should be recorded for a human. The script's own daily-limit branch, which exits the process, already makes that distinction. Everything else should follow the same discipline: a failure should leave a record, not a silent gap.

This article draws on Data Engineering Assignment (learning to make Data Pipeline) and answers to it (1, 2), on the Stack Exchange network, licensed under CC BY-SA 4.0.

  • #Python
  • #data pipeline
  • #database
  • #homework
  • #pandas
  • #postgresql

Comments

Add a comment
Sign in with Google to join the conversation