---
title: "Identity-keyed WeakMap cache went stale when the key object was mutated in place"
url: "https://www.dariuszparys.com/notes/weakmap-cache-stale-after-key-mutation"
author: "Dariusz Parys"
published: 2026-11-11T00:00:00.000Z
description: "A cache keyed on object identity keeps returning the first result after the key object is mutated in place, and tests that only build fresh objects do not catch it."
---

# Identity-keyed WeakMap cache went stale when the key object was mutated in place

## Context

An input spec was resolved into a derived object and memoized in a `WeakMap` keyed by the spec object, with a content-keyed map (JSON string) behind it. Later, an editor started mutating its spec in place on every confirmed action.

The lookup kept returning the object resolved the first time it saw that spec. The view looked right only while a preview was active, because previews were made with `structuredClone`, so each one was a new key. Unit tests passed because they resolved fresh objects every time. Only a screenshot showed the stale result.

## Insight

An identity-keyed cache can't tell that its key's contents have changed, so it serves the old result without any error. Memoizing on object identity is only safe if the key is never mutated after the first lookup. Pick one:

- **Copy at the boundary:** hand the consumer a copy, so every change produces a new key.
- **Freeze:** make the spec immutable once it has been resolved (`Object.freeze`, or at least a documented rule).
- **Key on content:** use a hash or serialization instead of identity.

## Snippet

```ts
const cache = new WeakMap<Spec, Derived>();
function resolve(spec: Spec): Derived {
  let d = cache.get(spec);
  if (!d) {
    d = derive(spec);
    cache.set(spec, d);
  }
  return d;
}

spec.items.push(item); // in-place mutation, same key
resolve(spec); // stale: returns the result for the old contents

resolve(structuredClone(spec)); // fix: new key, fresh result
```

Tests that only ever build fresh objects won't catch this. Add one that mutates a spec after resolving it and resolves it again.
