Power Query's lazy evaluation model can silently re-evaluate expensive functions thousands of times across a query graph. This expert-level lesson teaches you exactly how to architect memoization patterns in M — from two-phase pre-computation and record-based caches to composite key serialization and strategic buffering — so your functions run once and their results are reused everywhere.

You've built a sophisticated Power Query solution. It pulls data from a REST API, applies a chain of custom transformations, and feeds three separate downstream queries. Everything works. Then you open the query diagnostics and your stomach drops: the same expensive function is being called 847 times, and 840 of those calls are producing identical results. Your 45-second refresh has become a 12-minute ordeal, and your stakeholders are asking uncomfortable questions.
This is the memoization problem in Power Query, and it's one of the most misunderstood performance bottlenecks in the M ecosystem. Unlike Python or JavaScript, where you can decorate a function with @lru_cache or wrap it in a closure with a dictionary, M is a purely functional, lazy-evaluated language with no persistent mutable state. You cannot simply maintain a lookup table between calls the way you would in an imperative language. The good news is that M's evaluation model — when you understand it deeply — provides natural caching mechanisms you can deliberately engineer into your query graph. The bad news is that if you don't engineer them intentionally, the evaluator will happily recompute the same expensive result dozens of times without telling you.
By the end of this lesson, you'll have a thorough understanding of why M re-evaluates expressions, how to identify redundant computation in your query graphs, and — most importantly — how to structure your queries and custom functions to eliminate that redundancy using buffering, shared query references, and computation-collapsing patterns. You'll walk away with reusable techniques you can apply immediately to production solutions.
What you'll learn:
List.Accumulate and record-based lookup tablesTable.Buffer, List.Buffer, and Binary.Buffer strategically to pin computed results in memoryThis is an expert-level lesson. You should be comfortable with:
Before we can build caching solutions, we need to be precise about what we're actually fighting against. M's evaluation semantics are rooted in a concept borrowed from functional programming: referential transparency. Any expression that depends only on its inputs should produce the same output every time. The evaluator exploits this by being allowed to evaluate any expression at any time, in any order, and potentially multiple times if it determines that's what the dependency graph requires.
This is a feature, not a bug. It enables query folding, parallel execution, and streaming evaluation of large datasets. But it has a sharp edge: when you define a function inside a query and call it repeatedly within that same query, the M engine may choose to evaluate the function body fresh each time rather than caching its result.
Consider this pattern, which appears in countless real-world M solutions:
let
GetExchangeRate = (currencyCode as text) as number =>
let
RatesTable = Json.Document(Web.Contents("https://api.exchangerates.io/latest")),
Rates = RatesTable[rates],
Rate = Record.Field(Rates, currencyCode)
in
Rate,
SalesData = Csv.Document(File.Contents("C:\sales.csv"), [Delimiter=","]),
WithUSD = Table.AddColumn(SalesData, "USD_Amount",
each [Amount] * GetExchangeRate([CurrencyCode]))
in
WithUSD
If SalesData has 10,000 rows and they span 15 different currency codes, this code will make 10,000 HTTP requests — one per row — even though only 15 distinct results are possible. The function is pure in the mathematical sense, but nothing in this code tells the M evaluator to cache its results.
Key insight
M's evaluator does not automatically memoize function calls based on argument identity. The engine may apply its own internal optimizations in some contexts, but you cannot rely on this behavior in production. If you need a result computed only once, you must architect that explicitly.
The root cause here is that GetExchangeRate is defined as a function that contains the HTTP call in its body. Every invocation rebuilds the entire call chain from scratch. This is the first pattern to eliminate.
When Power Query professionals talk about "caching," they're often conflating two distinct problems. Getting precise about which layer you're working on determines which solution technique applies.
Layer 1: Query-graph caching — computing a named query once and sharing it across the graph. When you define a named query in the Power Query editor and reference it from multiple other queries, Power Query should compute it once and share the result. In practice, this works reliably for local data sources but can break down for web sources and when query folding interactions interfere. We'll address how to make this sharing robust.
Layer 2: Intra-query memoization — avoiding repeated evaluation of identical function arguments within a single query. This is the harder problem. Within one query, if you call a custom function 10,000 times with 15 distinct argument values, you need to collapse those 10,000 calls into 15, capture the results, and do a lookup for each row. This requires restructuring the computation entirely.
Most performance problems I've seen in complex Power Query solutions involve Layer 2. The fix is never "add a cache variable" — it's "restructure the computation so the expensive work happens at the set level, not the row level."
Let's start with the more tractable problem. When you have a query that multiple downstream queries depend on, you want to ensure that query is evaluated once and that result is shared.
The key technique here is Table.Buffer (and its siblings List.Buffer and Binary.Buffer). These functions force immediate, eager evaluation of a table and hold the result in memory, breaking the lazy evaluation chain at that point.
Here's the canonical pattern for a shared lookup table:
// Query: "ExchangeRates" (standalone query, loaded as connection only)
let
Source = Json.Document(
Web.Contents("https://api.exchangerates.io/latest",
[Headers=[#"Accept"="application/json"]])
),
RatesRecord = Source[rates],
RatesList = Record.FieldNames(RatesRecord),
RatesTable = Table.FromList(
RatesList,
Splitter.SplitByNothing(),
{"CurrencyCode"}
),
WithRates = Table.AddColumn(
RatesTable,
"Rate",
each Record.Field(RatesRecord, [CurrencyCode])
),
Typed = Table.TransformColumnTypes(
WithRates,
{{"Rate", type number}}
),
// Buffer here: this is the critical line
Buffered = Table.Buffer(Typed)
in
Buffered
Warning
Table.Buffer does not guarantee that the source query is called only once across all consuming queries in a single refresh. It guarantees that after the buffer is populated, subsequent row-by-row accesses read from memory rather than re-triggering the upstream. For true cross-query sharing, the query must be structured as a named query in the query list, not a let expression embedded inside another query.
Now in your consuming queries, you reference ExchangeRates by name and join against it rather than calling a function per row:
// Query: "SalesWithUSD"
let
SalesData = Csv.Document(
File.Contents("C:\sales.csv"),
[Delimiter=",", Columns=3, Encoding=1252]
),
TypedSales = Table.TransformColumnTypes(
SalesData,
{{"OrderID", Int64.Type}, {"Amount", type number}, {"CurrencyCode", type text}}
),
// Join against the buffered rates — no per-row function calls
WithRates = Table.NestedJoin(
TypedSales, {"CurrencyCode"},
ExchangeRates, {"CurrencyCode"},
"RateData", JoinKind.LeftOuter
),
Expanded = Table.ExpandTableColumn(
WithRates, "RateData", {"Rate"}, {"ExchangeRate"}
),
WithUSD = Table.AddColumn(
Expanded,
"USD_Amount",
each [Amount] * (if [ExchangeRate] = null then 1.0 else [ExchangeRate]),
type number
)
in
WithUSD
This is fundamentally better architecture. The HTTP call happens once, the result is buffered, and 10,000 rows get their rates through a join rather than 10,000 individual lookups. The semantics are the same; the execution cost is radically different.
For detailed treatment of Table.Buffer and related in-memory strategies, see Implementing Custom Table.Buffer and In-Memory Caching Strategies in M to Eliminate Redundant Query Recalculations. Let's move on to the more nuanced intra-query memoization problem, which requires a different toolset entirely.
Sometimes you genuinely cannot restructure your problem as a join. You have a function with complex branching logic, the input domain is not known until runtime, and the number of distinct argument values is small relative to the number of function calls. This is the scenario where you need to build a proper memoization cache inside a single query.
The fundamental challenge is that M has no mutable state. You cannot maintain a dictionary that accumulates results across function invocations the way you would in Python. What you can do is collect all the distinct argument values first, compute the results once for each, build a lookup structure, and then apply that lookup.
The technique works in two phases:
Here's a realistic scenario. You're processing employee records and need to call an internal HR API to resolve department codes to full department names, including cost center and location. The API call is moderately expensive (200ms per call), your dataset has 50,000 employee records, but there are only about 300 distinct department codes.
let
// --- Expensive function we want to memoize ---
ResolveDepartment = (deptCode as text) as record =>
let
Response = Json.Document(
Web.Contents(
"https://hr-api.internal/departments/" & deptCode,
[Headers=[#"Authorization" = "Bearer " & ApiToken]]
)
)
in
[
DeptName = Response[name],
CostCenter = Response[cost_center],
Location = Response[location]
],
// --- Source data ---
EmployeeData = Table.Buffer(
Sql.Database("sql-server", "HRDatabase", [Query="SELECT * FROM dbo.Employees"])
),
// --- Phase 1: Collect distinct department codes ---
DistinctDeptCodes = List.Buffer(
List.Distinct(Table.Column(EmployeeData, "DepartmentCode"))
),
// --- Phase 1b: Compute results for each distinct code exactly once ---
// List.Transform evaluates the function once per element
DeptResults = List.Transform(
DistinctDeptCodes,
each let
Code = _,
Result = ResolveDepartment(Code)
in
[
DepartmentCode = Code,
DeptName = Result[DeptName],
CostCenter = Result[CostCenter],
Location = Result[Location]
]
),
// --- Build a lookup table from the results ---
DeptLookup = Table.Buffer(
Table.FromRecords(DeptResults)
),
// --- Phase 2: Join instead of per-row function calls ---
WithDeptInfo = Table.NestedJoin(
EmployeeData, {"DepartmentCode"},
DeptLookup, {"DepartmentCode"},
"DeptData", JoinKind.LeftOuter
),
Expanded = Table.ExpandTableColumn(
WithDeptInfo,
"DeptData",
{"DeptName", "CostCenter", "Location"}
)
in
Expanded
The result: 300 API calls instead of 50,000. At 200ms each, that's 60 seconds versus roughly 2.8 hours. The logic is identical; the architecture is profoundly different.
Tip
Always List.Buffer your distinct values list before passing it to List.Transform. Without the buffer, the List.Distinct computation might be re-evaluated during the transform operation depending on how the evaluator resolves the dependency chain.
Sometimes your pre-computed results need to be accessed by a lookup key inside a complex expression that can't easily be restructured as a join. In this case, build a record where each field name is the key and each field value is the cached result:
let
ResolveTaxRate = (jurisdictionCode as text) as number =>
// ... expensive lookup ...
0.0, // placeholder
EmployeeData = Table.Buffer(
Sql.Database("sql-server", "PayrollDB", [Query="SELECT * FROM dbo.Payroll"])
),
DistinctJurisdictions = List.Distinct(
Table.Column(EmployeeData, "JurisdictionCode")
),
// Build a record: [CA = 0.0725, NY = 0.0685, TX = 0.0, ...]
// Record.FromList with List.Transform to generate field values
TaxRateCache = Record.FromList(
List.Transform(DistinctJurisdictions, ResolveTaxRate),
DistinctJurisdictions // field names
),
// Per-row lookup using Record.Field — O(1) access
WithTaxRate = Table.AddColumn(
EmployeeData,
"TaxRate",
each Record.Field(TaxRateCache, [JurisdictionCode]),
type number
),
WithTaxAmount = Table.AddColumn(
WithTaxRate,
"TaxAmount",
each [GrossAmount] * [TaxRate],
type number
)
in
WithTaxAmount
The TaxRateCache record is computed once during the let binding. Each row's Record.Field(TaxRateCache, [JurisdictionCode]) call reads from that already-evaluated record — a pure in-memory lookup with no re-evaluation of the tax rate function.
Key insight
In a let expression, each binding is evaluated at most once per evaluation of the outer expression. When you define TaxRateCache as a binding, its value is computed once and all references to TaxRateCache within the same let body resolve to that single computed value. This is the core mechanism that makes the record-based cache work.
The two-phase pattern above works well when you control the call site and know the input data upfront. But sometimes you're writing a utility function that will be used by others, and you want the memoization to be self-contained. Can you build a function factory that returns a memoized version of a function?
Strictly speaking, this requires state across invocations, which M doesn't support. But you can build something that achieves the same practical result for a known dataset using a closure pattern.
Here's a function factory that accepts a list of distinct argument values, pre-computes all results eagerly, and returns a lookup function:
let
// MemoizeOver: given a list of keys and a function,
// returns a function that does cached lookups
MemoizeOver = (keys as list, fn as function) as function =>
let
// Compute all results upfront
ComputedValues = List.Buffer(List.Transform(keys, fn)),
// Build the cache as a record
Cache = Record.FromList(
List.Transform(
ComputedValues,
each _ // identity — values are already computed
),
List.Transform(
keys,
each Text.From(_) // keys must be text for record field names
)
),
// Return a lookup function
LookupFn = (key as any) as any =>
Record.Field(Cache, Text.From(key))
in
LookupFn,
// Usage: build a memoized version of ResolveDepartment
// given the specific keys present in this dataset
DistinctCodes = List.Distinct(Table.Column(EmployeeData, "DepartmentCode")),
CachedResolveDept = MemoizeOver(DistinctCodes, ResolveDepartment),
// Now use it like a normal function — but results are cached
WithDept = Table.AddColumn(
EmployeeData,
"DeptName",
each (CachedResolveDept([DepartmentCode]))[DeptName]
)
in
WithDept
Warning
Record field names in M must be valid identifiers or be accessed with quoted syntax. If your keys contain spaces, special characters, or start with numbers, Record.Field will still work (since it takes the field name as a string argument), but Record.FromList with those names requires extra care. Test with Record.Field(Cache, "field name with spaces") syntax rather than the dot accessor.
This MemoizeOver factory has an important characteristic: the cache is built at the moment CachedResolveDept is bound. The expensive function is called exactly List.Count(DistinctCodes) times. After that, every call to CachedResolveDept is a pure record lookup.
For more patterns on building reusable function infrastructure, see Building a Reusable Function Library in Power Query.
A common obstacle with the record-based cache approach is that your function arguments might not be simple text values. What if your function takes a date and a currency code as arguments? You need a composite key.
The solution is to serialize the composite arguments into a canonical string key:
let
// Composite key serializer for (date, currencyCode) arguments
MakeKey = (dt as date, currencyCode as text) as text =>
Date.ToText(dt, "yyyy-MM-dd") & "|" & currencyCode,
// Expensive function: get historical exchange rate for a date and currency
GetHistoricalRate = (dt as date, currencyCode as text) as number =>
let
DateStr = Date.ToText(dt, "yyyy-MM-dd"),
Response = Json.Document(
Web.Contents(
"https://api.exchangerates.io/" & DateStr,
[Query=[base="USD", symbols=currencyCode]]
)
)
in
Record.Field(Response[rates], currencyCode),
// Build distinct argument combinations
SalesData = Table.Buffer(
Sql.Database("dwh-server", "SalesDW",
[Query="SELECT OrderDate, CurrencyCode, Amount FROM Sales"])
),
DistinctCombinations = Table.Distinct(
Table.SelectColumns(SalesData, {"OrderDate", "CurrencyCode"})
),
// Compute one result per distinct combination
WithKeys = Table.AddColumn(
DistinctCombinations,
"CacheKey",
each MakeKey([OrderDate], [CurrencyCode]),
type text
),
WithRates = Table.AddColumn(
WithKeys,
"Rate",
each GetHistoricalRate([OrderDate], [CurrencyCode]),
type number
),
// Buffer the lookup table
RateCache = Table.Buffer(WithRates),
// Apply via join using the same composite key
SalesWithKey = Table.AddColumn(
SalesData,
"CacheKey",
each MakeKey([OrderDate], [CurrencyCode]),
type text
),
WithRatesJoined = Table.NestedJoin(
SalesWithKey, {"CacheKey"},
RateCache, {"CacheKey"},
"RateData", JoinKind.LeftOuter
),
Expanded = Table.ExpandTableColumn(
WithRatesJoined, "RateData", {"Rate"}
),
Cleaned = Table.RemoveColumns(Expanded, {"CacheKey"})
in
Cleaned
The separator character in MakeKey matters. Use a character that cannot appear in either component. If dates are in ISO format and currency codes are 3-letter uppercase, a pipe | character is safe. For more complex types, consider using Text.FromBinary(Json.FromValue(_)) to serialize arbitrary M values to canonical strings.
Tip
When working with date keys, always normalize to a canonical format like yyyy-MM-dd before serialization. If your data has mixed date representations or time components you're ignoring, inconsistent key generation will produce cache misses for logically identical inputs. This is the most common bug in composite key implementations.
For some scenarios, you need to build a result set where each step depends on the previous step's cache state. This is a common pattern when processing ordered events, running totals, or any situation where previous results feed forward. The right tool here is List.Accumulate, which is M's functional fold operation.
Note
List.Accumulate is covered in depth in Advanced M: Iterators, Accumulators, and Recursive Patterns. Here we focus specifically on its use as a cache-building mechanism.
Consider a scenario where you're resolving a hierarchy: each node in an org chart has a parent, and you want to compute the full path from root to each node. Computing the path requires knowing the parent's path, which you may have already computed:
let
OrgData = Table.Buffer(
Sql.Database("hr-server", "OrgDB",
[Query="SELECT NodeID, ParentID, NodeName FROM OrgHierarchy ORDER BY Level"])
),
NodeList = Table.ToRecords(OrgData),
// State: a record where each field is a NodeID mapped to its full path
InitialState = [], // empty record = empty cache
FinalCache = List.Accumulate(
NodeList,
InitialState,
(cache, node) =>
let
NodeIDKey = Text.From(node[NodeID]),
ParentIDKey = Text.From(node[ParentID]),
// Look up parent path from cache (already computed since we sorted by Level)
ParentPath = if Record.HasFields(cache, {ParentIDKey})
then Record.Field(cache, ParentIDKey)
else "",
// Build this node's full path
ThisPath = if ParentPath = ""
then node[NodeName]
else ParentPath & " > " & node[NodeName],
// Add this node's result to the cache
UpdatedCache = Record.AddField(cache, NodeIDKey, ThisPath)
in
UpdatedCache
),
// Apply the cache back to the original table
WithPaths = Table.AddColumn(
OrgData,
"FullPath",
each Record.Field(FinalCache, Text.From([NodeID])),
type text
)
in
WithPaths
This pattern is powerful but has a critical limitation: List.Accumulate processes elements sequentially and cannot be parallelized. For large lists (tens of thousands of items), this can be slow. Use it when the sequential dependency is genuine (each step needs previous results) and not for simple per-row transformations where the join approach would work.
Warning
Record.AddField creates a new record on every iteration rather than mutating the existing one. This means each accumulation step produces a new record with one more field. For very large distinct key sets (thousands of unique values), this can produce significant memory pressure and performance degradation. If you have more than a few hundred distinct cache keys, prefer the List.Transform + Table.Buffer pattern over List.Accumulate with record state.
So far we've looked at intra-query memoization. Now let's zoom out to the full query graph and talk about how to architect your queries so shared computations are evaluated once regardless of how many downstream queries reference them.
The fundamental rule is: expensive computations should be named queries, not embedded expressions.
When you embed an expensive transformation inline inside multiple queries, each query re-runs that transformation independently. When you define it as a named query and reference it, Power Query can (and usually does) compute it once per refresh and share the result.
Here's the wrong way to structure a multi-report solution where three queries all need the same cleaned product catalog:
// In Query1 — WRONG: embedded computation
let
RawCatalog = Sql.Database("server", "db", [Query="SELECT * FROM ProductCatalog"]),
Cleaned = /* ... 15 transformation steps ... */,
Result = Table.Join(SalesData, Cleaned, ...)
in
Result
// In Query2 — WRONG: same expensive cleaning repeated
let
RawCatalog = Sql.Database("server", "db", [Query="SELECT * FROM ProductCatalog"]),
Cleaned = /* ... same 15 transformation steps ... */,
Result = Table.Join(ReturnData, Cleaned, ...)
in
Result
And the right way:
// Named query: "CleanedProductCatalog" (connection only)
let
RawCatalog = Sql.Database("server", "db", [Query="SELECT * FROM ProductCatalog"]),
Cleaned = /* ... 15 transformation steps ... */,
Buffered = Table.Buffer(Cleaned) // pin in memory
in
Buffered
// In Query1 — RIGHT: reference the named query
let
Result = Table.Join(SalesData, CleanedProductCatalog, ...)
in
Result
// In Query2 — RIGHT: same reference
let
Result = Table.Join(ReturnData, CleanedProductCatalog, ...)
in
Result
This pattern is called query factoring in ETL architecture. For a full treatment of how to orchestrate multi-stage pipelines this way, see Building Multi-Stage ETL Pipelines in Power Query M: Orchestrating Dependent Transformations with Modular Query Chains.
Key insight
Whether Power Query actually reuses the computed result of a shared named query depends on the data source type and the execution context. For DirectQuery sources, the query may be re-issued. For imported data, the result is typically shared within a single refresh. For Premium capacity in Power BI, dataset-level caching provides additional sharing. Table.Buffer strengthens the guarantee by explicitly materializing the result, but even with buffering, in some contexts (particularly multi-query refresh scenarios in Power BI Service), you may see repeated source calls. Use Query Diagnostics to verify.
None of the optimization work we've done here is valuable unless you can verify it's working. Power Query's Query Diagnostics feature is your instrument for this.
To enable diagnostics, go to the Power Query editor, click the Tools ribbon (or the View ribbon depending on your version), and find "Diagnostics." Enable "Start Diagnostics," then refresh your queries, then stop diagnostics.
You'll get two tables: a summary table and a detailed table. Focus on the detailed table. Look for these signals:
Data source requests: Each row represents a call to an external source. If you're seeing the same URL called 847 times and you expected 15, your memoization isn't working.
Exclusive duration: The time spent in that specific step, excluding time spent in steps it depends on. A step with high exclusive duration that you expected to be a simple lookup is a red flag.
Row count: If a step claiming to be a lookup is processing 50,000 rows repeatedly, it's being re-evaluated.
The diagnostics output is itself an M table, which means you can write queries against it to find the N highest-duration steps, count repeated data source requests by URL, or correlate step names with their evaluation counts. This meta-analysis approach pays off in complex solutions.
For detailed profiling techniques, see Implementing Custom Query Diagnostics and Step-Level Profiling in Power Query M.
Developers often buffer the final output table when they should be buffering the lookup or reference table. If CleanedProductCatalog is buffered but each consuming query still embeds the full cleaning logic, the buffer on the output doesn't prevent the cleaning from running twice.
Fix: Buffer the shared dependency, not the consumer.
This is a subtle but critical error:
// WRONG: cache is rebuilt on every function invocation
let
GetRate = (currencyCode as text) as number =>
let
AllRates = Json.Document(Web.Contents("https://api.rates.io/latest")),
// This runs on EVERY call to GetRate
Cache = Record.FromList(...),
Rate = Record.Field(Cache, currencyCode)
in
Rate
in
GetRate
The API call and cache construction are inside the function body. Every call to GetRate re-fetches all rates and rebuilds the cache. The cache provides no benefit.
Fix: Build the cache outside the function and pass it in, or use the two-phase pattern where you never call the expensive function at the row level at all.
List.Accumulate forces sequential evaluation. If your per-item computations are independent of each other (no result feeds into the next computation), List.Transform is better because it can potentially be evaluated in parallel.
Fix: Reserve List.Accumulate for genuinely sequential/dependent computations. Use List.Transform for independent per-item transformations.
When you add Table.Buffer to push computation in-memory, you break the query folding chain at that point. This means subsequent operations on the buffered table cannot be folded back to the data source. If the data source is a SQL server and you were relying on folding to push a WHERE clause down, buffering too early can dramatically increase the data volume loaded into memory.
Fix: Apply Table.Buffer after folding-compatible filter operations, not before. Use Query Diagnostics to verify that folding is happening where you expect it. For detailed guidance, see Implementing Custom Query Folding Logic in M: Keeping Transformations Native to the Data Source.
When building a cache using Record.FromList, the correspondence between the values list and the keys list must be exact. If List.Distinct returns codes in a different order than your List.Transform results (which it won't in practice, but can in theory when dealing with custom sorting), your cache will map the wrong rates to the wrong currencies.
Fix: Always derive keys and values from the same ordered source, and validate by spot-checking a few known mappings before deploying to production.
Even when you've defined a named query and referenced it in two places, there are scenarios where the M evaluator chooses to re-evaluate it rather than reuse the cached result — particularly when the query depends on parameters that have been changed, or when Power BI's incremental refresh logic interacts with the dependency graph.
Fix: When maximum guarantee of single evaluation is required, use Table.Buffer on the shared query and test with diagnostics under realistic refresh conditions.
Let's put everything together in a realistic scenario you can implement in your environment.
Scenario: You have a sales transactions table with 100,000 rows. Each row has a ProductSKU (500 distinct values), a StoreID (200 distinct values), and a TransactionDate. You need to enrich each row with:
Both lookups are expensive enough that per-row calls would be impractical.
Exercise Steps:
Step 1: Create a query called ProductCache. Use List.Distinct on the SKU column of your transactions to get distinct SKUs, then use List.Transform to call the product API once per SKU, build a table with Table.FromRecords, and end with Table.Buffer.
Step 2: Create a query called StoreCache. Connect to your SQL store metadata table, apply any necessary cleaning transforms, and end with Table.Buffer.
Step 3: Create your main EnrichedSales query. Load transactions into Table.Buffer. Perform two sequential Table.NestedJoin operations — first joining on ProductSKU against ProductCache, then joining on StoreID against StoreCache. Expand both joined tables.
Step 4: Enable Query Diagnostics, do a full refresh, then examine the diagnostics output. Confirm that:
Step 5: Try refactoring ProductCache to use the MemoizeOver factory pattern instead of the manual approach. Verify the diagnostics output is identical.
Challenge extension: Add a composite key scenario where you also need to look up a promotional discount rate that depends on both the StoreID and the TransactionDate month. Implement this with a composite key serializer and verify the number of distinct combinations is correctly computed.
The core insight of this entire lesson is that memoization in M is an architectural decision, not a runtime feature. Unlike languages with built-in caching decorators, M requires you to explicitly structure your computations so expensive work happens at the set level, results are pinned with buffers, and lookups happen through O(1) record field access or efficient table joins — never through repeated function calls on individual rows.
The key patterns we've covered:
List.Transform → build a lookup table → join or lookup per rowRecord.FromList with text keys provides O(1) lookup for single-argument function memoizationList.Accumulate for sequential caches: When later results depend on earlier ones, fold over the input accumulating cache stateTable.Buffer placement: Buffer after folding-compatible operations to retain query folding benefits while pinning resultsWhere to go from here: If you're working with recursive computations that need memoization — like hierarchy traversal or Fibonacci-style sequences — dig into Advanced M: Iterators, Accumulators, and Recursive Patterns for techniques that extend the patterns here into recursive territory. If you're building a library of memoizable utility functions for a team, Building a Reusable Function Library in Power Query covers the packaging and documentation patterns you'll need. And if you want to get deeper on how the evaluation engine makes decisions about when to re-evaluate, Understanding M Language Query Evaluation: Lazy Evaluation, Dependency Graphs, and Step Ordering in Power Query will round out your mental model of what the engine is actually doing when it encounters your carefully crafted cache structures.
Memoization in M rewards architectural thinking. Once you stop trying to cache at the call site and start building computations that naturally collapse redundant work, you'll find that the right solution is often also the most readable one.