Skip to content

Dependency graphs and incremental recalculation

A graph of which cells read which others lets a spreadsheet recompute just the formulas a change touched, in an order where each input is ready, and flag a formula that reaches back to itself.

On this page

What it is

A spreadsheet is a graph. Each cell is a node, and a formula draws an edge from each cell it reads to itself: C1 = A1 + B1 gives A1 and B1 edges into C1. In the design on this page the engine stores that graph in both directions. Parsing a formula yields the cells it references by name (its precedents), which tell the engine what must be finished before it evaluates; the formulas that read a cell (its dependents) tell it what to revisit when the cell changes. Microsoft's recalculation documentation, written for Excel 2013, describes calculation as three stages: build a dependency tree, derive a calculation chain from it that lists the formula cells in the order they should run, then recalculate.

Dirty marking is the incremental part. When a value or a formula changes, Excel marks all direct and indirect dependents as dirty: if B1 reads A1 and C1 reads B1, editing A1 dirties both B1 and C1. On the next recalculation it reevaluates the dirty cells in calculation-chain order, B1 before C1, and if it meets a formula whose input hasn't been computed yet, it moves that formula later in the chain. In automatic mode that recalculation starts as soon as the marking is done; in manual mode it waits for the user. Since Excel 2007, parts of the chain that don't depend on each other can run on separate threads.

Topological order is the order the chain approximates: a cell runs after everything it reads. HyperFormula, a spreadsheet formula engine, notes that such an order exists exactly when the graph has no cycle, and that there are usually many valid ones. A simple way to produce one for the dirty set: for each dirty cell, count how many of its inputs are also dirty and unfinished. Put the cells with a count of zero in a queue. Pop one, evaluate it, and lower the count of each dirty reader; a reader that reaches zero joins the queue. Cells that were not dirty keep their cached values and aren't touched.

ts
function recalc(changed: CellId, graph: Graph, values: Map<CellId, Value>) {
  // 1. mark: all direct and indirect readers of the edit
  const dirty = new Set<CellId>();
  const stack = [...graph.readersOf(changed)];
  while (stack.length) {
    const c = stack.pop()!;
    if (dirty.has(c)) continue; // seen already: a diamond, or a cycle
    dirty.add(c);
    stack.push(...graph.readersOf(c));
  }
  // 2. count unfinished dirty inputs per dirty cell
  const pending = new Map<CellId, number>();
  for (const c of dirty) {
    pending.set(c, [...graph.inputsOf(c)].filter(i => dirty.has(i)).length);
  }
  // 3. evaluate in an order where inputs are ready;
  // touched = dirty cells with at least one input that actually changed
  const touched = new Set<CellId>(graph.readersOf(changed));
  const ready = [...dirty].filter(c => pending.get(c) === 0);
  while (ready.length) {
    const c = ready.shift()!;
    let valueChanged = false;
    if (touched.has(c)) {
      const next = evaluate(c, values);
      valueChanged = next !== values.get(c);
      values.set(c, next);
    } // else: early cutoff, keep the cached value
    pending.delete(c);
    for (const r of graph.readersOf(c)) {
      if (!pending.has(r)) continue;
      if (valueChanged) touched.add(r);
      pending.set(r, pending.get(r)! - 1);
      if (pending.get(r) === 0) ready.push(r);
    }
  }
  // 4. whatever is left didn't reach zero: it is in or behind a cycle
  for (const c of pending.keys()) values.set(c, CYCLE_ERROR);
}

A cycle is a cell that depends, directly or through other cells, on itself. The queue above doesn't reach it, because at least one of its inputs stays unfinished, so it is left over at the end along with everything downstream of it. The two products below warn about it rather than compute it, unless the user opts into iterative calculation. Excel detects the circular reference and warns the user the first time one appears in a session; after the warning the cell can show 0 or its last computed value, and the status bar lists Circular References with a cell address. A tutorial on Google's spreadsheet app reports that it shows #REF! in the cell with a hover message saying a circular dependency was detected.

When to use it

Reach for a dependency graph when many derived values hang off a few inputs and recomputing all of them per edit is too slow to keep up with typing: spreadsheets, computed state in a UI, a build system's targets. The payoff grows with the gap between the size of the spreadsheet and the size of the affected set. Editing one cell that a thousand formulas read is still a thousand evaluations, while editing a cell nothing reads triggers no formula work beyond the lookup and any volatile cells.

Decide whether to push or pull. Excel's automatic mode pushes: marking finishes, then recalculation runs at once. The TC39 Signals proposal (Stage 1 as of this reading) describes the pull side, which frontend frameworks use for computed state: a computed signal is not recomputed when a dependency changes, but when something reads it; it caches its last value and skips the work if no dependency changed since; and a read topologically sorts the possibly dirty part of the graph so nothing runs twice. Pulling suits a grid where most formulas are scrolled out of view: mark them dirty cheaply and evaluate when a row comes on screen. Pushing suits a spreadsheet where visible values must be current the moment the edit lands.

Add an early cutoff when values often don't change. A reader has to be marked dirty before you know whether its input will change, but once the input is reevaluated and compares equal to its old value, a reader with no other changed input can keep its cached value and skip evaluation. The Signals proposal's cached computed values work on this principle: unchanged dependencies mean no recomputation. The cost is an equality check per cell, which is cheap for numbers and strings and needs care for arrays.

Budget for volatile functions. Excel reevaluates any cell holding NOW, TODAY, RANDBETWEEN, OFFSET or INDIRECT each time it recalculates, together with all of its dependents, whatever was edited, and the documentation advises using them sparingly because they slow recalculation. In your own engine, a volatile cell is a node that starts each pass dirty. A function whose reference is computed at run time has edges you can't know until it runs; the simple way to stay correct in your own engine is to treat such a cell as volatile too.

When not to

For a small spreadsheet with cheap formulas, a full recompute in topological order on each edit is often simpler and may be fast enough. Dirty tracking adds bookkeeping that can drift from the truth (a missed edge means a stale cell), and the bug is hard to see because the grid mostly looks right. Start with the full pass, measure it against your frame budget, and add dirty marking when the pass stops fitting.

When the cycle is intended, as in some financial or engineering models, iteration is the right tool rather than an error. Excel offers an iterative calculation setting that repeats the circular cells and, by default, stops after 100 iterations or when values move by less than 0.001. Microsoft's own guidance is to keep it off for most worksheets. Our reason to agree: with iteration on, an accidental cycle produces a number instead of a warning. An engine for a general audience should report the cycle and make iteration an explicit opt-in.

A big range reference strains the graph. A formula that sums a whole column would add one edge per cell if each cell points at the formula directly, and in that design inserting a row means touching those edges. A simpler design for a first version is to treat the range as a single node: the cells in it point at the range node, and the formula reads the range. Our advice in an interview: name that cost and the range node fix, then move on.

Don't rebuild the whole graph on each keystroke. Reparse the edited formula, remove its old edges, add the new ones, and then run the dirty pass. HyperFormula goes further for structural edits like inserting rows: it records the operation and postpones rewriting the affected formulas until one is displayed or recalculated.

Compared

StrategyHow it worksRight whenWhat it costs

Full recompute

Evaluate all formulas in one topological pass

Formulas are few and cheap; simplicity matters more than speed

Work grows with spreadsheet size, not edit size

Dirty marking, eager push

Mark readers dirty, recompute them at once, as Excel's automatic mode does

Visible values must be current right after the edit

Each edit pays for its whole affected set, on screen or not

Dirty marking, lazy pull

Mark dirty, compute on read, cache the result, as computed signals do

Most derived values are not read right away, such as off-screen rows

Each read checks dirtiness; the first read after an edit pays the cost

Iterative calculation

Repeat the circular cells until change is below a threshold or an iteration cap

Cycles are intentional, as in some financial models

May not converge; masks accidental cycles

Range node

One node stands for a range; cells point at it

Large SUM or AVERAGE ranges; row inserts

An extra hop per range read; the node must track membership

In a picture

dirtydirtyA1: 12B1: =A1*2D1: 5C1: =B1+D1

Step 1 of 4

The graph before the edit

B1 reads A1, and C1 reads both B1 and D1. Edges point from an input to the formula that reads it.

How to say it in an interview

The common mistake

Quiz

B1 and C1 both read A1, and D1 reads B1 and C1. A1 changes. With a count of unfinished dirty inputs per cell, how many times is D1 evaluated, and when?
The ready queue empties but several dirty cells still have a nonzero count. What does that tell you?
B1 is =ROUND(A1, 0) and C1 is =B1 * 10. A1 changes from 2.1 to 2.2, so B1 recomputes to 2 again. What should happen to C1?
A spreadsheet has one cell with =NOW() and fifty formulas that read it. Someone edits an unrelated cell. In Excel's model, what runs?

Questions that use this

Hear it in

Related

Sources

  1. Microsoft Learn: Excel Recalculation (Excel 2013)
  2. Microsoft Support: Remove or allow a circular reference in Excel
  3. HyperFormula docs (v3.5.0): Key concepts
  4. TC39: JavaScript Signals standard proposal (README)
  5. Spreadsheet Class: How to fix the Circular dependency detected error in Google Sheets
Sign in to report a mistake