Dagster Data Engineering Glossary:
Data Memoization
Memoization definition:
Memoization is a technique used to optimize computational efficiency by storing the results of expensive function calls or operations, and reusing them when the same inputs are encountered again. This approach is especially useful in situations where the cost of computation is high and the same results are needed multiple times.
While this can increase the speed of data processing, it can also lead to increased memory usage due to the storage of previous results. Therefore, it should be used judiciously, considering the trade-offs between computation time and memory usage. Therefore, it's a technique best used when the same inputs are likely to occur many times, and the benefits of faster computation outweigh the cost of additional memory use.
A common use case for memoization in data engineering could be when pulling data from an API. Data from APIs is often rate-limited, meaning you can only make a certain number of requests per minute or hour. If you're making repeated requests for the same data, memoization can help prevent hitting these rate limits by storing the results of previous requests.
Data memoization example using Python:
Please note that you need to have the necessary Python libraries installed in your Python environment to run the following code examples.
Here's a basic example in Python using the functools
library's cache
decorator, which implements memoization. We will use the Bureau of Labor Statistics’ public API to pull in Consumer Price Index data. The BLS API 2.0 allows us to make an anonymous call to pull small amounts of data so we don’t need an API key for this.
import requests
import pandas as pd
from functools import cache
import json
import time
def get_bls_data(series_id, start_year, end_year):
"""Fetch data from the BLS API for a given series, caching the results to avoid unnecessary repeated requests."""
headers = {"Content-type": "application/json"}
series = {"seriesid": [series_id], "startyear": start_year, "endyear": end_year}
p = requests.post("https://api.bls.gov/publicAPI/v2/timeseries/data/", json=series, headers=headers)
json_data = json.loads(p.text)
return json_data
@cache
def process_bls_data(series_id, start_year, end_year):
"""Fetch data from the BLS API and convert it into a pandas DataFrame."""
data = get_bls_data(series_id, start_year, end_year)
# Check if the API request was successful
if data['status'] == 'REQUEST_SUCCEEDED':
# Convert the data into a pandas DataFrame
df = pd.DataFrame(data['Results']['series'][0]['data'])
return df
else:
print(f"Failed to fetch data: {data['message']}")
# Usage
series_id = "CUUR0000SA0"
start_year = "2022"
end_year = "2023"
start_time = time.time()
df = process_bls_data(series_id, start_year, end_year)
print(df)
first_time = time.time()
df = process_bls_data(series_id, start_year, end_year)
print(df)
second_time = time.time()
print(f"Execution time was {first_time - start_time} on the first function call and {second_time - start_time} on the second one.")
This function uses the cache
decorator to memoize results. If the process_bls_data
function is called again with the same endpoint, it won't call on get_bls_data
to make a new HTTP request but will instead return the result from the cache. This can save time and prevent hitting API rate limits.
Because the BLS API is slow, you will see that the first time this function runs, it will take a while. But the second execution is almost immediate as your program is simply returning a cached result.
Eventually it will print out the most recent CPI data (twice):
year period periodName latest value footnotes
0 2023 M04 April true 303.363 [{}]
1 2023 M03 March NaN 301.836 [{}]
2 2023 M02 February NaN 300.840 [{}]
3 2023 M01 January NaN 299.170 [{}]
...
and it will indicate the difference in the execution time:
Execution time was 75.35774612426758 on the first function call and 0.006146907806396484 on the second one.
Our memoization of the API call resulted in a 12,259 X improvement in execution time.
Finally, be aware that while this can save time, it can also lead to using outdated data if the data at the endpoint changes frequently (which this example does not, it changes monthly). You should only use this approach if the data does not change frequently or if it's acceptable to use slightly outdated data.
Memoizing vs. Caching
"Caching" and "memoization" are terms used in computing that refer to the general concept of storing the results of expensive or frequently used operations to speed up subsequent accesses. Although they share similarities, there are some nuances in their usage and context.
Memoization: This term is usually used in the context of functional programming or algorithms. Memoization is a specific form of caching where the results of a deterministic function (a function that always produces the same output for the same input) are cached, so that future calls to the function with the same arguments can return the cached result rather than re-computing the value. It is often used as an optimization technique for recursive or dynamic programming algorithms. As shown in our example above, in Python, you can use the
functools.lru_cache
orfunctools.cache
decorators to automatically memoize a function.Caching: This term is used more broadly and can apply to many different layers of a system. For instance, a web browser may cache web pages so that it can display them more quickly if you visit them again. A database may cache query results to improve performance on repeated queries. Even hardware like CPUs use cache to store frequently used data close to the processor to reduce access times. In contrast to memoization, caching is not always tied to deterministic functions and can be used to store any data that may be expensive to fetch, compute, or generate.
In the context of data engineering, caching often refers to strategies to store data or computation results that are expensive to retrieve or compute, and that are expected to be re-used. This could be anything from intermediate results in a data processing pipeline, to the results of database queries, to API responses. Memoization, on the other hand, would more likely be used when writing specific functions or algorithms that are part of the data processing pipeline.