Skip to content

Polyglot Persistence: Pairing Relational SQL with Document Stores for Messaging Workloads

2 min read

Not every workload shares the same access pattern. Relational databases (PostgreSQL) shine at strict foreign keys, multi-row ACID transactions, RLS permissions, and financial ledgers. Document databases (MongoDB) shine at append-heavy, semi-structured omnichannel message streams where WhatsApp interactive cards, Instagram story replies, and voice attachments evolve rapidly.

Matching Data Shapes to the Right Store

WorkloadCharacteristicsIdeal Engine
Users, Workspaces, Roles, BillingStrict relational integrity, ACID constraints, RLSRelational SQL (PostgreSQL)
Omnichannel Messages & AttachmentsHigh write volume, polymorphic channel payloads, time-ordered scansDocument Store (or JSONB partitioned tables)
Ephemeral Presence & Pub/SubSub-millisecond fanout, TTL expirationIn-memory key-value / Pub/Sub (Redis/Valkey)
Full-Text & Vector RetrievalHybrid BM25 + HNSW semantic searchpgvector + FTS or dedicated search engine

Designing Compound Indexes for Inbox Queries

In any messaging store, the hot query is almost always: "show the 50 most recent conversations in workspace X matching status Y, sorted by last message timestamp." Follow the Equality, Sort, Range (ESR) rule when designing compound indexes:

ts
// ESR index pattern: equality fields first, sort field next, range filters last
const inboxListIndexSpec = {
  workspaceId: 1,
  status: 1,
  lastMessageAt: -1,
} as const;

Avoiding Dual-Write Inconsistencies

When a single feature spans two datastores, assign one clear system of record per entity and avoid fragile synchronous dual-writes without recovery:

  • Keep canonical identity and permissions in SQL.
  • Reference entities across stores by immutable UUIDs rather than mutable emails or slugs.
  • Use durable workflows or transactional outbox events whenever a state change in Store A must reliably project into Store B.

Next: protect third-party API keys and OAuth access tokens stored in your database in Secret Management and Envelope Encryption.

Was this helpful?