Identity Map

Escrito por Darjus Kazakevic · revisado el

One object per row, for the length of one transaction.

Load the same customer twice in one request and you get two objects for one row. Change one, save both, and the second save quietly undoes the first. This is a lost update. It appears only when the calls happen in a certain order, so it is hard to find.

An Identity Map is a small dictionary from id to object, scoped to one transaction. Every load checks it first. A hit returns the object already in memory; a miss reads the database and stores the result. Every mature ORM has one: Hibernate's session, Entity Framework's DbContext, SQLAlchemy's Session.

En esencia — Keep one in-memory object per database row for each transaction, so two loads of the same row return the same instance and cannot drift apart.

Cuándo recurrir a él

Recurre a él cuando

  • One request loads the same entity through more than one path
  • You write repositories by hand over raw SQL
  • You see lost updates after the same entity is saved twice

Reconsidéralo cuando

  • Read-only queries that return plain DTOs, not entities
  • Immutable value objects, which have no identity
  • Handlers that load each aggregate exactly once

How it behaves

Keyed by identity, not by query
The key is the entity type plus its primary key, not the SQL that found it. Two different queries that return the same row give back the same object.
Scoped to one transaction
The map lives exactly as long as the transaction or request. Keep it longer and it becomes a stale cache. Make it shorter and it stops preventing duplicates.
Correctness first, speed second
Its main job is to stop duplicate objects. The saved second query is a bonus. It is not an application cache: it never crosses requests or users.

Applying it well

Tie its lifetime to one transaction
Create the map when the business operation starts and drop it when the transaction ends. Most identity-map bugs are lifetime bugs: a session kept open across requests, or shared between threads.
Never share it between concurrent work
Use one map per request, thread or job. A shared map gives the same mutable object to two operations at once, and one silently changes the other's data.
Use a real cache for cross-request reads
If the goal is less database load across requests, add a cache such as Redis, with its own expiry rules. The identity map's job ends at the transaction boundary.

Errores habituales

  • Keeping the map across requests, which turns it into a cache with no invalidation.
  • Sharing one ORM session between threads. The symptom is rare, random data corruption.
  • Assuming it protects you across transactions. It does not; that is optimistic locking's job.
  • Loading 100,000 rows in one session, so every entity stays in memory until commit.