<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Mesejo on Medium]]></title>
        <description><![CDATA[Stories by Daniel Mesejo on Medium]]></description>
        <link>https://medium.com/@danielmesejo?source=rss-2f9ac945a78a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W5gZbvpjh07AO_l-JBCMIA.jpeg</url>
            <title>Stories by Daniel Mesejo on Medium</title>
            <link>https://medium.com/@danielmesejo?source=rss-2f9ac945a78a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:58:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielmesejo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Crafting Resilient Scripts with Python and Prefect]]></title>
            <link>https://medium.com/inside-freenow/craft-resilient-data-scripts-with-python-and-prefect-cefb17904abd?source=rss-2f9ac945a78a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cefb17904abd</guid>
            <category><![CDATA[developer-tooling]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[negative-engineering]]></category>
            <category><![CDATA[prefect]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel Mesejo]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 16:26:49 GMT</pubDate>
            <atom:updated>2023-03-15T19:57:54.209Z</atom:updated>
            <content:encoded><![CDATA[<h4>Remove negative engineering and focus on domain logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sg01v9UUCHjhnnRI" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a software engineer, crafting a resilient script is a crucial task that can be a bit daunting. In general, you create a script that involves many parts, like loading, processing, and inserting data. In addition to the core domain logic, each component requires code for monitoring, logging, and error handling.</p><p>Although it may seem tedious to add code for these tasks, they are essential to create a pipeline that is resilient. In this post, you’ll learn how to create resilient pipelines that are easy to follow and modify by using Python and Prefect.</p><p>You don’t necessarily need to be an expert in Python or libraries like requests and pandas to benefit from this tutorial, but it would be helpful to have some familiarity with them.</p><h4>The (Toy) Problem</h4><p>Our task is to write a script that classifies a company as “luxury” if more than half of its owned cars are classified as such, and “economy” otherwise. To achieve this, we need to follow these steps:</p><ol><li>Extract a car list that includes each car’s brand, license plate, and company ID.</li><li>Transform this data by grouping it by company ID.</li><li>Update this information in batches to avoid overloading the system.</li></ol><h4>First Solution Attempt</h4><p>A first iteration of the script may look something like this:</p><pre>from itertools import islice<br><br>import click<br>import pandas as pd<br>import requests<br>import yaml<br>from sqlalchemy import create_engine<br>from yaml import SafeLoader<br><br><br>def batched(iterable, n):<br>    &quot;&quot;&quot;Batch data into tuples of length n. The last batch may be shorter.&quot;&quot;&quot;<br>    # batched(&#39;ABCDEFG&#39;, 3) --&gt; ABC DEF G<br>    if n &lt; 1:<br>        raise ValueError(&quot;n must be at least one&quot;)<br>    it = iter(iterable)<br>    while batch := tuple(islice(it, n)):<br>        yield batch<br><br><br>def config(file_path: str) -&gt; dict:<br>    with open(file_path) as infile:<br>        configuration = yaml.load(infile, Loader=SafeLoader)<br>    return configuration<br><br><br>def extract_data(configuration: dict) -&gt; pd.DataFrame:<br>    con = create_engine(configuration[&quot;datasource_url&quot;])<br>    sql = &quot;&quot;&quot;select * from cars&quot;&quot;&quot;<br>    return pd.read_sql(sql, con)<br><br><br>def transform_data(configuration: dict, data: pd.DataFrame) -&gt; list:<br>    &quot;&quot;&quot;Return the segment of a company based on the cars&quot;&quot;&quot;<br>    luxury_brands = set(configuration[&quot;luxury_brands&quot;])<br>    data[&quot;segment&quot;] = [<br>        &quot;luxury&quot; if name in luxury_brands else &quot;economy&quot; for name in data[&quot;brand&quot;]<br>    ]<br><br>    groups = data.groupby(&quot;company_id&quot;)[&quot;segment&quot;].value_counts(normalize=True)<br>    res = groups.groupby(groups.index.get_level_values(0)).idxmax()<br>    return [<br>        {&quot;company_id&quot;: str(company_id), &quot;segment&quot;: segment}<br>        for company_id, segment in res<br>    ]<br><br>def load_data(configuration: dict, data: list):<br>    for batch in batched(data, 10):<br>        batch_update(configuration, batch)<br><br><br>def batch_update(configuration, data):<br>    requests.put(configuration[&quot;url&quot;], json=list(data))<br><br><br>def main(configuration_path: str):<br>    configuration = config(configuration_path)<br>    df = extract_data(configuration)<br>    data_to_load = transform_data(configuration, df)<br>    load_data(configuration, data_to_load)<br><br><br>@click.command()<br>@click.argument(&quot;configuration_path&quot;, type=click.Path(exists=True))<br>def command(configuration_path: str):<br>    main(configuration_path)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    command()<br></pre><p>To the untrained eye, there is nothing wrong with this script but it presents two flaws:</p><ol><li>It lacks monitoring (and logging) so it gives no feedback on the state of the process.</li><li>It assumes the network is reliable, and that is a <a href="https://en.wikipedia.org/wiki/Fallacies_of_distributed_computing">fallacy</a>.</li></ol><p>To solve problem 1, we could add some logging to each component of the pipeline. For example, the load_data function would look something like this:</p><pre>import logging<br>logging.basicConfig(level=logging.INFO)<br><br>def load_data(configuration: dict, data: list):<br>    logging.info(f&quot;Starting function: {load_data.__name__}&quot;)<br>    for batch in batched(data, 10):<br>        batch_update(configuration, batch)<br>    logging.info(f&quot;Ending function: {load_data.__name__}&quot;)</pre><p>Depending on the number of components of the pipeline, this may be tedious, repetitive, and time-consuming. The code still needs to handle timeouts and failures (remember the network is unreliable). One approach could be:</p><pre>def load_data(configuration: dict, data: list):<br>    logging.info(f&quot;Starting function: {load_data.__name__}&quot;)<br>    for batch in batched(data, 10):<br>        retries = 3<br>        for _ in range(retries):<br>            try:<br>                batch_update(configuration, batch)<br>                break<br>            except RequestException as error:<br>                pass<br>    logging.info(f&quot;Ending function: {load_data.__name__}&quot;)</pre><h4>Negative Engineering</h4><p>Writing code that is not essential to the domain logic to make it work, like error recovery, monitoring, and logging is known as <a href="https://medium.com/the-prefect-blog/positive-and-negative-data-engineering-a02cb497583d">negative engineering</a>.</p><blockquote><strong><em>Negative data engineering</em></strong> is when engineers write defensive code to make sure the positive code actually runs. For example: what happens if data arrives malformed? What if the database goes down? What if the computer running the code fails? What if the code succeeds but the computer fails before it can report the success? Negative engineering is characterized by needing to anticipate this infinity of possible failures.</blockquote><p>One critical issue with negative engineering is that <strong>it diverts attention from the most critical aspect</strong>: domain logic. Not only does it reduce the productivity of software engineers by requiring them to spend valuable time on defensive issues, but it also complicates the code, making it more challenging for future software engineers to read and comprehend. Therefore, it is important to reduce negative engineering to ensure software development efficiency and maintainability.</p><h3>Removing Negative Engineering with Prefect</h3><p><a href="https://www.prefect.io/">Prefect</a> is an open-source library that enables you to orchestrate your data workflow in Python. Prefect’s mission is to eliminate negative engineering so that you can focus on the domain logic or positive engineering.</p><p>In the rest of this article, I will demonstrate how easy is to make resilient scripts by using Prefect decorators.</p><p>To install Prefect 2.0, just type on your terminal:</p><pre>pip install -U &quot;prefect&gt;=2.0b&quot;</pre><h4>Prefect Flows and Tasks</h4><p>The central components of Prefect workflows are flows and tasks. From the <a href="https://docs.prefect.io/tutorials/first-steps/">documentation</a>:</p><blockquote>A <a href="https://docs.prefect.io/concepts/flows/">flow</a> is the basis of all Prefect workflows. A flow is a Python function decorated with a @flow decorator.</blockquote><blockquote>A <a href="https://docs.prefect.io/concepts/tasks/">task</a> is a Python function decorated with a @task decorator. Tasks represent distinct pieces of work executed within a flow.</blockquote><p>In the context of our example script, flows and tasks can be defined as below:</p><pre>@task<br>def extract_data(configuration: dict) -&gt; pd.DataFrame:<br>    ....<br><br>@task<br>def transform_data(data: pd.DataFrame) -&gt; list:<br>    ....<br><br>@flow<br>def load_data(configuration: dict, data: list):<br>    ....<br><br>@task<br>def batch_update(configuration, data):<br>    ....<br><br>@flow<br>def main(configuration_path: str):<br>    ....</pre><h4>Task Retries</h4><p>To automatically retry on failure, add retries and retry_delay_seconds parameters to your task. For example:</p><pre>@task(retries=2,<br>      retry_delay_seconds=60)<br>def batch_update(configuration, data):<br>    requests.put(configuration[&quot;url&quot;], json=list(data))</pre><h4>Task Caching</h4><p>Caching stores the results of tasks that may be expensive, this is especially handy when a function task fails and is not able to recover in the middle of the flow.</p><p>To use caching in Prefect task, specify a caching key function using the parametercache_key_fn. For example:</p><pre>def cache_key_from_batch(context, parameters):<br>    return &quot;-&quot;.join(f&quot;{di[&#39;company_id&#39;]}{di[&#39;segment&#39;]}&quot; for di in parameters[&quot;data&quot;])<br><br><br>@task(retries=2,<br>      retry_delay_seconds=60,<br>      cache_key_fn=cache_key_from_batch,<br>      cache_expiration=timedelta(days=1))<br>def batch_update(configuration, data):<br>    requests.put(configuration[&quot;url&quot;], json=list(data))</pre><p>By default, a cache doesn’t expire. cache_expiration is an optional argument that indicates when the cache expires. It is a good practice to use cache_expiration to avoid permanent cache and unexpected behaviors.</p><p>In the example we used cache_key_from_batch but Prefect provides its own caching key function: task_input_hash. To cache a task based on (all) its inputs, use task_input_hash . If the task inputs do not change, Prefect will use the cached results.</p><h4>Running a flow</h4><p>To run the flow just type in the terminal:</p><pre>python demo.py config.yml</pre><p>You should see something like this:</p><pre>17:16:32.408 | INFO    | prefect.engine - Created flow run &#39;efficient-jaguar&#39; for flow &#39;main&#39;<br>17:16:32.503 | INFO    | Flow run &#39;efficient-jaguar&#39; - Created task run &#39;extract_data-0&#39; for task &#39;extract_data&#39;<br>17:16:32.504 | INFO    | Flow run &#39;efficient-jaguar&#39; - Executing &#39;extract_data-0&#39; immediately...<br>17:16:32.651 | INFO    | Task run &#39;extract_data-0&#39; - Finished in state Completed()<br>17:16:32.666 | INFO    | Flow run &#39;efficient-jaguar&#39; - Created task run &#39;transform_data-0&#39; for task &#39;transform_data&#39;<br>17:16:32.666 | INFO    | Flow run &#39;efficient-jaguar&#39; - Executing &#39;transform_data-0&#39; immediately...<br>17:16:32.713 | INFO    | Task run &#39;transform_data-0&#39; - Finished in state Completed()<br>17:16:32.766 | INFO    | Flow run &#39;efficient-jaguar&#39; - Created subflow run &#39;important-marmoset&#39; for flow &#39;load-data&#39;<br>17:16:32.805 | INFO    | Flow run &#39;important-marmoset&#39; - Created task run &#39;batch_update-0&#39; for task &#39;batch_update&#39;<br>17:16:32.805 | INFO    | Flow run &#39;important-marmoset&#39; - Executing &#39;batch_update-0&#39; immediately...<br>17:16:32.867 | INFO    | Task run &#39;batch_update-0&#39; - Finished in state Completed()<br>17:16:32.883 | INFO    | Flow run &#39;important-marmoset&#39; - Created task run &#39;batch_update-1&#39; for task &#39;batch_update&#39;</pre><p>And voila, now the script provides immediate feedback about the stage of the pipeline. If you run it again, you’ll see that the batch_update function state is Cached(type=COMPLETED), which allows the pipeline to recover in case of a failure:</p><pre>08:21:41.522 | INFO    | Task run &#39;batch_update-6&#39; - Finished in state Cached(type=COMPLETED)<br>08:21:41.535 | INFO    | Flow run &#39;military-pelican&#39; - Created task run &#39;batch_update-7&#39; for task &#39;batch_update&#39;<br>08:21:41.536 | INFO    | Flow run &#39;military-pelican&#39; - Executing &#39;batch_update-7&#39; immediately...<br>08:21:41.553 | INFO    | Task run &#39;batch_update-7&#39; - Finished in state Cached(type=COMPLETED)<br>08:21:41.567 | INFO    | Flow run &#39;military-pelican&#39; - Created task run &#39;batch_update-8&#39; for task &#39;batch_update&#39;<br>08:21:41.567 | INFO    | Flow run &#39;military-pelican&#39; - Executing &#39;batch_update-8&#39; immediately...<br>08:21:41.584 | INFO    | Task run &#39;batch_update-8&#39; - Finished in state Cached(type=COMPLETED)<br>08:21:41.599 | INFO    | Flow run &#39;military-pelican&#39; - Created task run &#39;batch_update-9&#39; for task &#39;batch_update&#39;<br>08:21:41.599 | INFO    | Flow run &#39;military-pelican&#39; - Executing &#39;batch_update-9&#39; immediately...<br>08:21:41.616 | INFO    | Task run &#39;batch_update-9&#39; - Finished in state Cached(type=COMPLETED)</pre><h4>Further Reading</h4><p>The Prefect documentation is an excellent resource to explore engaging tutorials. If you are keen on learning more, I highly recommend diving into the <a href="https://docs.prefect.io/tutorials/first-steps/">first steps of documentation</a>.</p><p>If you’re interested in playing around with the script featured in this post, you can access it, along with the infrastructure needed to run it, by clicking <a href="https://github.com/mesejo/writings/tree/main/prefect-demo">here</a>. Have fun tinkering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cefb17904abd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inside-freenow/craft-resilient-data-scripts-with-python-and-prefect-cefb17904abd">Crafting Resilient Scripts with Python and Prefect</a> was originally published in <a href="https://medium.com/inside-freenow">FREENOW Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>