Data Memoization | Dagster Glossary

Back to Glossary Index

Data Memoization

Store the results of expensive function calls and reusing them when the same inputs occur again.

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.

  1. 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 or functools.cache decorators to automatically memoize a function.

  2. 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.


Other data engineering terms related to
Data Management:
Dagster Glossary code icon

Append

Adding or attaching new records or data items to the end of an existing dataset, database table, file, or list.
An image representing the data engineering concept of 'Append'

Archive

Move rarely accessed data to a low-cost, long-term storage solution to reduce costs. Store data for long-term retention and compliance.
An image representing the data engineering concept of 'Archive'
Dagster Glossary code icon

Augment

Add new data or information to an existing dataset to enhance its value.
An image representing the data engineering concept of 'Augment'

Auto-materialize

The automatic execution of computations and the persistence of their results.
An image representing the data engineering concept of 'Auto-materialize'

Backup

Create a copy of data to protect against loss or corruption.
An image representing the data engineering concept of 'Backup'
Dagster Glossary code icon

Batch Processing

Process large volumes of data all at once in a single operation or batch.
An image representing the data engineering concept of 'Batch Processing'
Dagster Glossary code icon

Cache

Store expensive computation results so they can be reused, not recomputed.
An image representing the data engineering concept of 'Cache'
Dagster Glossary code icon

Categorize

Organizing and classifying data into different categories, groups, or segments.
An image representing the data engineering concept of 'Categorize'
Dagster Glossary code icon

Deduplicate

Identify and remove duplicate records or entries to improve data quality.
An image representing the data engineering concept of 'Deduplicate'

Deserialize

Deserialization is essentially the reverse process of serialization. See: 'Serialize'.
An image representing the data engineering concept of 'Deserialize'
Dagster Glossary code icon

Dimensionality

Analyzing the number of features or attributes in the data to improve performance.
An image representing the data engineering concept of 'Dimensionality'
Dagster Glossary code icon

Encapsulate

The bundling of data with the methods that operate on that data.
An image representing the data engineering concept of 'Encapsulate'
Dagster Glossary code icon

Enrich

Enhance data with additional information from external sources.
An image representing the data engineering concept of 'Enrich'

Export

Extract data from a system for use in another system or application.
An image representing the data engineering concept of 'Export'
Dagster Glossary code icon

Graph Theory

A powerful tool to model and understand intricate relationships within our data systems.
An image representing the data engineering concept of 'Graph Theory'
Dagster Glossary code icon

Idempotent

An operation that produces the same result each time it is performed.
An image representing the data engineering concept of 'Idempotent'
Dagster Glossary code icon

Index

Create an optimized data structure for fast search and retrieval.
An image representing the data engineering concept of 'Index'
Dagster Glossary code icon

Integrate

Combine data from different sources to create a unified view for analysis or reporting.
An image representing the data engineering concept of 'Integrate'
Dagster Glossary code icon

Lineage

Understand how data moves through a pipeline, including its origin, transformations, dependencies, and ultimate consumption.
An image representing the data engineering concept of 'Lineage'
Dagster Glossary code icon

Linearizability

Ensure that each individual operation on a distributed system appear to occur instantaneously.
An image representing the data engineering concept of 'Linearizability'
Dagster Glossary code icon

Materialize

Executing a computation and persisting the results into storage.
An image representing the data engineering concept of 'Materialize'
Dagster Glossary code icon

Merge

Combine data from multiple datasets into a single dataset.
An image representing the data engineering concept of 'Merge'
Dagster Glossary code icon

Model

Create a conceptual representation of data objects.
An image representing the data engineering concept of 'Model'

Monitor

Track data processing metrics and system health to ensure high availability and performance.
An image representing the data engineering concept of 'Monitor'
Dagster Glossary code icon

Named Entity Recognition

Locate and classify named entities in text into pre-defined categories.
An image representing the data engineering concept of 'Named Entity Recognition'
Dagster Glossary code icon

Parse

Interpret and convert data from one format to another.
Dagster Glossary code icon

Partition

Data partitioning is a technique that data engineers and ML engineers use to divide data into smaller subsets for improved performance.
An image representing the data engineering concept of 'Partition'
Dagster Glossary code icon

Prep

Transform your data so it is fit-for-purpose.
An image representing the data engineering concept of 'Prep'
Dagster Glossary code icon

Preprocess

Transform raw data before data analysis or machine learning modeling.
Dagster Glossary code icon

Replicate

Create a copy of data for redundancy or distributed processing.

Scaling

Increasing the capacity or performance of a system to handle more data or traffic.
Dagster Glossary code icon

Schema Inference

Automatically identify the structure of a dataset.
An image representing the data engineering concept of 'Schema Inference'
Dagster Glossary code icon

Schema Mapping

Translate data from one schema or structure to another to facilitate data integration.
Dagster Glossary code icon

Secondary Index

Improve the efficiency of data retrieval in a database or storage system.
An image representing the data engineering concept of 'Secondary Index'
Dagster Glossary code icon

Software-defined Asset

A declarative design pattern that represents a data asset through code.
An image representing the data engineering concept of 'Software-defined Asset'

Synchronize

Ensure that data in different systems or databases are in sync and up-to-date.
Dagster Glossary code icon

Validate

Check data for completeness, accuracy, and consistency.
An image representing the data engineering concept of 'Validate'
Dagster Glossary code icon

Version

Maintain a history of changes to data for auditing and tracking purposes.
An image representing the data engineering concept of 'Version'