# Polyglot Persistence

**Also known as:** Several data stores · Right store per job  
**Category:** Data & Storage (Where the data lives)  
**Complexity:** 3/5  
**Guide:** https://layra4.dev/architectures/data-storage/polyglot-persistence

*Several kinds of store in one system, each picked for the job it does best.*

Polyglot persistence means one system uses several kinds of data store, each for the work it suits. Orders live in a relational database, product search runs on a search index, sessions sit in a key-value cache, and reports run on a column store. Each store is fast at its own job and poor at the others.

The cost is everything between the stores: data copied from one to another, gaps while a copy lags, and more systems to back up, patch and watch. For many products, one Postgres database with its JSON, full-text and vector features covers every need for years. Reach for a second store when you can name the query the first one cannot serve.

> **In one sentence.** Add a second kind of store only for a workload the first cannot serve, keep one source of truth for each piece of data, and feed every other copy from it.

## Origin (≈2011)

The phrase spread with the NoSQL wave, as teams added document, key-value and graph stores beside their relational database. Pramod Sadalage and Martin Fowler gave it a chapter in NoSQL Distilled (2012).

## Key concepts

### System of record vs derived store

For each piece of data, one store holds the truth. Every other store holds a derived copy: built from the source, a little behind it, and safe to drop and rebuild.

> products: Postgres (truth) → search index, cache, warehouse (derived)

### Sync paths

How a change reaches the derived stores. There are three common ways, from weakest to strongest.

- Dual write: the app writes both stores. Simple, and drifts on any partial failure
- Outbox: the change and its event commit in one transaction; a worker delivers it
- Change data capture: read every committed change from the database's log

### Ownership

Each store has one owning service or team that writes to it, runs it and decides its schema. Others read through the owner's API or a published feed, never by writing to the store directly.

### Operational surface

Each kind of store brings its own backups, upgrades, monitoring, failover, security patches and on-call know-how. The bill grows with the number of kinds you run, more than with the number of instances.

### One Postgres first

A single relational database with extensions covers documents (jsonb), full-text search (tsvector), vectors (pgvector) and time series (partitioned tables). It is rarely the best at each, often good enough, and keeps one transaction around all of them.

## Design rules

### Name the query before adding a store

Write down the query or load the current store cannot serve, with numbers: latency, volume, cost. Try an index, an extension or a replica first. Add the store only if those fail.

### One source of truth per entity

Each entity is written to exactly one store. Every other copy is fed from that store, so when copies disagree, there is one answer to which is right.

### Never dual-write from request code

A crash between two writes leaves the stores disagreeing, and nothing notices. Commit the change with an outbox event, or capture it from the log, and let a worker update the copies.

### Give every store an owner and a restore drill

A store with no owner goes unpatched and unwatched. Before adding one, name who runs it, how it is backed up, and how a derived copy is rebuilt from scratch.

## Examples

### Dual write vs one source of truth with derived copies

```typescript
// Bad: two stores written from request code. A crash or a timeout between
// the two lines leaves them disagreeing, and nothing ever notices.
export async function renameProductDualWrite(id: string, name: string): Promise<void> {
  await db.query('update products set name = $1 where id = $2', [name, id]);
  await search.upsert('products', { id, name });          // may never run
}

// Good: Postgres is the truth. The change and its event commit together.
export async function renameProduct(id: string, name: string): Promise<void> {
  await db.transaction(async (tx) => {
    await tx.query(
      'update products set name = $1, version = version + 1 where id = $2',
      [name, id],
    );
    await tx.query("insert into outbox (topic, key) values ('product.changed', $1)", [id]);
  });
}

// One worker feeds every derived store from the current row. It re-reads the
// source instead of trusting the event, so a replay always converges, and the
// version stops a slow worker from writing an older copy over a newer one.
export async function onProductChanged(event: { key: string }): Promise<void> {
  const p = await db.queryOne(
    'select id, name, price_cents, version from products where id = $1',
    [event.key],
  );
  if (!p) {
    await search.delete('products', event.key);
  } else {
    await search.upsert('products', p, { externalVersion: p.version });
  }
  await cache.del('product:' + event.key);                 // the next read refills it
}

// A rebuild is the same projection, run over every row.
export async function rebuildDerivedStores(): Promise<void> {
  for await (const row of db.stream('select id from products')) {
    await onProductChanged({ key: row.id });
  }
}
```

The first function is the common bug: two stores written in a row, with nothing to repair a gap. The second commits the change and its event together. One worker feeds every derived store from the current row, so replaying it repairs any copy, and the same code rebuilds everything.

## When to use

- A workload the main database serves badly: ranked text search, huge analytic scans, sub-millisecond hot reads
- Separate services or teams that each own their data and choose its store
- Scale or cost limits one kind of store cannot meet, with measurements to show it

## When not to use

- A small team: every kind of store is one more thing to run and learn
- The main database can still do the job with an index, an extension or a replica
- Data that must change atomically across stores, in one transaction

## Benefits

- Each workload runs on a store built for it
- Heavy reads such as search and analytics move off the main database
- Stores scale, fail and get replaced independently

## Costs

- Every derived copy lags, and needs a sync path that must not lose changes
- No transaction spans the stores, so consistency between them is eventual
- More backups, upgrades, monitoring, security reviews and on-call knowledge

## Pitfalls

- Dual writes from request code, so the search index slowly drifts from the database and no one can say by how much.
- No clear source of truth, so the cache, the index and the database each show a different current price.
- Adding a store for one feature, then keeping it for years after the feature is gone, unowned and unpatched.
- Backing up the main database but not the store that turned out to hold the only copy of some data.

## Related patterns

- [Choosing a Database](https://layra4.dev/architectures/data-storage/choosing-a-database) — how to pick each store, one workload at a time
- [Change Data Capture](https://layra4.dev/architectures/data-storage/change-data-capture) — the most reliable way to feed derived stores
- [Outbox](https://layra4.dev/architectures/infrastructure/outbox) — commit a change and its event in one transaction
- [CQRS](https://layra4.dev/architectures/architectural/cqrs) — a read model in its own store is polyglot persistence by design
- [Microservices](https://layra4.dev/architectures/system/microservices) — each service owns its data, often in a different kind of store

## Further reading

- *NoSQL Distilled* — Pramod J. Sadalage, Martin Fowler (2012) — The NoSQL data models, and a chapter on mixing them in one system.
- *Designing Data-Intensive Applications, ch. 11–12* — Martin Kleppmann (2017) — Derived data, dual writes, and keeping several stores in sync.
